blob: 745c81bd08007e7779e058f737d9bd6d2e385958 [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;
Michael Jurka18014792010-10-14 09:01:34 -070021import android.animation.ObjectAnimator;
Adam Cohenbfbfd262011-06-13 16:55:12 -070022import android.animation.PropertyValuesHolder;
Chet Haase00397b12010-10-07 11:13:10 -070023import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070024import android.animation.ValueAnimator;
25import android.animation.ValueAnimator.AnimatorUpdateListener;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080026import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040027import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070028import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070029import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070030import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080031import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070032import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070033import android.graphics.Point;
34import android.graphics.PointF;
Adam Cohenb5ba0972011-09-07 18:02:31 -070035import android.graphics.PorterDuff;
36import android.graphics.PorterDuffXfermode;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080037import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080038import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070039import android.graphics.drawable.Drawable;
Adam Cohenb5ba0972011-09-07 18:02:31 -070040import android.graphics.drawable.NinePatchDrawable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070042import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.view.MotionEvent;
44import android.view.View;
45import android.view.ViewDebug;
46import android.view.ViewGroup;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070048import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070049import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080050
Adam Cohen66396872011-04-15 17:50:36 -070051import com.android.launcher.R;
Adam Cohen69ce2e52011-07-03 19:25:21 -070052import com.android.launcher2.FolderIcon.FolderRingAnimator;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070053
Adam Cohen69ce2e52011-07-03 19:25:21 -070054import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070055import java.util.Arrays;
Adam Cohenbfbfd262011-06-13 16:55:12 -070056import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080057import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070058
Michael Jurkabdb5c532011-02-01 15:05:06 -080059public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070060 static final String TAG = "CellLayout";
61
Winson Chung4b825dcd2011-06-19 12:41:22 -070062 private int mOriginalCellWidth;
63 private int mOriginalCellHeight;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064 private int mCellWidth;
65 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070066
Adam Cohend22015c2010-07-26 22:02:18 -070067 private int mCountX;
68 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069
Adam Cohen234c4cd2011-07-17 21:03:04 -070070 private int mOriginalWidthGap;
71 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080072 private int mWidthGap;
73 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070074 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080075 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080076
77 private final Rect mRect = new Rect();
78 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070079
Patrick Dubroyde7658b2010-09-27 11:15:43 -070080 // These are temporary variables to prevent having to allocate a new object just to
81 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070082 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070083 private final int[] mTmpPoint = new int[2];
84 private final PointF mTmpPointF = new PointF();
Adam Cohen69ce2e52011-07-03 19:25:21 -070085 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070086
The Android Open Source Project31dd5032009-03-03 19:32:27 -080087 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080088 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070089 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
Michael Jurkadee05892010-07-27 10:01:56 -070091 private OnTouchListener mInterceptTouchListener;
92
Adam Cohen69ce2e52011-07-03 19:25:21 -070093 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070094 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070095
Adam Cohenb5ba0972011-09-07 18:02:31 -070096 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070097 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070098 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070099
Michael Jurka33945b22010-12-21 18:19:38 -0800100 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -0800101 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700102 private Drawable mOverScrollForegroundDrawable;
103 private Drawable mOverScrollLeft;
104 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700105 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700106 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700107 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700108
Michael Jurka33945b22010-12-21 18:19:38 -0800109 // If we're actively dragging something over this screen, mIsDragOverlapping is true
110 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700111 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700112
Winson Chung150fbab2010-09-29 17:14:26 -0700113 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700114 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800115 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700116 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700117 private InterruptibleInOutAnimator[] mDragOutlineAnims =
118 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700119
120 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700121 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700122 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700123
Patrick Dubroy96864c32011-03-10 17:17:23 -0800124 private BubbleTextView mPressedOrFocusedIcon;
125
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700126 private Drawable mCrosshairsDrawable = null;
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700127 private InterruptibleInOutAnimator mCrosshairsAnimator = null;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700128 private float mCrosshairsVisibility = 0.0f;
129
Adam Cohen482ed822012-03-02 14:15:13 -0800130 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
131 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohenbfbfd262011-06-13 16:55:12 -0700132
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700133 // When a drag operation is in progress, holds the nearest cell to the touch point
134 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800135
Joe Onorato4be866d2010-10-10 11:26:02 -0700136 private boolean mDragging = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800137 private boolean mItemLocationsDirty = false;
Joe Onorato4be866d2010-10-10 11:26:02 -0700138
Patrick Dubroyce34a972010-10-19 10:34:32 -0700139 private TimeInterpolator mEaseOutInterpolator;
Michael Jurka8c920dd2011-01-20 14:16:56 -0800140 private CellLayoutChildren mChildren;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700141
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800142 private boolean mIsHotseat = false;
Winson Chungeecf02d2012-03-02 17:14:58 -0800143 private float mChildScale = 1f;
144 private float mHotseatChildScale = 1f;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800145
Adam Cohen482ed822012-03-02 14:15:13 -0800146 public static final int MODE_DRAG_OVER = 0;
147 public static final int MODE_ON_DROP = 1;
148 public static final int MODE_ON_DROP_EXTERNAL = 2;
149 public static final int MODE_ACCEPT_DROP = 3;
150 private static final boolean DESTRUCTIVE_REORDER = true;
151 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
152
153 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
154 private Rect mOccupiedRect = new Rect();
155 private int[] mDirectionVector = new int[2];
156
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800157 public CellLayout(Context context) {
158 this(context, null);
159 }
160
161 public CellLayout(Context context, AttributeSet attrs) {
162 this(context, attrs, 0);
163 }
164
165 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
166 super(context, attrs, defStyle);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700167
168 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
169 // the user where a dragged item will land when dropped.
170 setWillNotDraw(false);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700171
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
173
Winson Chung4b825dcd2011-06-19 12:41:22 -0700174 mOriginalCellWidth =
175 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
176 mOriginalCellHeight =
177 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700178 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
179 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700180 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700181 mCountX = LauncherModel.getCellCountX();
182 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700183 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800184 mTmpOccupied = new boolean[mCountX][mCountY];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185
186 a.recycle();
187
188 setAlwaysDrawnWithCacheEnabled(false);
189
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700190 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700191
Winson Chung967289b2011-06-30 18:09:30 -0700192 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700193 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800194
Adam Cohenb5ba0972011-09-07 18:02:31 -0700195 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
196 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
197 mForegroundPadding =
198 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800199
Winson Chungb26f3d62011-06-02 10:49:29 -0700200 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700201 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700202
Winson Chungeecf02d2012-03-02 17:14:58 -0800203 int iconScale = res.getInteger(R.integer.app_icon_scale_percent);
204 if (iconScale >= 0) {
205 mChildScale = iconScale / 100f;
206 }
207 int hotseatIconScale = res.getInteger(R.integer.app_icon_hotseat_scale_percent);
208 if (hotseatIconScale >= 0) {
209 mHotseatChildScale = hotseatIconScale / 100f;
210 }
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800211
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700212 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700213
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700214 mCrosshairsDrawable = res.getDrawable(R.drawable.gardening_crosshairs);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700215 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700216
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700217 // Set up the animation for fading the crosshairs in and out
218 int animDuration = res.getInteger(R.integer.config_crosshairsFadeInTime);
Patrick Dubroy49250ad2010-10-08 15:33:52 -0700219 mCrosshairsAnimator = new InterruptibleInOutAnimator(animDuration, 0.0f, 1.0f);
Chet Haase472b2812010-10-14 07:02:04 -0700220 mCrosshairsAnimator.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700221 public void onAnimationUpdate(ValueAnimator animation) {
222 mCrosshairsVisibility = ((Float) animation.getAnimatedValue()).floatValue();
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700223 invalidate();
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700224 }
225 });
Patrick Dubroyce34a972010-10-19 10:34:32 -0700226 mCrosshairsAnimator.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700227
Winson Chungb8c69f32011-10-19 21:36:08 -0700228 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700229 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800230 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700231 }
232
233 // When dragging things around the home screens, we show a green outline of
234 // where the item will land. The outlines gradually fade out, leaving a trail
235 // behind the drag path.
236 // Set up all the animations that are used to implement this fading.
237 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700238 final float fromAlphaValue = 0;
239 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700240
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700241 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700242
243 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700244 final InterruptibleInOutAnimator anim =
245 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700246 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700247 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700248 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700249 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700250 final Bitmap outline = (Bitmap)anim.getTag();
251
252 // If an animation is started and then stopped very quickly, we can still
253 // get spurious updates we've cleared the tag. Guard against this.
254 if (outline == null) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700255 if (false) {
256 Object val = animation.getAnimatedValue();
257 Log.d(TAG, "anim " + thisIndex + " update: " + val +
258 ", isStopped " + anim.isStopped());
259 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700260 // Try to prevent it from continuing to run
261 animation.cancel();
262 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700263 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800264 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700265 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700266 }
267 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700268 // The animation holds a reference to the drag outline bitmap as long is it's
269 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700270 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700271 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700272 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700273 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700274 anim.setTag(null);
275 }
276 }
277 });
278 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700279 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700280
Michael Jurka18014792010-10-14 09:01:34 -0700281 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700282 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800283
Michael Jurka8c920dd2011-01-20 14:16:56 -0800284 mChildren = new CellLayoutChildren(context);
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700285 mChildren.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Michael Jurka8c920dd2011-01-20 14:16:56 -0800286 addView(mChildren);
Michael Jurka18014792010-10-14 09:01:34 -0700287 }
288
Michael Jurkaf6440da2011-04-05 14:50:34 -0700289 static int widthInPortrait(Resources r, int numCells) {
290 // We use this method from Workspace to figure out how many rows/columns Launcher should
291 // have. We ignore the left/right padding on CellLayout because it turns out in our design
292 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700293 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700294 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
295 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700296
Winson Chung4b825dcd2011-06-19 12:41:22 -0700297 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700298 }
299
Michael Jurkaf6440da2011-04-05 14:50:34 -0700300 static int heightInLandscape(Resources r, int numCells) {
301 // We use this method from Workspace to figure out how many rows/columns Launcher should
302 // have. We ignore the left/right padding on CellLayout because it turns out in our design
303 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700304 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700305 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
306 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700307
Winson Chung4b825dcd2011-06-19 12:41:22 -0700308 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700309 }
310
Adam Cohen2801caf2011-05-13 20:57:39 -0700311 public void enableHardwareLayers() {
Adam Cohen7ef91832011-08-25 14:06:02 -0700312 mChildren.enableHardwareLayers();
Adam Cohen2801caf2011-05-13 20:57:39 -0700313 }
314
315 public void setGridSize(int x, int y) {
316 mCountX = x;
317 mCountY = y;
318 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800319 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen76fc0852011-06-17 13:26:23 -0700320 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700321 }
322
Patrick Dubroy96864c32011-03-10 17:17:23 -0800323 private void invalidateBubbleTextView(BubbleTextView icon) {
324 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700325 invalidate(icon.getLeft() + getPaddingLeft() - padding,
326 icon.getTop() + getPaddingTop() - padding,
327 icon.getRight() + getPaddingLeft() + padding,
328 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800329 }
330
Adam Cohenb5ba0972011-09-07 18:02:31 -0700331 void setOverScrollAmount(float r, boolean left) {
332 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
333 mOverScrollForegroundDrawable = mOverScrollLeft;
334 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
335 mOverScrollForegroundDrawable = mOverScrollRight;
336 }
337
338 mForegroundAlpha = (int) Math.round((r * 255));
339 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
340 invalidate();
341 }
342
Patrick Dubroy96864c32011-03-10 17:17:23 -0800343 void setPressedOrFocusedIcon(BubbleTextView icon) {
344 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
345 // requires an expanded clip rect (due to the glow's blur radius)
346 BubbleTextView oldIcon = mPressedOrFocusedIcon;
347 mPressedOrFocusedIcon = icon;
348 if (oldIcon != null) {
349 invalidateBubbleTextView(oldIcon);
350 }
351 if (mPressedOrFocusedIcon != null) {
352 invalidateBubbleTextView(mPressedOrFocusedIcon);
353 }
354 }
355
Winson Chung6e314082011-01-27 16:46:51 -0800356 public CellLayoutChildren getChildrenLayout() {
357 if (getChildCount() > 0) {
358 return (CellLayoutChildren) getChildAt(0);
359 }
360 return null;
361 }
362
Michael Jurka33945b22010-12-21 18:19:38 -0800363 void setIsDragOverlapping(boolean isDragOverlapping) {
364 if (mIsDragOverlapping != isDragOverlapping) {
365 mIsDragOverlapping = isDragOverlapping;
366 invalidate();
367 }
368 }
369
370 boolean getIsDragOverlapping() {
371 return mIsDragOverlapping;
372 }
373
Adam Cohenebea84d2011-11-09 17:20:41 -0800374 protected void setOverscrollTransformsDirty(boolean dirty) {
375 mScrollingTransformsDirty = dirty;
376 }
377
378 protected void resetOverscrollTransforms() {
379 if (mScrollingTransformsDirty) {
380 setOverscrollTransformsDirty(false);
381 setTranslationX(0);
382 setRotationY(0);
383 // It doesn't matter if we pass true or false here, the important thing is that we
384 // pass 0, which results in the overscroll drawable not being drawn any more.
385 setOverScrollAmount(0, false);
386 setPivotX(getMeasuredWidth() / 2);
387 setPivotY(getMeasuredHeight() / 2);
388 }
389 }
390
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700391 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700392 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700393 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
394 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
395 // When we're small, we are either drawn normally or in the "accepts drops" state (during
396 // a drag). However, we also drag the mini hover background *over* one of those two
397 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700398 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700399 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800400
401 if (mIsDragOverlapping) {
402 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700403 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700404 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700405 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700406 }
Michael Jurka33945b22010-12-21 18:19:38 -0800407
408 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
409 bg.setBounds(mBackgroundRect);
410 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700411 }
Romain Guya6abce82009-11-10 02:54:41 -0800412
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700413 if (mCrosshairsVisibility > 0.0f) {
414 final int countX = mCountX;
415 final int countY = mCountY;
416
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700417 final float MAX_ALPHA = 0.4f;
418 final int MAX_VISIBLE_DISTANCE = 600;
419 final float DISTANCE_MULTIPLIER = 0.002f;
420
421 final Drawable d = mCrosshairsDrawable;
422 final int width = d.getIntrinsicWidth();
423 final int height = d.getIntrinsicHeight();
424
Winson Chung4b825dcd2011-06-19 12:41:22 -0700425 int x = getPaddingLeft() - (mWidthGap / 2) - (width / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700426 for (int col = 0; col <= countX; col++) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700427 int y = getPaddingTop() - (mHeightGap / 2) - (height / 2);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700428 for (int row = 0; row <= countY; row++) {
429 mTmpPointF.set(x - mDragCenter.x, y - mDragCenter.y);
430 float dist = mTmpPointF.length();
431 // Crosshairs further from the drag point are more faint
432 float alpha = Math.min(MAX_ALPHA,
433 DISTANCE_MULTIPLIER * (MAX_VISIBLE_DISTANCE - dist));
434 if (alpha > 0.0f) {
435 d.setBounds(x, y, x + width, y + height);
436 d.setAlpha((int) (alpha * 255 * mCrosshairsVisibility));
437 d.draw(canvas);
438 }
439 y += mCellHeight + mHeightGap;
440 }
441 x += mCellWidth + mWidthGap;
442 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700443 }
Winson Chung150fbab2010-09-29 17:14:26 -0700444
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700445 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700446 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700447 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700448 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800449 final Rect r = mDragOutlines[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700450 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700451 paint.setAlpha((int)(alpha + .5f));
Adam Cohend41fbf52012-02-16 23:53:59 -0800452 canvas.drawBitmap(b, null, r, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700453 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700454 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800455
456 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
457 // requires an expanded clip rect (due to the glow's blur radius)
458 if (mPressedOrFocusedIcon != null) {
459 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
460 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
461 if (b != null) {
462 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700463 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
464 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800465 null);
466 }
467 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700468
Adam Cohen482ed822012-03-02 14:15:13 -0800469 if (DEBUG_VISUALIZE_OCCUPIED) {
470 int[] pt = new int[2];
471 ColorDrawable cd = new ColorDrawable(Color.RED);
472 cd.setBounds(0, 0, 80, 80);
473 for (int i = 0; i < mCountX; i++) {
474 for (int j = 0; j < mCountY; j++) {
475 if (mOccupied[i][j]) {
476 cellToPoint(i, j, pt);
477 canvas.save();
478 canvas.translate(pt[0], pt[1]);
479 cd.draw(canvas);
480 canvas.restore();
481 }
482 }
483 }
484 }
485
Adam Cohen69ce2e52011-07-03 19:25:21 -0700486 // The folder outer / inner ring image(s)
487 for (int i = 0; i < mFolderOuterRings.size(); i++) {
488 FolderRingAnimator fra = mFolderOuterRings.get(i);
489
490 // Draw outer ring
491 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
492 int width = (int) fra.getOuterRingSize();
493 int height = width;
494 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
495
496 int centerX = mTempLocation[0] + mCellWidth / 2;
497 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
498
499 canvas.save();
500 canvas.translate(centerX - width / 2, centerY - height / 2);
501 d.setBounds(0, 0, width, height);
502 d.draw(canvas);
503 canvas.restore();
504
505 // Draw inner ring
506 d = FolderRingAnimator.sSharedInnerRingDrawable;
507 width = (int) fra.getInnerRingSize();
508 height = width;
509 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
510
511 centerX = mTempLocation[0] + mCellWidth / 2;
512 centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
513 canvas.save();
514 canvas.translate(centerX - width / 2, centerY - width / 2);
515 d.setBounds(0, 0, width, height);
516 d.draw(canvas);
517 canvas.restore();
518 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700519
520 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
521 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
522 int width = d.getIntrinsicWidth();
523 int height = d.getIntrinsicHeight();
524
525 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
526 int centerX = mTempLocation[0] + mCellWidth / 2;
527 int centerY = mTempLocation[1] + FolderRingAnimator.sPreviewSize / 2;
528
529 canvas.save();
530 canvas.translate(centerX - width / 2, centerY - width / 2);
531 d.setBounds(0, 0, width, height);
532 d.draw(canvas);
533 canvas.restore();
534 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700535 }
536
Adam Cohenb5ba0972011-09-07 18:02:31 -0700537 @Override
538 protected void dispatchDraw(Canvas canvas) {
539 super.dispatchDraw(canvas);
540 if (mForegroundAlpha > 0) {
541 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
542 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
543 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
544 mOverScrollForegroundDrawable.draw(canvas);
545 p.setXfermode(null);
546 }
547 }
548
Adam Cohen69ce2e52011-07-03 19:25:21 -0700549 public void showFolderAccept(FolderRingAnimator fra) {
550 mFolderOuterRings.add(fra);
551 }
552
553 public void hideFolderAccept(FolderRingAnimator fra) {
554 if (mFolderOuterRings.contains(fra)) {
555 mFolderOuterRings.remove(fra);
556 }
557 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700558 }
559
Adam Cohenc51934b2011-07-26 21:07:43 -0700560 public void setFolderLeaveBehindCell(int x, int y) {
561 mFolderLeaveBehindCell[0] = x;
562 mFolderLeaveBehindCell[1] = y;
563 invalidate();
564 }
565
566 public void clearFolderLeaveBehind() {
567 mFolderLeaveBehindCell[0] = -1;
568 mFolderLeaveBehindCell[1] = -1;
569 invalidate();
570 }
571
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700572 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700573 public boolean shouldDelayChildPressedState() {
574 return false;
575 }
576
577 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700578 public void cancelLongPress() {
579 super.cancelLongPress();
580
581 // Cancel long press for all children
582 final int count = getChildCount();
583 for (int i = 0; i < count; i++) {
584 final View child = getChildAt(i);
585 child.cancelLongPress();
586 }
587 }
588
Michael Jurkadee05892010-07-27 10:01:56 -0700589 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
590 mInterceptTouchListener = listener;
591 }
592
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800593 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700594 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800595 }
596
597 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700598 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 }
600
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800601 public void setIsHotseat(boolean isHotseat) {
602 mIsHotseat = isHotseat;
603 }
604
Winson Chungeecf02d2012-03-02 17:14:58 -0800605 public float getChildrenScale() {
606 return mIsHotseat ? mHotseatChildScale : mChildScale;
607 }
608
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700609 public boolean addViewToCellLayout(
610 View child, int index, int childId, LayoutParams params, boolean markCells) {
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800611 return addViewToCellLayout(child, index, childId, params, markCells, false);
612 }
613
Winson Chungeecf02d2012-03-02 17:14:58 -0800614 private void scaleChild(BubbleTextView bubbleChild, float pivot, float scale) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800615 // If we haven't measured the child yet, do it now
616 // (this happens if we're being dropped from all-apps
617 if (bubbleChild.getLayoutParams() instanceof LayoutParams &&
618 (bubbleChild.getMeasuredWidth() | bubbleChild.getMeasuredHeight()) == 0) {
619 getChildrenLayout().measureChild(bubbleChild);
620 }
621 int measuredWidth = bubbleChild.getMeasuredWidth();
622 int measuredHeight = bubbleChild.getMeasuredHeight();
623
Andrew Flynnbc239a12012-03-06 11:39:49 -0800624 bubbleChild.setScaleX(scale);
625 bubbleChild.setScaleY(scale);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800626 }
627
628 private void resetChild(BubbleTextView bubbleChild) {
629 bubbleChild.setScaleX(1f);
630 bubbleChild.setScaleY(1f);
Andrew Flynnbc239a12012-03-06 11:39:49 -0800631
632 bubbleChild.setTextColor(getResources().getColor(R.color.workspace_icon_text_color));
633 }
634
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800635 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
636 boolean markCells, boolean allApps) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700637 final LayoutParams lp = params;
638
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800639 // Hotseat icons - scale down and remove text
640 // Don't scale the all apps button
641 // scale percent set to -1 means do not scale
642 // Only scale BubbleTextViews
643 if (child instanceof BubbleTextView) {
644 BubbleTextView bubbleChild = (BubbleTextView) child;
645
Andrew Flynnbc239a12012-03-06 11:39:49 -0800646 // Start the child with 100% scale and visible text
647 resetChild(bubbleChild);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800648
Winson Chungeecf02d2012-03-02 17:14:58 -0800649 if (mIsHotseat && !allApps && mHotseatChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800650 // Scale/make transparent for a hotseat
Winson Chungeecf02d2012-03-02 17:14:58 -0800651 scaleChild(bubbleChild, 0f, mHotseatChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800652
Andrew Flynnbc239a12012-03-06 11:39:49 -0800653 bubbleChild.setTextColor(getResources().getColor(android.R.color.transparent));
Winson Chungeecf02d2012-03-02 17:14:58 -0800654 } else if (mChildScale >= 0) {
Andrew Flynnbc239a12012-03-06 11:39:49 -0800655 // Else possibly still scale it if we need to for smaller icons
Winson Chungeecf02d2012-03-02 17:14:58 -0800656 scaleChild(bubbleChild, 0f, mChildScale);
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800657 }
658 }
659
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800660 // Generate an id for each view, this assumes we have at most 256x256 cells
661 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700662 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700663 // If the horizontal or vertical span is set to -1, it is taken to
664 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700665 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
666 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667
Winson Chungaafa03c2010-06-11 17:34:16 -0700668 child.setId(childId);
669
Michael Jurka8c920dd2011-01-20 14:16:56 -0800670 mChildren.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700671
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700672 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700673
Winson Chungaafa03c2010-06-11 17:34:16 -0700674 return true;
675 }
676 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800677 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700678
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700680 public void removeAllViews() {
681 clearOccupiedCells();
Michael Jurka8c920dd2011-01-20 14:16:56 -0800682 mChildren.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700683 }
684
685 @Override
686 public void removeAllViewsInLayout() {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700687 if (mChildren.getChildCount() > 0) {
688 clearOccupiedCells();
689 mChildren.removeAllViewsInLayout();
690 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700691 }
692
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700693 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkacf6125c2011-01-28 15:20:01 -0800694 mChildren.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700695 }
696
Michael Jurka0280c3b2010-09-17 15:00:07 -0700697 @Override
698 public void removeView(View view) {
699 markCellsAsUnoccupiedForView(view);
Michael Jurka8c920dd2011-01-20 14:16:56 -0800700 mChildren.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700701 }
702
703 @Override
704 public void removeViewAt(int index) {
Michael Jurka8c920dd2011-01-20 14:16:56 -0800705 markCellsAsUnoccupiedForView(mChildren.getChildAt(index));
706 mChildren.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700707 }
708
709 @Override
710 public void removeViewInLayout(View view) {
711 markCellsAsUnoccupiedForView(view);
Michael Jurka8c920dd2011-01-20 14:16:56 -0800712 mChildren.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700713 }
714
715 @Override
716 public void removeViews(int start, int count) {
717 for (int i = start; i < start + count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -0800718 markCellsAsUnoccupiedForView(mChildren.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700719 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800720 mChildren.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700721 }
722
723 @Override
724 public void removeViewsInLayout(int start, int count) {
725 for (int i = start; i < start + count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -0800726 markCellsAsUnoccupiedForView(mChildren.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700727 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800728 mChildren.removeViewsInLayout(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700729 }
730
Michael Jurka8c920dd2011-01-20 14:16:56 -0800731 public void drawChildren(Canvas canvas) {
732 mChildren.draw(canvas);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800733 }
734
Michael Jurkaabded662011-03-04 12:06:57 -0800735 void buildChildrenLayer() {
736 mChildren.buildLayer();
737 }
738
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800739 @Override
740 protected void onAttachedToWindow() {
741 super.onAttachedToWindow();
742 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
743 }
744
Michael Jurkaaf442092010-06-10 17:01:57 -0700745 public void setTagToCellInfoForPoint(int touchX, int touchY) {
746 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800747 Rect frame = mRect;
Michael Jurkaaf442092010-06-10 17:01:57 -0700748 final int x = touchX + mScrollX;
749 final int y = touchY + mScrollY;
Michael Jurka8c920dd2011-01-20 14:16:56 -0800750 final int count = mChildren.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700751
752 boolean found = false;
753 for (int i = count - 1; i >= 0; i--) {
Michael Jurka8c920dd2011-01-20 14:16:56 -0800754 final View child = mChildren.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800755 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700756
Adam Cohen1b607ed2011-03-03 17:26:50 -0800757 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
758 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700759 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700760
Winson Chungeecf02d2012-03-02 17:14:58 -0800761 float scale = child.getScaleX();
762 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
763 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700764 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
765 // offset that by this CellLayout's padding to test an (x,y) point that is relative
766 // to this view.
Winson Chung4b825dcd2011-06-19 12:41:22 -0700767 frame.offset(mPaddingLeft, mPaddingTop);
Winson Chungeecf02d2012-03-02 17:14:58 -0800768 frame.inset((int) (frame.width() * (1f - scale) / 2),
769 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700770
Michael Jurkaaf442092010-06-10 17:01:57 -0700771 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700772 cellInfo.cell = child;
773 cellInfo.cellX = lp.cellX;
774 cellInfo.cellY = lp.cellY;
775 cellInfo.spanX = lp.cellHSpan;
776 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700777 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700778 break;
779 }
780 }
781 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700782
Michael Jurkad771c962011-08-09 15:00:48 -0700783 mLastDownOnOccupiedCell = found;
784
Michael Jurkaaf442092010-06-10 17:01:57 -0700785 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700786 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700787 pointToCellExact(x, y, cellXY);
788
Michael Jurkaaf442092010-06-10 17:01:57 -0700789 cellInfo.cell = null;
790 cellInfo.cellX = cellXY[0];
791 cellInfo.cellY = cellXY[1];
792 cellInfo.spanX = 1;
793 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700794 }
795 setTag(cellInfo);
796 }
797
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800798 @Override
799 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700800 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
801 // even in the case where we return early. Not clearing here was causing bugs whereby on
802 // long-press we'd end up picking up an item from a previous drag operation.
803 final int action = ev.getAction();
804
805 if (action == MotionEvent.ACTION_DOWN) {
806 clearTagCellInfo();
807 }
808
Michael Jurkadee05892010-07-27 10:01:56 -0700809 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
810 return true;
811 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800812
813 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700814 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800815 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800816
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800817 return false;
818 }
819
Adam Cohenc1997fd2011-08-15 18:26:39 -0700820 private void clearTagCellInfo() {
821 final CellInfo cellInfo = mCellInfo;
822 cellInfo.cell = null;
823 cellInfo.cellX = -1;
824 cellInfo.cellY = -1;
825 cellInfo.spanX = 0;
826 cellInfo.spanY = 0;
827 setTag(cellInfo);
828 }
829
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800830 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700831 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800832 }
833
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700834 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700835 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800836 * @param x X coordinate of the point
837 * @param y Y coordinate of the point
838 * @param result Array of 2 ints to hold the x and y coordinate of the cell
839 */
840 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700841 final int hStartPadding = getPaddingLeft();
842 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800843
844 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
845 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
846
Adam Cohend22015c2010-07-26 22:02:18 -0700847 final int xAxis = mCountX;
848 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800849
850 if (result[0] < 0) result[0] = 0;
851 if (result[0] >= xAxis) result[0] = xAxis - 1;
852 if (result[1] < 0) result[1] = 0;
853 if (result[1] >= yAxis) result[1] = yAxis - 1;
854 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700855
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800856 /**
857 * Given a point, return the cell that most closely encloses that point
858 * @param x X coordinate of the point
859 * @param y Y coordinate of the point
860 * @param result Array of 2 ints to hold the x and y coordinate of the cell
861 */
862 void pointToCellRounded(int x, int y, int[] result) {
863 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
864 }
865
866 /**
867 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700868 *
869 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800870 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700871 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800872 * @param result Array of 2 ints to hold the x and y coordinate of the point
873 */
874 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700875 final int hStartPadding = getPaddingLeft();
876 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800877
878 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
879 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
880 }
881
Adam Cohene3e27a82011-04-15 12:07:39 -0700882 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800883 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700884 *
885 * @param cellX X coordinate of the cell
886 * @param cellY Y coordinate of the cell
887 *
888 * @param result Array of 2 ints to hold the x and y coordinate of the point
889 */
890 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700891 regionToCenterPoint(cellX, cellY, 1, 1, result);
892 }
893
894 /**
895 * Given a cell coordinate and span return the point that represents the center of the regio
896 *
897 * @param cellX X coordinate of the cell
898 * @param cellY Y coordinate of the cell
899 *
900 * @param result Array of 2 ints to hold the x and y coordinate of the point
901 */
902 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700903 final int hStartPadding = getPaddingLeft();
904 final int vStartPadding = getPaddingTop();
Adam Cohene3e27a82011-04-15 12:07:39 -0700905
Adam Cohen47a876d2012-03-19 13:21:41 -0700906 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
907 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
908 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
909 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700910 }
911
Adam Cohen482ed822012-03-02 14:15:13 -0800912 public float getDistanceFromCell(float x, float y, int[] cell) {
913 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
914 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
915 Math.pow(y - mTmpPoint[1], 2));
916 return distance;
917 }
918
Romain Guy84f296c2009-11-04 15:00:44 -0800919 int getCellWidth() {
920 return mCellWidth;
921 }
922
923 int getCellHeight() {
924 return mCellHeight;
925 }
926
Adam Cohend4844c32011-02-18 19:25:06 -0800927 int getWidthGap() {
928 return mWidthGap;
929 }
930
931 int getHeightGap() {
932 return mHeightGap;
933 }
934
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700935 Rect getContentRect(Rect r) {
936 if (r == null) {
937 r = new Rect();
938 }
939 int left = getPaddingLeft();
940 int top = getPaddingTop();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700941 int right = left + getWidth() - mPaddingLeft - mPaddingRight;
942 int bottom = top + getHeight() - mPaddingTop - mPaddingBottom;
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700943 r.set(left, top, right, bottom);
944 return r;
945 }
946
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800947 @Override
948 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
949 // TODO: currently ignoring padding
Winson Chungaafa03c2010-06-11 17:34:16 -0700950
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800951 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700952 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
953
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800954 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
955 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700956
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800957 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
958 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
959 }
960
Adam Cohend22015c2010-07-26 22:02:18 -0700961 int numWidthGaps = mCountX - 1;
962 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963
Adam Cohen234c4cd2011-07-17 21:03:04 -0700964 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700965 int hSpace = widthSpecSize - mPaddingLeft - mPaddingRight;
966 int vSpace = heightSpecSize - mPaddingTop - mPaddingBottom;
967 int hFreeSpace = hSpace - (mCountX * mOriginalCellWidth);
968 int vFreeSpace = vSpace - (mCountY * mOriginalCellHeight);
969 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
970 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700971 mChildren.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700972 } else {
973 mWidthGap = mOriginalWidthGap;
974 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700975 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700976
Michael Jurka8c920dd2011-01-20 14:16:56 -0800977 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
978 int newWidth = widthSpecSize;
979 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700980 if (widthSpecMode == MeasureSpec.AT_MOST) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700981 newWidth = mPaddingLeft + mPaddingRight + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700982 ((mCountX - 1) * mWidthGap);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700983 newHeight = mPaddingTop + mPaddingBottom + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700984 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700985 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700986 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800987
988 int count = getChildCount();
989 for (int i = 0; i < count; i++) {
990 View child = getChildAt(i);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700991 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - mPaddingLeft -
992 mPaddingRight, MeasureSpec.EXACTLY);
993 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - mPaddingTop -
994 mPaddingBottom, MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -0800995 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
996 }
997 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800998 }
999
1000 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -07001001 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001002 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001003 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001004 View child = getChildAt(i);
Winson Chung4b825dcd2011-06-19 12:41:22 -07001005 child.layout(mPaddingLeft, mPaddingTop,
1006 r - l - mPaddingRight, b - t - mPaddingBottom);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001007 }
1008 }
1009
1010 @Override
Michael Jurkadee05892010-07-27 10:01:56 -07001011 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1012 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -07001013 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001014 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
1015 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -07001016 }
1017
1018 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001019 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001020 mChildren.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001021 }
1022
1023 @Override
1024 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001025 mChildren.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001026 }
1027
Michael Jurka5f1c5092010-09-03 14:15:02 -07001028 public float getBackgroundAlpha() {
1029 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001030 }
1031
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001032 public void setBackgroundAlphaMultiplier(float multiplier) {
1033 mBackgroundAlphaMultiplier = multiplier;
1034 }
1035
Adam Cohenddb82192010-11-10 16:32:54 -08001036 public float getBackgroundAlphaMultiplier() {
1037 return mBackgroundAlphaMultiplier;
1038 }
1039
Michael Jurka5f1c5092010-09-03 14:15:02 -07001040 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001041 if (mBackgroundAlpha != alpha) {
1042 mBackgroundAlpha = alpha;
1043 invalidate();
1044 }
Michael Jurkadee05892010-07-27 10:01:56 -07001045 }
1046
Michael Jurka5f1c5092010-09-03 14:15:02 -07001047 // Need to return true to let the view system know we know how to handle alpha-- this is
1048 // because when our children have an alpha of 0.0f, they are still rendering their "dimmed"
1049 // versions
1050 @Override
1051 protected boolean onSetAlpha(int alpha) {
1052 return true;
1053 }
1054
Michael Jurkaafaa0502011-12-13 18:22:50 -08001055 @Override
Michael Jurka5f1c5092010-09-03 14:15:02 -07001056 public void setAlpha(float alpha) {
1057 setChildrenAlpha(alpha);
1058 super.setAlpha(alpha);
1059 }
1060
Michael Jurkadee05892010-07-27 10:01:56 -07001061 private void setChildrenAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001062 final int childCount = getChildCount();
1063 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001064 getChildAt(i).setAlpha(alpha);
1065 }
1066 }
1067
Patrick Dubroy440c3602010-07-13 17:50:32 -07001068 public View getChildAt(int x, int y) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08001069 return mChildren.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001070 }
1071
Adam Cohen76fc0852011-06-17 13:26:23 -07001072 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001073 int delay, boolean permanent, boolean adjustOccupied) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001074 CellLayoutChildren clc = getChildrenLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08001075 boolean[][] occupied = mOccupied;
1076 if (!permanent) {
1077 occupied = mTmpOccupied;
1078 }
1079
1080 if (clc.indexOfChild(child) != -1 && !occupied[cellX][cellY]) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001081 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1082 final ItemInfo info = (ItemInfo) child.getTag();
1083
1084 // We cancel any existing animations
1085 if (mReorderAnimators.containsKey(lp)) {
1086 mReorderAnimators.get(lp).cancel();
1087 mReorderAnimators.remove(lp);
1088 }
1089
Adam Cohen482ed822012-03-02 14:15:13 -08001090 final int oldX = lp.x;
1091 final int oldY = lp.y;
1092 if (adjustOccupied) {
1093 occupied[lp.cellX][lp.cellY] = false;
1094 occupied[cellX][cellY] = true;
1095 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001096 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001097 if (permanent) {
1098 lp.cellX = info.cellX = cellX;
1099 lp.cellY = info.cellY = cellY;
1100 } else {
1101 lp.tmpCellX = cellX;
1102 lp.tmpCellY = cellY;
1103 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001104 clc.setupLp(lp);
1105 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001106 final int newX = lp.x;
1107 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001108
Adam Cohen76fc0852011-06-17 13:26:23 -07001109 lp.x = oldX;
1110 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001111
Adam Cohen482ed822012-03-02 14:15:13 -08001112 // Exit early if we're not actually moving the view
1113 if (oldX == newX && oldY == newY) {
1114 lp.isLockedToGrid = true;
1115 return true;
1116 }
1117
1118 ValueAnimator va = ValueAnimator.ofFloat(0f, 1f);
1119 va.setDuration(duration);
1120 mReorderAnimators.put(lp, va);
1121
1122 va.addUpdateListener(new AnimatorUpdateListener() {
1123 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001124 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001125 float r = ((Float) animation.getAnimatedValue()).floatValue();
1126 child.setTranslationX(r * (newX - oldX));
1127 child.setTranslationY(r * (newY - oldY));
Adam Cohenbfbfd262011-06-13 16:55:12 -07001128 }
1129 });
Adam Cohen482ed822012-03-02 14:15:13 -08001130 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001131 boolean cancelled = false;
1132 public void onAnimationEnd(Animator animation) {
1133 // If the animation was cancelled, it means that another animation
1134 // has interrupted this one, and we don't want to lock the item into
1135 // place just yet.
1136 if (!cancelled) {
Adam Cohen482ed822012-03-02 14:15:13 -08001137 child.setTranslationX(0);
1138 child.setTranslationY(0);
Adam Cohenbfbfd262011-06-13 16:55:12 -07001139 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001140 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001141 }
1142 if (mReorderAnimators.containsKey(lp)) {
1143 mReorderAnimators.remove(lp);
1144 }
1145 }
1146 public void onAnimationCancel(Animator animation) {
1147 cancelled = true;
1148 }
1149 });
Adam Cohen482ed822012-03-02 14:15:13 -08001150 va.setStartDelay(delay);
1151 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001152 return true;
1153 }
1154 return false;
1155 }
1156
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001157 /**
1158 * Estimate where the top left cell of the dragged item will land if it is dropped.
1159 *
1160 * @param originX The X value of the top left corner of the item
1161 * @param originY The Y value of the top left corner of the item
1162 * @param spanX The number of horizontal cells that the item spans
1163 * @param spanY The number of vertical cells that the item spans
1164 * @param result The estimated drop cell X and Y.
1165 */
1166 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001167 final int countX = mCountX;
1168 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001169
Michael Jurkaa63c4522010-08-19 13:52:27 -07001170 // pointToCellRounded takes the top left of a cell but will pad that with
1171 // cellWidth/2 and cellHeight/2 when finding the matching cell
1172 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001173
1174 // If the item isn't fully on this screen, snap to the edges
1175 int rightOverhang = result[0] + spanX - countX;
1176 if (rightOverhang > 0) {
1177 result[0] -= rightOverhang; // Snap to right
1178 }
1179 result[0] = Math.max(0, result[0]); // Snap to left
1180 int bottomOverhang = result[1] + spanY - countY;
1181 if (bottomOverhang > 0) {
1182 result[1] -= bottomOverhang; // Snap to bottom
1183 }
1184 result[1] = Math.max(0, result[1]); // Snap to top
1185 }
1186
Adam Cohen482ed822012-03-02 14:15:13 -08001187 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1188 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001189 final int oldDragCellX = mDragCell[0];
1190 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001191
Winson Chungb8c69f32011-10-19 21:36:08 -07001192 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001193 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1194 } else {
1195 mDragCenter.set(originX, originY);
1196 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001197
Adam Cohen2801caf2011-05-13 20:57:39 -07001198 if (dragOutline == null && v == null) {
1199 if (mCrosshairsDrawable != null) {
1200 invalidate();
1201 }
1202 return;
1203 }
1204
Adam Cohen482ed822012-03-02 14:15:13 -08001205 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1206 mDragCell[0] = cellX;
1207 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001208 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001209 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001210 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001211
Joe Onorato4be866d2010-10-10 11:26:02 -07001212 int left = topLeft[0];
1213 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001214
Winson Chungb8c69f32011-10-19 21:36:08 -07001215 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001216 // When drawing the drag outline, it did not account for margin offsets
1217 // added by the view's parent.
1218 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1219 left += lp.leftMargin;
1220 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001221
Adam Cohen99e8b402011-03-25 19:23:43 -07001222 // Offsets due to the size difference between the View and the dragOutline.
1223 // There is a size difference to account for the outer blur, which may lie
1224 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001225 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001226 // We center about the x axis
1227 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1228 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001229 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001230 if (dragOffset != null && dragRegion != null) {
1231 // Center the drag region *horizontally* in the cell and apply a drag
1232 // outline offset
1233 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1234 - dragRegion.width()) / 2;
1235 top += dragOffset.y;
1236 } else {
1237 // Center the drag outline in the cell
1238 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1239 - dragOutline.getWidth()) / 2;
1240 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1241 - dragOutline.getHeight()) / 2;
1242 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001243 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001244 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001245 mDragOutlineAnims[oldIndex].animateOut();
1246 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001247 Rect r = mDragOutlines[mDragOutlineCurrent];
1248 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1249 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001250 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001251 }
Winson Chung150fbab2010-09-29 17:14:26 -07001252
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001253 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1254 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001255 }
Patrick Dubroy49250ad2010-10-08 15:33:52 -07001256
1257 // If we are drawing crosshairs, the entire CellLayout needs to be invalidated
1258 if (mCrosshairsDrawable != null) {
1259 invalidate();
1260 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001261 }
1262
Adam Cohene0310962011-04-18 16:15:31 -07001263 public void clearDragOutlines() {
1264 final int oldIndex = mDragOutlineCurrent;
1265 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001266 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001267 }
1268
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001269 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001270 * Find a vacant area that will fit the given bounds nearest the requested
1271 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001272 *
Romain Guy51afc022009-05-04 18:03:43 -07001273 * @param pixelX The X location at which you want to search for a vacant area.
1274 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001275 * @param spanX Horizontal span of the object.
1276 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001277 * @param result Array in which to place the result, or null (in which case a new array will
1278 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001279 * @return The X, Y cell of a vacant area that can contain this object,
1280 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001281 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001282 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1283 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001284 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001285 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001286
Michael Jurka6a1435d2010-09-27 17:35:12 -07001287 /**
1288 * Find a vacant area that will fit the given bounds nearest the requested
1289 * cell location. Uses Euclidean distance to score multiple vacant areas.
1290 *
1291 * @param pixelX The X location at which you want to search for a vacant area.
1292 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001293 * @param minSpanX The minimum horizontal span required
1294 * @param minSpanY The minimum vertical span required
1295 * @param spanX Horizontal span of the object.
1296 * @param spanY Vertical span of the object.
1297 * @param result Array in which to place the result, or null (in which case a new array will
1298 * be allocated)
1299 * @return The X, Y cell of a vacant area that can contain this object,
1300 * nearest the requested location.
1301 */
1302 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1303 int spanY, int[] result, int[] resultSpan) {
1304 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1305 result, resultSpan);
1306 }
1307
1308 /**
1309 * Find a vacant area that will fit the given bounds nearest the requested
1310 * cell location. Uses Euclidean distance to score multiple vacant areas.
1311 *
1312 * @param pixelX The X location at which you want to search for a vacant area.
1313 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001314 * @param spanX Horizontal span of the object.
1315 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001316 * @param ignoreOccupied If true, the result can be an occupied cell
1317 * @param result Array in which to place the result, or null (in which case a new array will
1318 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001319 * @return The X, Y cell of a vacant area that can contain this object,
1320 * nearest the requested location.
1321 */
Adam Cohendf035382011-04-11 17:22:04 -07001322 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1323 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001324 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001325 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001326 }
1327
1328 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1329 private void lazyInitTempRectStack() {
1330 if (mTempRectStack.isEmpty()) {
1331 for (int i = 0; i < mCountX * mCountY; i++) {
1332 mTempRectStack.push(new Rect());
1333 }
1334 }
1335 }
Adam Cohen482ed822012-03-02 14:15:13 -08001336
Adam Cohend41fbf52012-02-16 23:53:59 -08001337 private void recycleTempRects(Stack<Rect> used) {
1338 while (!used.isEmpty()) {
1339 mTempRectStack.push(used.pop());
1340 }
1341 }
1342
1343 /**
1344 * Find a vacant area that will fit the given bounds nearest the requested
1345 * cell location. Uses Euclidean distance to score multiple vacant areas.
1346 *
1347 * @param pixelX The X location at which you want to search for a vacant area.
1348 * @param pixelY The Y location at which you want to search for a vacant area.
1349 * @param minSpanX The minimum horizontal span required
1350 * @param minSpanY The minimum vertical span required
1351 * @param spanX Horizontal span of the object.
1352 * @param spanY Vertical span of the object.
1353 * @param ignoreOccupied If true, the result can be an occupied cell
1354 * @param result Array in which to place the result, or null (in which case a new array will
1355 * be allocated)
1356 * @return The X, Y cell of a vacant area that can contain this object,
1357 * nearest the requested location.
1358 */
1359 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001360 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1361 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001362 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001363 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001364 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001365
Adam Cohene3e27a82011-04-15 12:07:39 -07001366 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1367 // to the center of the item, but we are searching based on the top-left cell, so
1368 // we translate the point over to correspond to the top-left.
1369 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1370 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1371
Jeff Sharkey70864282009-04-07 21:08:40 -07001372 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001373 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001374 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001375 final Rect bestRect = new Rect(-1, -1, -1, -1);
1376 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001377
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001378 final int countX = mCountX;
1379 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001380
Adam Cohend41fbf52012-02-16 23:53:59 -08001381 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1382 spanX < minSpanX || spanY < minSpanY) {
1383 return bestXY;
1384 }
1385
1386 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001387 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001388 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1389 int ySize = -1;
1390 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001391 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001392 // First, let's see if this thing fits anywhere
1393 for (int i = 0; i < minSpanX; i++) {
1394 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001395 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001396 continue inner;
1397 }
Michael Jurkac28de512010-08-13 11:27:44 -07001398 }
1399 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001400 xSize = minSpanX;
1401 ySize = minSpanY;
1402
1403 // We know that the item will fit at _some_ acceptable size, now let's see
1404 // how big we can make it. We'll alternate between incrementing x and y spans
1405 // until we hit a limit.
1406 boolean incX = true;
1407 boolean hitMaxX = xSize >= spanX;
1408 boolean hitMaxY = ySize >= spanY;
1409 while (!(hitMaxX && hitMaxY)) {
1410 if (incX && !hitMaxX) {
1411 for (int j = 0; j < ySize; j++) {
1412 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1413 // We can't move out horizontally
1414 hitMaxX = true;
1415 }
1416 }
1417 if (!hitMaxX) {
1418 xSize++;
1419 }
1420 } else if (!hitMaxY) {
1421 for (int i = 0; i < xSize; i++) {
1422 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1423 // We can't move out vertically
1424 hitMaxY = true;
1425 }
1426 }
1427 if (!hitMaxY) {
1428 ySize++;
1429 }
1430 }
1431 hitMaxX |= xSize >= spanX;
1432 hitMaxY |= ySize >= spanY;
1433 incX = !incX;
1434 }
1435 incX = true;
1436 hitMaxX = xSize >= spanX;
1437 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001438 }
Winson Chung0be025d2011-05-23 17:45:09 -07001439 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001440 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001441
Adam Cohend41fbf52012-02-16 23:53:59 -08001442 // We verify that the current rect is not a sub-rect of any of our previous
1443 // candidates. In this case, the current rect is disqualified in favour of the
1444 // containing rect.
1445 Rect currentRect = mTempRectStack.pop();
1446 currentRect.set(x, y, x + xSize, y + ySize);
1447 boolean contained = false;
1448 for (Rect r : validRegions) {
1449 if (r.contains(currentRect)) {
1450 contained = true;
1451 break;
1452 }
1453 }
1454 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001455 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1456 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001457
Adam Cohend41fbf52012-02-16 23:53:59 -08001458 if ((distance <= bestDistance && !contained) ||
1459 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001460 bestDistance = distance;
1461 bestXY[0] = x;
1462 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001463 if (resultSpan != null) {
1464 resultSpan[0] = xSize;
1465 resultSpan[1] = ySize;
1466 }
1467 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001468 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001469 }
1470 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001471 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001472 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001473
Adam Cohenc0dcf592011-06-01 15:30:43 -07001474 // Return -1, -1 if no suitable location found
1475 if (bestDistance == Double.MAX_VALUE) {
1476 bestXY[0] = -1;
1477 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001478 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001479 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001480 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001481 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001482
Adam Cohen482ed822012-03-02 14:15:13 -08001483 /**
1484 * Find a vacant area that will fit the given bounds nearest the requested
1485 * cell location, and will also weigh in a suggested direction vector of the
1486 * desired location. This method computers distance based on unit grid distances,
1487 * not pixel distances.
1488 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001489 * @param cellX The X cell nearest to which you want to search for a vacant area.
1490 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001491 * @param spanX Horizontal span of the object.
1492 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001493 * @param direction The favored direction in which the views should move from x, y
1494 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1495 * matches exactly. Otherwise we find the best matching direction.
1496 * @param occoupied The array which represents which cells in the CellLayout are occupied
1497 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1498 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001499 * @param result Array in which to place the result, or null (in which case a new array will
1500 * be allocated)
1501 * @return The X, Y cell of a vacant area that can contain this object,
1502 * nearest the requested location.
1503 */
1504 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001505 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001506 // Keep track of best-scoring drop area
1507 final int[] bestXY = result != null ? result : new int[2];
1508 float bestDistance = Float.MAX_VALUE;
1509 int bestDirectionScore = Integer.MIN_VALUE;
1510
1511 final int countX = mCountX;
1512 final int countY = mCountY;
1513
1514 for (int y = 0; y < countY - (spanY - 1); y++) {
1515 inner:
1516 for (int x = 0; x < countX - (spanX - 1); x++) {
1517 // First, let's see if this thing fits anywhere
1518 for (int i = 0; i < spanX; i++) {
1519 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001520 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001521 continue inner;
1522 }
1523 }
1524 }
1525
1526 float distance = (float)
1527 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1528 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001529 computeDirectionVector(x - cellX, y - cellY, curDirection);
1530 // The direction score is just the dot product of the two candidate direction
1531 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001532 int curDirectionScore = direction[0] * curDirection[0] +
1533 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001534 boolean exactDirectionOnly = false;
1535 boolean directionMatches = direction[0] == curDirection[0] &&
1536 direction[0] == curDirection[0];
1537 if ((directionMatches || !exactDirectionOnly) &&
1538 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001539 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1540 bestDistance = distance;
1541 bestDirectionScore = curDirectionScore;
1542 bestXY[0] = x;
1543 bestXY[1] = y;
1544 }
1545 }
1546 }
1547
1548 // Return -1, -1 if no suitable location found
1549 if (bestDistance == Float.MAX_VALUE) {
1550 bestXY[0] = -1;
1551 bestXY[1] = -1;
1552 }
1553 return bestXY;
1554 }
1555
Adam Cohen47a876d2012-03-19 13:21:41 -07001556 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1557 int[] direction,boolean[][] occupied,
1558 boolean blockOccupied[][], int[] result) {
1559 // Keep track of best-scoring drop area
1560 final int[] bestXY = result != null ? result : new int[2];
1561 bestXY[0] = -1;
1562 bestXY[1] = -1;
1563 float bestDistance = Float.MAX_VALUE;
1564
1565 // We use this to march in a single direction
1566 if (direction[0] != 0 && direction[1] != 0) {
1567 return bestXY;
1568 }
1569
1570 // This will only incrememnet one of x or y based on the assertion above
1571 int x = cellX + direction[0];
1572 int y = cellY + direction[1];
1573 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
1574
1575 boolean fail = false;
1576 for (int i = 0; i < spanX; i++) {
1577 for (int j = 0; j < spanY; j++) {
1578 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1579 fail = true;
1580 }
1581 }
1582 }
1583 if (!fail) {
1584 float distance = (float)
1585 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1586 if (Float.compare(distance, bestDistance) < 0) {
1587 bestDistance = distance;
1588 bestXY[0] = x;
1589 bestXY[1] = y;
1590 }
1591 }
1592 x += direction[0];
1593 y += direction[1];
1594 }
1595 return bestXY;
1596 }
1597
Adam Cohen482ed822012-03-02 14:15:13 -08001598 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
1599 int[] direction) {
1600 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1601 boolean success = false;
1602 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1603 lp.cellVSpan, mTmpOccupied, false);
1604 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1605
1606 findNearestArea(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan,
Adam Cohen47a876d2012-03-19 13:21:41 -07001607 direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001608
1609 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1610 lp.tmpCellX = mTempLocation[0];
1611 lp.tmpCellY = mTempLocation[1];
1612 success = true;
1613
1614 }
1615 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1616 lp.cellVSpan, mTmpOccupied, true);
1617 return success;
1618 }
1619
Adam Cohen47a876d2012-03-19 13:21:41 -07001620 // This method looks in the specified direction to see if there is an additional view
1621 // immediately adjecent in that direction
1622 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
1623 boolean[][] occupied) {
1624 boolean found = false;
1625
1626 int childCount = mChildren.getChildCount();
1627 Rect r0 = new Rect(boundingRect);
1628 Rect r1 = new Rect();
1629
1630 int deltaX = 0;
1631 int deltaY = 0;
1632 if (direction[1] < 0) {
1633 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom);
1634 deltaY = -1;
1635 } else if (direction[1] > 0) {
1636 r0.set(r0.left, r0.top, r0.right, r0.bottom + 1);
1637 deltaY = 1;
1638 } else if (direction[0] < 0) {
1639 r0.set(r0.left - 1, r0.top, r0.right, r0.bottom);
1640 deltaX = -1;
1641 } else if (direction[0] > 0) {
1642 r0.set(r0.left, r0.top, r0.right + 1, r0.bottom);
1643 deltaX = 1;
1644 }
1645
1646 for (int i = 0; i < childCount; i++) {
1647 View child = mChildren.getChildAt(i);
1648 if (views.contains(child)) continue;
1649 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1650
1651 r1.set(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan, lp.tmpCellY + lp.cellVSpan);
1652 if (Rect.intersects(r0, r1)) {
1653 if (!lp.canReorder) {
1654 return false;
1655 }
1656 boolean pushed = false;
1657 for (int x = lp.tmpCellX; x < lp.tmpCellX + lp.cellHSpan; x++) {
1658 for (int y = lp.tmpCellY; y < lp.tmpCellY + lp.cellVSpan; y++) {
1659 boolean inBounds = x - deltaX >= 0 && x -deltaX < mCountX
1660 && y - deltaY >= 0 && y - deltaY < mCountY;
1661 if (inBounds && occupied[x - deltaX][y - deltaY]) {
1662 pushed = true;
1663 }
1664 }
1665 }
1666 if (pushed) {
1667 views.add(child);
1668 boundingRect.union(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan,
1669 lp.tmpCellY + lp.cellVSpan);
1670 found = true;
1671 }
1672 }
1673 }
1674 return found;
1675 }
1676
1677 private boolean pushViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1678 int[] direction) {
1679 if (views.size() == 0) return true;
1680
1681
1682 boolean success = false;
1683
1684 // We construct a rect which represents the entire group of views
1685 Rect boundingRect = null;
1686 for (View v: views) {
1687 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1688 if (boundingRect == null) {
1689 boundingRect = new Rect(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan,
1690 lp.tmpCellY + lp.cellVSpan);
1691 } else {
1692 boundingRect.union(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan,
1693 lp.tmpCellY + lp.cellVSpan);
1694 }
1695 }
1696
1697 ArrayList<View> dup = (ArrayList<View>) views.clone();
1698 while (addViewInDirection(dup, boundingRect, direction, mTmpOccupied)) {
1699 }
1700 for (View v: dup) {
1701 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1702 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1703 lp.cellVSpan, mTmpOccupied, false);
1704 }
1705
1706 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1707 int top = boundingRect.top;
1708 int left = boundingRect.left;
1709 for (View v: dup) {
1710 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1711 markCellsForView(lp.tmpCellX - left, lp.tmpCellY - top, lp.cellHSpan,
1712 lp.cellVSpan, blockOccupied, true);
1713 }
1714
1715 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1716
1717 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1718 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1719
1720 int deltaX = mTempLocation[0] - boundingRect.left;
1721 int deltaY = mTempLocation[1] - boundingRect.top;
1722 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1723 for (View v: dup) {
1724 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1725 lp.tmpCellX += deltaX;
1726 lp.tmpCellY += deltaY;
1727 }
1728 success = true;
1729 }
1730 for (View v: dup) {
1731 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1732 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1733 lp.cellVSpan, mTmpOccupied, true);
1734 }
1735 return success;
1736 }
1737
Adam Cohen482ed822012-03-02 14:15:13 -08001738 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
1739 int[] direction) {
1740 if (views.size() == 0) return true;
1741 boolean success = false;
1742
1743 // We construct a rect which represents the entire group of views
1744 Rect boundingRect = null;
1745 for (View v: views) {
1746 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1747 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1748 lp.cellVSpan, mTmpOccupied, false);
1749 if (boundingRect == null) {
1750 boundingRect = new Rect(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan,
1751 lp.tmpCellY + lp.cellVSpan);
1752 } else {
1753 boundingRect.union(lp.tmpCellX, lp.tmpCellY, lp.tmpCellX + lp.cellHSpan,
1754 lp.tmpCellY + lp.cellVSpan);
1755 }
1756 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001757 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1758 int top = boundingRect.top;
1759 int left = boundingRect.left;
1760 for (View v: views) {
1761 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1762 markCellsForView(lp.tmpCellX - left, lp.tmpCellY - top, lp.cellHSpan,
1763 lp.cellVSpan, blockOccupied, true);
1764 }
1765
Adam Cohen482ed822012-03-02 14:15:13 -08001766 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1767
1768 // TODO: this bounding rect may not be completely filled, lets be more precise about this
1769 // check.
Adam Cohen47a876d2012-03-19 13:21:41 -07001770 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1771 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001772
1773 int deltaX = mTempLocation[0] - boundingRect.left;
1774 int deltaY = mTempLocation[1] - boundingRect.top;
1775 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
1776 for (View v: views) {
1777 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1778 lp.tmpCellX += deltaX;
1779 lp.tmpCellY += deltaY;
1780 }
1781 success = true;
1782 }
1783 for (View v: views) {
1784 LayoutParams lp = (LayoutParams) v.getLayoutParams();
1785 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan,
1786 lp.cellVSpan, mTmpOccupied, true);
1787 }
1788 return success;
1789 }
1790
1791 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1792 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1793 }
1794
1795 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
1796 View ignoreView) {
1797 mIntersectingViews.clear();
1798
1799 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001800
1801 if (ignoreView != null) {
1802 LayoutParams lp = (LayoutParams) ignoreView.getLayoutParams();
1803 lp.tmpCellX = cellX;
1804 lp.tmpCellY = cellY;
1805 }
1806
1807 int childCount = mChildren.getChildCount();
1808 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1809 Rect r1 = new Rect();
1810 for (int i = 0; i < childCount; i++) {
1811 View child = mChildren.getChildAt(i);
1812 if (child == ignoreView) continue;
1813 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1814 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
1815 if (Rect.intersects(r0, r1)) {
1816 if (!lp.canReorder) {
1817 return false;
1818 }
1819 mIntersectingViews.add(child);
1820 }
1821 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001822
1823 if (pushViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction)) {
1824 return true;
1825 }
1826 // Try the opposite direction
1827 direction[0] *= -1;
1828 direction[1] *= -1;
1829 if (pushViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction)) {
1830 return true;
1831 }
1832 // Switch the direction back
1833 direction[0] *= -1;
1834 direction[1] *= -1;
1835
Adam Cohen482ed822012-03-02 14:15:13 -08001836 // First we try moving the views as a block
1837 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction)) {
1838 return true;
1839 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001840
Adam Cohen482ed822012-03-02 14:15:13 -08001841 // Ok, they couldn't move as a block, let's move them individually
1842 for (View v : mIntersectingViews) {
1843 if (!addViewToTempLocation(v, mOccupiedRect, direction)) {
1844 return false;
1845 }
1846 }
1847 return true;
1848 }
1849
1850 /*
1851 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1852 * the provided point and the provided cell
1853 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001854 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001855 double angle = Math.atan(((float) deltaY) / deltaX);
1856
1857 result[0] = 0;
1858 result[1] = 0;
1859 if (Math.abs(Math.cos(angle)) > 0.5f) {
1860 result[0] = (int) Math.signum(deltaX);
1861 }
1862 if (Math.abs(Math.sin(angle)) > 0.5f) {
1863 result[1] = (int) Math.signum(deltaY);
1864 }
1865 }
1866
1867 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1868 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
1869 // This creates a copy of the current occupied array, omitting the current view being
1870 // dragged
1871 resetTempLayoutToCurrent(dragView);
1872
1873 // We find the nearest cell into which we would place the dragged item, assuming there's
1874 // nothing in its way.
1875 int result[] = new int[2];
1876 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1877
1878 boolean success = false;
1879 // First we try the exact nearest position of the item being dragged,
1880 // we will then want to try to move this around to other neighbouring positions
1881 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView);
1882
1883 if (!success) {
1884 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1885 // x, then 1 in y etc.
1886 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1887 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1888 dragView, false, solution);
1889 } else if (spanY > minSpanY) {
1890 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1891 dragView, true, solution);
1892 }
1893 solution.isSolution = false;
1894 } else {
1895 solution.isSolution = true;
1896 solution.dragViewX = result[0];
1897 solution.dragViewY = result[1];
1898 solution.dragViewSpanX = spanX;
1899 solution.dragViewSpanY = spanY;
1900 copyCurrentStateToSolution(solution, true);
1901 }
1902 return solution;
1903 }
1904
1905 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
1906 int childCount = mChildren.getChildCount();
1907 for (int i = 0; i < childCount; i++) {
1908 View child = mChildren.getChildAt(i);
1909 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1910 Point p;
1911 if (temp) {
1912 p = new Point(lp.tmpCellX, lp.tmpCellY);
1913 } else {
1914 p = new Point(lp.cellX, lp.cellY);
1915 }
1916 solution.map.put(child, p);
1917 }
1918 }
1919
1920 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1921 for (int i = 0; i < mCountX; i++) {
1922 for (int j = 0; j < mCountY; j++) {
1923 mTmpOccupied[i][j] = false;
1924 }
1925 }
1926
1927 int childCount = mChildren.getChildCount();
1928 for (int i = 0; i < childCount; i++) {
1929 View child = mChildren.getChildAt(i);
1930 if (child == dragView) continue;
1931 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1932 Point p = solution.map.get(child);
1933 if (p != null) {
1934 lp.tmpCellX = p.x;
1935 lp.tmpCellY = p.y;
1936 markCellsForView(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan,
1937 mTmpOccupied, true);
1938 }
1939 }
1940 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1941 solution.dragViewSpanY, mTmpOccupied, true);
1942 }
1943
1944 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1945 commitDragView) {
1946
1947 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1948 for (int i = 0; i < mCountX; i++) {
1949 for (int j = 0; j < mCountY; j++) {
1950 occupied[i][j] = false;
1951 }
1952 }
1953
1954 int childCount = mChildren.getChildCount();
1955 for (int i = 0; i < childCount; i++) {
1956 View child = mChildren.getChildAt(i);
1957 if (child == dragView) continue;
1958 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1959 Point p = solution.map.get(child);
1960 if (p != null) {
1961 if (lp.cellX != p.x || lp.cellY != p.y) {
1962 animateChildToPosition(child, p.x, p.y, 150, 0, DESTRUCTIVE_REORDER, false);
1963 }
1964 markCellsForView(p.x, p.y, lp.cellHSpan, lp.cellVSpan, occupied, true);
1965 }
1966 }
1967 if (commitDragView) {
1968 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1969 solution.dragViewSpanY, occupied, true);
1970 }
1971 }
1972
1973 private void commitTempPlacement() {
1974 for (int i = 0; i < mCountX; i++) {
1975 for (int j = 0; j < mCountY; j++) {
1976 mOccupied[i][j] = mTmpOccupied[i][j];
1977 }
1978 }
1979 int childCount = mChildren.getChildCount();
1980 for (int i = 0; i < childCount; i++) {
1981 LayoutParams lp = (LayoutParams) mChildren.getChildAt(i).getLayoutParams();
1982 lp.cellX = lp.tmpCellX;
1983 lp.cellY = lp.tmpCellY;
1984 }
1985 }
1986
1987 public void setUseTempCoords(boolean useTempCoords) {
1988 int childCount = mChildren.getChildCount();
1989 for (int i = 0; i < childCount; i++) {
1990 LayoutParams lp = (LayoutParams) mChildren.getChildAt(i).getLayoutParams();
1991 lp.useTmpCoords = useTempCoords;
1992 }
1993 }
1994
1995 private void resetTempLayoutToCurrent(View ignoreView) {
1996 for (int i = 0; i < mCountX; i++) {
1997 for (int j = 0; j < mCountY; j++) {
1998 mTmpOccupied[i][j] = mOccupied[i][j];
1999 }
2000 }
2001 int childCount = mChildren.getChildCount();
2002 for (int i = 0; i < childCount; i++) {
2003 View child = mChildren.getChildAt(i);
2004 if (child == ignoreView) continue;
2005 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2006 lp.tmpCellX = lp.cellX;
2007 lp.tmpCellY = lp.cellY;
2008 }
2009 }
2010
2011 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2012 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2013 int[] result = new int[2];
2014 int[] resultSpan = new int[2];
2015 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2016 resultSpan);
2017 if (result[0] >= 0 && result[1] >= 0) {
2018 copyCurrentStateToSolution(solution, false);
2019 solution.dragViewX = result[0];
2020 solution.dragViewY = result[1];
2021 solution.dragViewSpanX = resultSpan[0];
2022 solution.dragViewSpanY = resultSpan[1];
2023 solution.isSolution = true;
2024 } else {
2025 solution.isSolution = false;
2026 }
2027 return solution;
2028 }
2029
2030 public void prepareChildForDrag(View child) {
2031 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002032 }
2033
2034 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2035 View dragView, int[] result, int resultSpan[], int mode) {
2036
2037 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002038 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002039
2040 if (resultSpan == null) {
2041 resultSpan = new int[2];
2042 }
2043
2044 // We attempt the first algorithm
Adam Cohen47a876d2012-03-19 13:21:41 -07002045 regionToCenterPoint(result[0], result[1], spanX, spanY, mTmpPoint);
2046 computeDirectionVector((mTmpPoint[0] - pixelX) / spanX, (mTmpPoint[1] - pixelY) / spanY,
2047 mDirectionVector);
Adam Cohen482ed822012-03-02 14:15:13 -08002048 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2049 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2050
2051 // We attempt the approach which doesn't shuffle views at all
2052 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2053 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2054
2055 ItemConfiguration finalSolution = null;
2056 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2057 finalSolution = swapSolution;
2058 } else if (noShuffleSolution.isSolution) {
2059 finalSolution = noShuffleSolution;
2060 }
2061
2062 boolean foundSolution = true;
2063 if (!DESTRUCTIVE_REORDER) {
2064 setUseTempCoords(true);
2065 }
2066
2067 if (finalSolution != null) {
2068 result[0] = finalSolution.dragViewX;
2069 result[1] = finalSolution.dragViewY;
2070 resultSpan[0] = finalSolution.dragViewSpanX;
2071 resultSpan[1] = finalSolution.dragViewSpanY;
2072
2073 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2074 // committing anything or animating anything as we just want to determine if a solution
2075 // exists
2076 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2077 if (!DESTRUCTIVE_REORDER) {
2078 copySolutionToTempState(finalSolution, dragView);
2079 }
2080 setItemPlacementDirty(true);
2081 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2082
2083 if (!DESTRUCTIVE_REORDER && mode == MODE_ON_DROP) {
2084 commitTempPlacement();
2085 }
2086 }
2087 } else {
2088 foundSolution = false;
2089 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2090 }
2091
2092 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2093 setUseTempCoords(false);
2094 }
2095 boolean[][] occupied = mOccupied;
2096
2097 mChildren.requestLayout();
2098 return result;
2099 }
2100
2101 public boolean isItemPlacementDirty() {
2102 return mItemLocationsDirty;
2103 }
2104
2105 public void setItemPlacementDirty(boolean dirty) {
2106 mItemLocationsDirty = dirty;
2107 }
2108
2109 private class ItemConfiguration {
2110 HashMap<View, Point> map = new HashMap<View, Point>();
2111 boolean isSolution = false;
2112 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2113
2114 int area() {
2115 return dragViewSpanX * dragViewSpanY;
2116 }
2117 void clear() {
2118 map.clear();
2119 isSolution = false;
2120 }
2121 }
2122
Adam Cohendf035382011-04-11 17:22:04 -07002123 /**
2124 * Find a vacant area that will fit the given bounds nearest the requested
2125 * cell location. Uses Euclidean distance to score multiple vacant areas.
2126 *
2127 * @param pixelX The X location at which you want to search for a vacant area.
2128 * @param pixelY The Y location at which you want to search for a vacant area.
2129 * @param spanX Horizontal span of the object.
2130 * @param spanY Vertical span of the object.
2131 * @param ignoreView Considers space occupied by this view as unoccupied
2132 * @param result Previously returned value to possibly recycle.
2133 * @return The X, Y cell of a vacant area that can contain this object,
2134 * nearest the requested location.
2135 */
2136 int[] findNearestVacantArea(
2137 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2138 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2139 }
2140
2141 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002142 * Find a vacant area that will fit the given bounds nearest the requested
2143 * cell location. Uses Euclidean distance to score multiple vacant areas.
2144 *
2145 * @param pixelX The X location at which you want to search for a vacant area.
2146 * @param pixelY The Y location at which you want to search for a vacant area.
2147 * @param minSpanX The minimum horizontal span required
2148 * @param minSpanY The minimum vertical span required
2149 * @param spanX Horizontal span of the object.
2150 * @param spanY Vertical span of the object.
2151 * @param ignoreView Considers space occupied by this view as unoccupied
2152 * @param result Previously returned value to possibly recycle.
2153 * @return The X, Y cell of a vacant area that can contain this object,
2154 * nearest the requested location.
2155 */
2156 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2157 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002158 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2159 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002160 }
2161
2162 /**
Adam Cohendf035382011-04-11 17:22:04 -07002163 * Find a starting cell position that will fit the given bounds nearest the requested
2164 * cell location. Uses Euclidean distance to score multiple vacant areas.
2165 *
2166 * @param pixelX The X location at which you want to search for a vacant area.
2167 * @param pixelY The Y location at which you want to search for a vacant area.
2168 * @param spanX Horizontal span of the object.
2169 * @param spanY Vertical span of the object.
2170 * @param ignoreView Considers space occupied by this view as unoccupied
2171 * @param result Previously returned value to possibly recycle.
2172 * @return The X, Y cell of a vacant area that can contain this object,
2173 * nearest the requested location.
2174 */
2175 int[] findNearestArea(
2176 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2177 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2178 }
2179
Michael Jurka0280c3b2010-09-17 15:00:07 -07002180 boolean existsEmptyCell() {
2181 return findCellForSpan(null, 1, 1);
2182 }
2183
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002184 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002185 * Finds the upper-left coordinate of the first rectangle in the grid that can
2186 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2187 * then this method will only return coordinates for rectangles that contain the cell
2188 * (intersectX, intersectY)
2189 *
2190 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2191 * can be found.
2192 * @param spanX The horizontal span of the cell we want to find.
2193 * @param spanY The vertical span of the cell we want to find.
2194 *
2195 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002196 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002197 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002198 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002199 }
2200
2201 /**
2202 * Like above, but ignores any cells occupied by the item "ignoreView"
2203 *
2204 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2205 * can be found.
2206 * @param spanX The horizontal span of the cell we want to find.
2207 * @param spanY The vertical span of the cell we want to find.
2208 * @param ignoreView The home screen item we should treat as not occupying any space
2209 * @return
2210 */
2211 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002212 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2213 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002214 }
2215
2216 /**
2217 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2218 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2219 *
2220 * @param spanX The horizontal span of the cell we want to find.
2221 * @param spanY The vertical span of the cell we want to find.
2222 * @param ignoreView The home screen item we should treat as not occupying any space
2223 * @param intersectX The X coordinate of the cell that we should try to overlap
2224 * @param intersectX The Y coordinate of the cell that we should try to overlap
2225 *
2226 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2227 */
2228 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2229 int intersectX, int intersectY) {
2230 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002231 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002232 }
2233
2234 /**
2235 * The superset of the above two methods
2236 */
2237 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002238 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002239 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002240 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002241
Michael Jurka28750fb2010-09-24 17:43:49 -07002242 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002243 while (true) {
2244 int startX = 0;
2245 if (intersectX >= 0) {
2246 startX = Math.max(startX, intersectX - (spanX - 1));
2247 }
2248 int endX = mCountX - (spanX - 1);
2249 if (intersectX >= 0) {
2250 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2251 }
2252 int startY = 0;
2253 if (intersectY >= 0) {
2254 startY = Math.max(startY, intersectY - (spanY - 1));
2255 }
2256 int endY = mCountY - (spanY - 1);
2257 if (intersectY >= 0) {
2258 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2259 }
2260
Winson Chungbbc60d82010-11-11 16:34:41 -08002261 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002262 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002263 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002264 for (int i = 0; i < spanX; i++) {
2265 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002266 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002267 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002268 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002269 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002270 continue inner;
2271 }
2272 }
2273 }
2274 if (cellXY != null) {
2275 cellXY[0] = x;
2276 cellXY[1] = y;
2277 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002278 foundCell = true;
2279 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002280 }
2281 }
2282 if (intersectX == -1 && intersectY == -1) {
2283 break;
2284 } else {
2285 // if we failed to find anything, try again but without any requirements of
2286 // intersecting
2287 intersectX = -1;
2288 intersectY = -1;
2289 continue;
2290 }
2291 }
2292
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002293 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002294 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002295 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002296 }
2297
2298 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002299 * A drag event has begun over this layout.
2300 * It may have begun over this layout (in which case onDragChild is called first),
2301 * or it may have begun on another layout.
2302 */
2303 void onDragEnter() {
2304 if (!mDragging) {
2305 // Fade in the drag indicators
2306 if (mCrosshairsAnimator != null) {
2307 mCrosshairsAnimator.animateIn();
2308 }
2309 }
2310 mDragging = true;
2311 }
2312
2313 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002314 * Called when drag has left this CellLayout or has been completed (successfully or not)
2315 */
2316 void onDragExit() {
Joe Onorato4be866d2010-10-10 11:26:02 -07002317 // This can actually be called when we aren't in a drag, e.g. when adding a new
2318 // item to this layout via the customize drawer.
2319 // Guard against that case.
2320 if (mDragging) {
2321 mDragging = false;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002322
Joe Onorato4be866d2010-10-10 11:26:02 -07002323 // Fade out the drag indicators
2324 if (mCrosshairsAnimator != null) {
2325 mCrosshairsAnimator.animateOut();
2326 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002327 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002328
2329 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002330 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002331 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2332 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
2333
Michael Jurka33945b22010-12-21 18:19:38 -08002334 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002335 }
2336
2337 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002338 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002339 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002340 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002341 *
2342 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002343 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002344 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002345 if (child != null) {
2346 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002347 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002348 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002349 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002350 }
2351
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002352 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002353 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002354 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002355 * @param cellX X coordinate of upper left corner expressed as a cell position
2356 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002357 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002358 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002359 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002360 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002361 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002362 final int cellWidth = mCellWidth;
2363 final int cellHeight = mCellHeight;
2364 final int widthGap = mWidthGap;
2365 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002366
Winson Chung4b825dcd2011-06-19 12:41:22 -07002367 final int hStartPadding = getPaddingLeft();
2368 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002369
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002370 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2371 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2372
2373 int x = hStartPadding + cellX * (cellWidth + widthGap);
2374 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002375
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002376 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002377 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002378
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002379 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002380 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002381 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002382 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002383 * @param width Width in pixels
2384 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002385 * @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 -08002386 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002387 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002388 return rectToCell(getResources(), width, height, result);
2389 }
2390
2391 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002392 // Always assume we're working with the smallest span to make sure we
2393 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002394 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2395 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002396 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002397
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002398 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002399 int spanX = (int) Math.ceil(width / (float) smallerSize);
2400 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002401
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002402 if (result == null) {
2403 return new int[] { spanX, spanY };
2404 }
2405 result[0] = spanX;
2406 result[1] = spanY;
2407 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002408 }
2409
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002410 public int[] cellSpansToSize(int hSpans, int vSpans) {
2411 int[] size = new int[2];
2412 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2413 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2414 return size;
2415 }
2416
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002417 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002418 * Calculate the grid spans needed to fit given item
2419 */
2420 public void calculateSpans(ItemInfo info) {
2421 final int minWidth;
2422 final int minHeight;
2423
2424 if (info instanceof LauncherAppWidgetInfo) {
2425 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2426 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2427 } else if (info instanceof PendingAddWidgetInfo) {
2428 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2429 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2430 } else {
2431 // It's not a widget, so it must be 1x1
2432 info.spanX = info.spanY = 1;
2433 return;
2434 }
2435 int[] spans = rectToCell(minWidth, minHeight, null);
2436 info.spanX = spans[0];
2437 info.spanY = spans[1];
2438 }
2439
2440 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002441 * Find the first vacant cell, if there is one.
2442 *
2443 * @param vacant Holds the x and y coordinate of the vacant cell
2444 * @param spanX Horizontal cell span.
2445 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002446 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002447 * @return True if a vacant cell was found
2448 */
2449 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002450
Michael Jurka0280c3b2010-09-17 15:00:07 -07002451 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002452 }
2453
2454 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2455 int xCount, int yCount, boolean[][] occupied) {
2456
Adam Cohen2801caf2011-05-13 20:57:39 -07002457 for (int y = 0; y < yCount; y++) {
2458 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002459 boolean available = !occupied[x][y];
2460out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2461 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2462 available = available && !occupied[i][j];
2463 if (!available) break out;
2464 }
2465 }
2466
2467 if (available) {
2468 vacant[0] = x;
2469 vacant[1] = y;
2470 return true;
2471 }
2472 }
2473 }
2474
2475 return false;
2476 }
2477
Michael Jurka0280c3b2010-09-17 15:00:07 -07002478 private void clearOccupiedCells() {
2479 for (int x = 0; x < mCountX; x++) {
2480 for (int y = 0; y < mCountY; y++) {
2481 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002482 }
2483 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002484 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002485
Adam Cohen1b607ed2011-03-03 17:26:50 -08002486 /**
2487 * Given a view, determines how much that view can be expanded in all directions, in terms of
2488 * whether or not there are other items occupying adjacent cells. Used by the
2489 * AppWidgetResizeFrame to determine how the widget can be resized.
2490 */
Adam Cohend4844c32011-02-18 19:25:06 -08002491 public void getExpandabilityArrayForView(View view, int[] expandability) {
Adam Cohen1b607ed2011-03-03 17:26:50 -08002492 final LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohend4844c32011-02-18 19:25:06 -08002493 boolean flag;
2494
Adam Cohen1b607ed2011-03-03 17:26:50 -08002495 expandability[AppWidgetResizeFrame.LEFT] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002496 for (int x = lp.cellX - 1; x >= 0; x--) {
2497 flag = false;
2498 for (int y = lp.cellY; y < lp.cellY + lp.cellVSpan; y++) {
2499 if (mOccupied[x][y]) flag = true;
2500 }
2501 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002502 expandability[AppWidgetResizeFrame.LEFT]++;
Adam Cohend4844c32011-02-18 19:25:06 -08002503 }
2504
Adam Cohen1b607ed2011-03-03 17:26:50 -08002505 expandability[AppWidgetResizeFrame.TOP] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002506 for (int y = lp.cellY - 1; y >= 0; y--) {
2507 flag = false;
2508 for (int x = lp.cellX; x < lp.cellX + lp.cellHSpan; x++) {
2509 if (mOccupied[x][y]) flag = true;
2510 }
2511 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002512 expandability[AppWidgetResizeFrame.TOP]++;
2513 }
Adam Cohend4844c32011-02-18 19:25:06 -08002514
Adam Cohen1b607ed2011-03-03 17:26:50 -08002515 expandability[AppWidgetResizeFrame.RIGHT] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002516 for (int x = lp.cellX + lp.cellHSpan; x < mCountX; x++) {
2517 flag = false;
2518 for (int y = lp.cellY; y < lp.cellY + lp.cellVSpan; y++) {
2519 if (mOccupied[x][y]) flag = true;
2520 }
2521 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002522 expandability[AppWidgetResizeFrame.RIGHT]++;
2523 }
Adam Cohend4844c32011-02-18 19:25:06 -08002524
Adam Cohen1b607ed2011-03-03 17:26:50 -08002525 expandability[AppWidgetResizeFrame.BOTTOM] = 0;
Adam Cohend4844c32011-02-18 19:25:06 -08002526 for (int y = lp.cellY + lp.cellVSpan; y < mCountY; y++) {
2527 flag = false;
2528 for (int x = lp.cellX; x < lp.cellX + lp.cellHSpan; x++) {
2529 if (mOccupied[x][y]) flag = true;
2530 }
2531 if (flag) break;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002532 expandability[AppWidgetResizeFrame.BOTTOM]++;
2533 }
Adam Cohend4844c32011-02-18 19:25:06 -08002534 }
2535
Adam Cohend41fbf52012-02-16 23:53:59 -08002536 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002537 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002538 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002539 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002540
Adam Cohend4844c32011-02-18 19:25:06 -08002541 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002542 markCellsAsOccupiedForView(view, mOccupied);
2543 }
2544 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08002545 if (view == null || view.getParent() != mChildren) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002546 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002547 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002548 }
2549
Adam Cohend4844c32011-02-18 19:25:06 -08002550 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002551 markCellsAsUnoccupiedForView(view, mOccupied);
2552 }
2553 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurka8c920dd2011-01-20 14:16:56 -08002554 if (view == null || view.getParent() != mChildren) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002555 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002556 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002557 }
2558
Adam Cohen482ed822012-03-02 14:15:13 -08002559 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2560 boolean value) {
2561 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002562 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2563 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002564 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002565 }
2566 }
2567 }
2568
Adam Cohen2801caf2011-05-13 20:57:39 -07002569 public int getDesiredWidth() {
Winson Chung4b825dcd2011-06-19 12:41:22 -07002570 return mPaddingLeft + mPaddingRight + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002571 (Math.max((mCountX - 1), 0) * mWidthGap);
2572 }
2573
2574 public int getDesiredHeight() {
Winson Chung4b825dcd2011-06-19 12:41:22 -07002575 return mPaddingTop + mPaddingBottom + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002576 (Math.max((mCountY - 1), 0) * mHeightGap);
2577 }
2578
Michael Jurka66d72172011-04-12 16:29:25 -07002579 public boolean isOccupied(int x, int y) {
2580 if (x < mCountX && y < mCountY) {
2581 return mOccupied[x][y];
2582 } else {
2583 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2584 }
2585 }
2586
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002587 @Override
2588 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2589 return new CellLayout.LayoutParams(getContext(), attrs);
2590 }
2591
2592 @Override
2593 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2594 return p instanceof CellLayout.LayoutParams;
2595 }
2596
2597 @Override
2598 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2599 return new CellLayout.LayoutParams(p);
2600 }
2601
Winson Chungaafa03c2010-06-11 17:34:16 -07002602 public static class CellLayoutAnimationController extends LayoutAnimationController {
2603 public CellLayoutAnimationController(Animation animation, float delay) {
2604 super(animation, delay);
2605 }
2606
2607 @Override
2608 protected long getDelayForView(View view) {
2609 return (int) (Math.random() * 150);
2610 }
2611 }
2612
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002613 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2614 /**
2615 * Horizontal location of the item in the grid.
2616 */
2617 @ViewDebug.ExportedProperty
2618 public int cellX;
2619
2620 /**
2621 * Vertical location of the item in the grid.
2622 */
2623 @ViewDebug.ExportedProperty
2624 public int cellY;
2625
2626 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002627 * Temporary horizontal location of the item in the grid during reorder
2628 */
2629 public int tmpCellX;
2630
2631 /**
2632 * Temporary vertical location of the item in the grid during reorder
2633 */
2634 public int tmpCellY;
2635
2636 /**
2637 * Indicates that the temporary coordinates should be used to layout the items
2638 */
2639 public boolean useTmpCoords;
2640
2641 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002642 * Number of cells spanned horizontally by the item.
2643 */
2644 @ViewDebug.ExportedProperty
2645 public int cellHSpan;
2646
2647 /**
2648 * Number of cells spanned vertically by the item.
2649 */
2650 @ViewDebug.ExportedProperty
2651 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002652
Adam Cohen1b607ed2011-03-03 17:26:50 -08002653 /**
2654 * Indicates whether the item will set its x, y, width and height parameters freely,
2655 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2656 */
Adam Cohend4844c32011-02-18 19:25:06 -08002657 public boolean isLockedToGrid = true;
2658
Adam Cohen482ed822012-03-02 14:15:13 -08002659 /**
2660 * Indicates whether this item can be reordered. Always true except in the case of the
2661 * the AllApps button.
2662 */
2663 public boolean canReorder = true;
2664
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002665 // X coordinate of the view in the layout.
2666 @ViewDebug.ExportedProperty
2667 int x;
2668 // Y coordinate of the view in the layout.
2669 @ViewDebug.ExportedProperty
2670 int y;
2671
Romain Guy84f296c2009-11-04 15:00:44 -08002672 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002673
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002674 public LayoutParams(Context c, AttributeSet attrs) {
2675 super(c, attrs);
2676 cellHSpan = 1;
2677 cellVSpan = 1;
2678 }
2679
2680 public LayoutParams(ViewGroup.LayoutParams source) {
2681 super(source);
2682 cellHSpan = 1;
2683 cellVSpan = 1;
2684 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002685
2686 public LayoutParams(LayoutParams source) {
2687 super(source);
2688 this.cellX = source.cellX;
2689 this.cellY = source.cellY;
2690 this.cellHSpan = source.cellHSpan;
2691 this.cellVSpan = source.cellVSpan;
2692 }
2693
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002694 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002695 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002696 this.cellX = cellX;
2697 this.cellY = cellY;
2698 this.cellHSpan = cellHSpan;
2699 this.cellVSpan = cellVSpan;
2700 }
2701
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002702 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002703 if (isLockedToGrid) {
2704 final int myCellHSpan = cellHSpan;
2705 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002706 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2707 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002708
Adam Cohend4844c32011-02-18 19:25:06 -08002709 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2710 leftMargin - rightMargin;
2711 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2712 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002713 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2714 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002715 }
2716 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002717
Winson Chungaafa03c2010-06-11 17:34:16 -07002718 public String toString() {
2719 return "(" + this.cellX + ", " + this.cellY + ")";
2720 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002721
2722 public void setWidth(int width) {
2723 this.width = width;
2724 }
2725
2726 public int getWidth() {
2727 return width;
2728 }
2729
2730 public void setHeight(int height) {
2731 this.height = height;
2732 }
2733
2734 public int getHeight() {
2735 return height;
2736 }
2737
2738 public void setX(int x) {
2739 this.x = x;
2740 }
2741
2742 public int getX() {
2743 return x;
2744 }
2745
2746 public void setY(int y) {
2747 this.y = y;
2748 }
2749
2750 public int getY() {
2751 return y;
2752 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002753 }
2754
Michael Jurka0280c3b2010-09-17 15:00:07 -07002755 // This class stores info for two purposes:
2756 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
2757 // its spanX, spanY, and the screen it is on
2758 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
2759 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
2760 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07002761 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002762 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07002763 int cellX = -1;
2764 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002765 int spanX;
2766 int spanY;
2767 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07002768 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002769
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002770 @Override
2771 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07002772 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
2773 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002774 }
2775 }
Michael Jurkad771c962011-08-09 15:00:48 -07002776
2777 public boolean lastDownOnOccupiedCell() {
2778 return mLastDownOnOccupiedCell;
2779 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002780}