blob: aa8c1323d38b08fef601b18dcdb85d9fb7987ca1 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Joe Onoratoa5902522009-07-30 13:37:37 -070017package com.android.launcher2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080018
Joe Onorato4be866d2010-10-10 11:26:02 -070019import android.animation.Animator;
Michael Jurka629758f2012-06-14 16:18:21 -070020import android.animation.AnimatorListenerAdapter;
Brandon Keely50e6e562012-05-08 16:28:49 -070021import android.animation.AnimatorSet;
Chet Haase00397b12010-10-07 11:13:10 -070022import android.animation.TimeInterpolator;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070023import android.animation.ValueAnimator;
24import android.animation.ValueAnimator.AnimatorUpdateListener;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080025import android.content.Context;
Joe Onorato79e56262009-09-21 15:23:04 -040026import android.content.res.Resources;
Winson Chungaafa03c2010-06-11 17:34:16 -070027import android.content.res.TypedArray;
Joe Onorato4be866d2010-10-10 11:26:02 -070028import android.graphics.Bitmap;
Winson Chungaafa03c2010-06-11 17:34:16 -070029import android.graphics.Canvas;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -080030import android.graphics.Color;
Joe Onorato4be866d2010-10-10 11:26:02 -070031import android.graphics.Paint;
Patrick Dubroyde7658b2010-09-27 11:15:43 -070032import android.graphics.Point;
Adam Cohenb5ba0972011-09-07 18:02:31 -070033import android.graphics.PorterDuff;
34import android.graphics.PorterDuffXfermode;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.graphics.Rect;
Adam Cohen482ed822012-03-02 14:15:13 -080036import android.graphics.drawable.ColorDrawable;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070037import android.graphics.drawable.Drawable;
Adam Cohenb5ba0972011-09-07 18:02:31 -070038import android.graphics.drawable.NinePatchDrawable;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080039import android.util.AttributeSet;
Joe Onorato4be866d2010-10-10 11:26:02 -070040import android.util.Log;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.view.MotionEvent;
42import android.view.View;
43import android.view.ViewDebug;
44import android.view.ViewGroup;
Winson Chungaafa03c2010-06-11 17:34:16 -070045import android.view.animation.Animation;
Winson Chung150fbab2010-09-29 17:14:26 -070046import android.view.animation.DecelerateInterpolator;
Winson Chungaafa03c2010-06-11 17:34:16 -070047import android.view.animation.LayoutAnimationController;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080048
Adam Cohen66396872011-04-15 17:50:36 -070049import com.android.launcher.R;
Adam Cohen69ce2e52011-07-03 19:25:21 -070050import com.android.launcher2.FolderIcon.FolderRingAnimator;
Patrick Dubroy8e58e912010-10-14 13:21:48 -070051
Adam Cohen69ce2e52011-07-03 19:25:21 -070052import java.util.ArrayList;
Adam Cohenc0dcf592011-06-01 15:30:43 -070053import java.util.Arrays;
Adam Cohenbfbfd262011-06-13 16:55:12 -070054import java.util.HashMap;
Adam Cohend41fbf52012-02-16 23:53:59 -080055import java.util.Stack;
Adam Cohenc0dcf592011-06-01 15:30:43 -070056
Michael Jurkabdb5c532011-02-01 15:05:06 -080057public class CellLayout extends ViewGroup {
Winson Chungaafa03c2010-06-11 17:34:16 -070058 static final String TAG = "CellLayout";
59
Adam Cohen2acce882012-03-28 19:03:19 -070060 private Launcher mLauncher;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061 private int mCellWidth;
62 private int mCellHeight;
Winson Chungaafa03c2010-06-11 17:34:16 -070063
Adam Cohend22015c2010-07-26 22:02:18 -070064 private int mCountX;
65 private int mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080066
Adam Cohen234c4cd2011-07-17 21:03:04 -070067 private int mOriginalWidthGap;
68 private int mOriginalHeightGap;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080069 private int mWidthGap;
70 private int mHeightGap;
Winson Chung4b825dcd2011-06-19 12:41:22 -070071 private int mMaxGap;
Adam Cohenebea84d2011-11-09 17:20:41 -080072 private boolean mScrollingTransformsDirty = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073
74 private final Rect mRect = new Rect();
75 private final CellInfo mCellInfo = new CellInfo();
Winson Chungaafa03c2010-06-11 17:34:16 -070076
Patrick Dubroyde7658b2010-09-27 11:15:43 -070077 // These are temporary variables to prevent having to allocate a new object just to
78 // return an (x, y) value from helper functions. Do NOT use them to maintain other state.
Winson Chung0be025d2011-05-23 17:45:09 -070079 private final int[] mTmpXY = new int[2];
Patrick Dubroyde7658b2010-09-27 11:15:43 -070080 private final int[] mTmpPoint = new int[2];
Adam Cohen69ce2e52011-07-03 19:25:21 -070081 int[] mTempLocation = new int[2];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -070082
The Android Open Source Project31dd5032009-03-03 19:32:27 -080083 boolean[][] mOccupied;
Adam Cohen482ed822012-03-02 14:15:13 -080084 boolean[][] mTmpOccupied;
Michael Jurkad771c962011-08-09 15:00:48 -070085 private boolean mLastDownOnOccupiedCell = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
Michael Jurkadee05892010-07-27 10:01:56 -070087 private OnTouchListener mInterceptTouchListener;
88
Adam Cohen69ce2e52011-07-03 19:25:21 -070089 private ArrayList<FolderRingAnimator> mFolderOuterRings = new ArrayList<FolderRingAnimator>();
Adam Cohenc51934b2011-07-26 21:07:43 -070090 private int[] mFolderLeaveBehindCell = {-1, -1};
Adam Cohen69ce2e52011-07-03 19:25:21 -070091
Adam Cohenb5ba0972011-09-07 18:02:31 -070092 private int mForegroundAlpha = 0;
Michael Jurka5f1c5092010-09-03 14:15:02 -070093 private float mBackgroundAlpha;
Adam Cohen1b0aaac2010-10-28 11:11:18 -070094 private float mBackgroundAlphaMultiplier = 1.0f;
Adam Cohenf34bab52010-09-30 14:11:56 -070095
Michael Jurka33945b22010-12-21 18:19:38 -080096 private Drawable mNormalBackground;
Michael Jurka33945b22010-12-21 18:19:38 -080097 private Drawable mActiveGlowBackground;
Adam Cohenb5ba0972011-09-07 18:02:31 -070098 private Drawable mOverScrollForegroundDrawable;
99 private Drawable mOverScrollLeft;
100 private Drawable mOverScrollRight;
Michael Jurka18014792010-10-14 09:01:34 -0700101 private Rect mBackgroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700102 private Rect mForegroundRect;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700103 private int mForegroundPadding;
Patrick Dubroy1262e362010-10-06 15:49:50 -0700104
Michael Jurka33945b22010-12-21 18:19:38 -0800105 // If we're actively dragging something over this screen, mIsDragOverlapping is true
106 private boolean mIsDragOverlapping = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700107 private final Point mDragCenter = new Point();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700108
Winson Chung150fbab2010-09-29 17:14:26 -0700109 // These arrays are used to implement the drag visualization on x-large screens.
Joe Onorato4be866d2010-10-10 11:26:02 -0700110 // They are used as circular arrays, indexed by mDragOutlineCurrent.
Adam Cohend41fbf52012-02-16 23:53:59 -0800111 private Rect[] mDragOutlines = new Rect[4];
Chet Haase472b2812010-10-14 07:02:04 -0700112 private float[] mDragOutlineAlphas = new float[mDragOutlines.length];
Joe Onorato4be866d2010-10-10 11:26:02 -0700113 private InterruptibleInOutAnimator[] mDragOutlineAnims =
114 new InterruptibleInOutAnimator[mDragOutlines.length];
Winson Chung150fbab2010-09-29 17:14:26 -0700115
116 // Used as an index into the above 3 arrays; indicates which is the most current value.
Joe Onorato4be866d2010-10-10 11:26:02 -0700117 private int mDragOutlineCurrent = 0;
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700118 private final Paint mDragOutlinePaint = new Paint();
Winson Chung150fbab2010-09-29 17:14:26 -0700119
Patrick Dubroy96864c32011-03-10 17:17:23 -0800120 private BubbleTextView mPressedOrFocusedIcon;
121
Adam Cohen482ed822012-03-02 14:15:13 -0800122 private HashMap<CellLayout.LayoutParams, Animator> mReorderAnimators = new
123 HashMap<CellLayout.LayoutParams, Animator>();
Adam Cohen19f37922012-03-21 11:59:11 -0700124 private HashMap<View, ReorderHintAnimation>
125 mShakeAnimators = new HashMap<View, ReorderHintAnimation>();
126
127 private boolean mItemPlacementDirty = false;
Adam Cohenbfbfd262011-06-13 16:55:12 -0700128
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700129 // When a drag operation is in progress, holds the nearest cell to the touch point
130 private final int[] mDragCell = new int[2];
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800131
Joe Onorato4be866d2010-10-10 11:26:02 -0700132 private boolean mDragging = false;
133
Patrick Dubroyce34a972010-10-19 10:34:32 -0700134 private TimeInterpolator mEaseOutInterpolator;
Michael Jurkaa52570f2012-03-20 03:18:20 -0700135 private ShortcutAndWidgetContainer mShortcutsAndWidgets;
Patrick Dubroyce34a972010-10-19 10:34:32 -0700136
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800137 private boolean mIsHotseat = false;
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800138
Adam Cohen482ed822012-03-02 14:15:13 -0800139 public static final int MODE_DRAG_OVER = 0;
140 public static final int MODE_ON_DROP = 1;
141 public static final int MODE_ON_DROP_EXTERNAL = 2;
142 public static final int MODE_ACCEPT_DROP = 3;
Adam Cohen19f37922012-03-21 11:59:11 -0700143 private static final boolean DESTRUCTIVE_REORDER = false;
Adam Cohen482ed822012-03-02 14:15:13 -0800144 private static final boolean DEBUG_VISUALIZE_OCCUPIED = false;
145
Adam Cohena897f392012-04-27 18:12:05 -0700146 static final int LANDSCAPE = 0;
147 static final int PORTRAIT = 1;
148
Adam Cohen7bdfc972012-05-22 16:50:35 -0700149 private static final float REORDER_HINT_MAGNITUDE = 0.12f;
Adam Cohen19f37922012-03-21 11:59:11 -0700150 private static final int REORDER_ANIMATION_DURATION = 150;
151 private float mReorderHintAnimationMagnitude;
152
Adam Cohen482ed822012-03-02 14:15:13 -0800153 private ArrayList<View> mIntersectingViews = new ArrayList<View>();
154 private Rect mOccupiedRect = new Rect();
155 private int[] mDirectionVector = new int[2];
Adam Cohen19f37922012-03-21 11:59:11 -0700156 int[] mPreviousReorderDirection = new int[2];
Adam Cohenb209e632012-03-27 17:09:36 -0700157 private static final int INVALID_DIRECTION = -100;
Adam Cohenc6cc61d2012-04-04 12:47:08 -0700158 private DropTarget.DragEnforcer mDragEnforcer;
Adam Cohen482ed822012-03-02 14:15:13 -0800159
Romain Guy8a0bff52012-05-06 13:14:33 -0700160 private final static PorterDuffXfermode sAddBlendMode =
161 new PorterDuffXfermode(PorterDuff.Mode.ADD);
Michael Jurkaca993832012-06-29 15:17:04 -0700162 private final static Paint sPaint = new Paint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700163
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800164 public CellLayout(Context context) {
165 this(context, null);
166 }
167
168 public CellLayout(Context context, AttributeSet attrs) {
169 this(context, attrs, 0);
170 }
171
172 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
173 super(context, attrs, defStyle);
Michael Jurka8b805b12012-04-18 14:23:14 -0700174 mDragEnforcer = new DropTarget.DragEnforcer(context);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700175
176 // A ViewGroup usually does not draw, but CellLayout needs to draw a rectangle to show
177 // the user where a dragged item will land when dropped.
178 setWillNotDraw(false);
Adam Cohen2acce882012-03-28 19:03:19 -0700179 mLauncher = (Launcher) context;
Michael Jurkaa63c4522010-08-19 13:52:27 -0700180
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800181 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
182
Adam Cohenf4bd5792012-04-27 11:35:29 -0700183 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
184 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700185 mWidthGap = mOriginalWidthGap = a.getDimensionPixelSize(R.styleable.CellLayout_widthGap, 0);
186 mHeightGap = mOriginalHeightGap = a.getDimensionPixelSize(R.styleable.CellLayout_heightGap, 0);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700187 mMaxGap = a.getDimensionPixelSize(R.styleable.CellLayout_maxGap, 0);
Adam Cohend22015c2010-07-26 22:02:18 -0700188 mCountX = LauncherModel.getCellCountX();
189 mCountY = LauncherModel.getCellCountY();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700190 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800191 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen5b53f292012-03-29 14:30:35 -0700192 mPreviousReorderDirection[0] = INVALID_DIRECTION;
193 mPreviousReorderDirection[1] = INVALID_DIRECTION;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800194
195 a.recycle();
196
197 setAlwaysDrawnWithCacheEnabled(false);
198
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700199 final Resources res = getResources();
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700200
Winson Chung967289b2011-06-30 18:09:30 -0700201 mNormalBackground = res.getDrawable(R.drawable.homescreen_blue_normal_holo);
Winson Chungdea74b72011-09-13 18:06:43 -0700202 mActiveGlowBackground = res.getDrawable(R.drawable.homescreen_blue_strong_holo);
Michael Jurka33945b22010-12-21 18:19:38 -0800203
Adam Cohenb5ba0972011-09-07 18:02:31 -0700204 mOverScrollLeft = res.getDrawable(R.drawable.overscroll_glow_left);
205 mOverScrollRight = res.getDrawable(R.drawable.overscroll_glow_right);
206 mForegroundPadding =
207 res.getDimensionPixelSize(R.dimen.workspace_overscroll_drawable_padding);
Michael Jurka33945b22010-12-21 18:19:38 -0800208
Adam Cohen19f37922012-03-21 11:59:11 -0700209 mReorderHintAnimationMagnitude = (REORDER_HINT_MAGNITUDE *
210 res.getDimensionPixelSize(R.dimen.app_icon_size));
211
Winson Chungb26f3d62011-06-02 10:49:29 -0700212 mNormalBackground.setFilterBitmap(true);
Winson Chungb26f3d62011-06-02 10:49:29 -0700213 mActiveGlowBackground.setFilterBitmap(true);
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700214
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700215 // Initialize the data structures used for the drag visualization.
Winson Chung150fbab2010-09-29 17:14:26 -0700216
Patrick Dubroyce34a972010-10-19 10:34:32 -0700217 mEaseOutInterpolator = new DecelerateInterpolator(2.5f); // Quint ease out
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700218
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700219
Winson Chungb8c69f32011-10-19 21:36:08 -0700220 mDragCell[0] = mDragCell[1] = -1;
Joe Onorato4be866d2010-10-10 11:26:02 -0700221 for (int i = 0; i < mDragOutlines.length; i++) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800222 mDragOutlines[i] = new Rect(-1, -1, -1, -1);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700223 }
224
225 // When dragging things around the home screens, we show a green outline of
226 // where the item will land. The outlines gradually fade out, leaving a trail
227 // behind the drag path.
228 // Set up all the animations that are used to implement this fading.
229 final int duration = res.getInteger(R.integer.config_dragOutlineFadeTime);
Chet Haase472b2812010-10-14 07:02:04 -0700230 final float fromAlphaValue = 0;
231 final float toAlphaValue = (float)res.getInteger(R.integer.config_dragOutlineMaxAlpha);
Joe Onorato4be866d2010-10-10 11:26:02 -0700232
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700233 Arrays.fill(mDragOutlineAlphas, fromAlphaValue);
Joe Onorato4be866d2010-10-10 11:26:02 -0700234
235 for (int i = 0; i < mDragOutlineAnims.length; i++) {
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700236 final InterruptibleInOutAnimator anim =
237 new InterruptibleInOutAnimator(duration, fromAlphaValue, toAlphaValue);
Patrick Dubroyce34a972010-10-19 10:34:32 -0700238 anim.getAnimator().setInterpolator(mEaseOutInterpolator);
Patrick Dubroy046e7eb2010-10-06 12:14:43 -0700239 final int thisIndex = i;
Chet Haase472b2812010-10-14 07:02:04 -0700240 anim.getAnimator().addUpdateListener(new AnimatorUpdateListener() {
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700241 public void onAnimationUpdate(ValueAnimator animation) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700242 final Bitmap outline = (Bitmap)anim.getTag();
243
244 // If an animation is started and then stopped very quickly, we can still
245 // get spurious updates we've cleared the tag. Guard against this.
246 if (outline == null) {
Michael Jurka3a9fced2012-04-13 14:44:29 -0700247 @SuppressWarnings("all") // suppress dead code warning
248 final boolean debug = false;
249 if (debug) {
Patrick Dubroyfe6bd872010-10-13 17:32:10 -0700250 Object val = animation.getAnimatedValue();
251 Log.d(TAG, "anim " + thisIndex + " update: " + val +
252 ", isStopped " + anim.isStopped());
253 }
Joe Onorato4be866d2010-10-10 11:26:02 -0700254 // Try to prevent it from continuing to run
255 animation.cancel();
256 } else {
Chet Haase472b2812010-10-14 07:02:04 -0700257 mDragOutlineAlphas[thisIndex] = (Float) animation.getAnimatedValue();
Adam Cohend41fbf52012-02-16 23:53:59 -0800258 CellLayout.this.invalidate(mDragOutlines[thisIndex]);
Joe Onorato4be866d2010-10-10 11:26:02 -0700259 }
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700260 }
261 });
Joe Onorato4be866d2010-10-10 11:26:02 -0700262 // The animation holds a reference to the drag outline bitmap as long is it's
263 // running. This way the bitmap can be GCed when the animations are complete.
Chet Haase472b2812010-10-14 07:02:04 -0700264 anim.getAnimator().addListener(new AnimatorListenerAdapter() {
Michael Jurka3c4c20f2010-10-28 15:36:06 -0700265 @Override
Joe Onorato4be866d2010-10-10 11:26:02 -0700266 public void onAnimationEnd(Animator animation) {
Chet Haase472b2812010-10-14 07:02:04 -0700267 if ((Float) ((ValueAnimator) animation).getAnimatedValue() == 0f) {
Joe Onorato4be866d2010-10-10 11:26:02 -0700268 anim.setTag(null);
269 }
270 }
271 });
272 mDragOutlineAnims[i] = anim;
Patrick Dubroyde7658b2010-09-27 11:15:43 -0700273 }
Patrick Dubroyce34a972010-10-19 10:34:32 -0700274
Michael Jurka18014792010-10-14 09:01:34 -0700275 mBackgroundRect = new Rect();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700276 mForegroundRect = new Rect();
Michael Jurkabea15192010-11-17 12:33:46 -0800277
Michael Jurkaa52570f2012-03-20 03:18:20 -0700278 mShortcutsAndWidgets = new ShortcutAndWidgetContainer(context);
279 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
280 addView(mShortcutsAndWidgets);
Michael Jurka18014792010-10-14 09:01:34 -0700281 }
282
Michael Jurkaf6440da2011-04-05 14:50:34 -0700283 static int widthInPortrait(Resources r, int numCells) {
284 // We use this method from Workspace to figure out how many rows/columns Launcher should
285 // have. We ignore the left/right padding on CellLayout because it turns out in our design
286 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700287 int cellWidth = r.getDimensionPixelSize(R.dimen.workspace_cell_width);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700288 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
289 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700290
Winson Chung4b825dcd2011-06-19 12:41:22 -0700291 return minGap * (numCells - 1) + cellWidth * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700292 }
293
Michael Jurkaf6440da2011-04-05 14:50:34 -0700294 static int heightInLandscape(Resources r, int numCells) {
295 // We use this method from Workspace to figure out how many rows/columns Launcher should
296 // have. We ignore the left/right padding on CellLayout because it turns out in our design
297 // the padding extends outside the visible screen size, but it looked fine anyway.
Michael Jurkaf6440da2011-04-05 14:50:34 -0700298 int cellHeight = r.getDimensionPixelSize(R.dimen.workspace_cell_height);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700299 int minGap = Math.min(r.getDimensionPixelSize(R.dimen.workspace_width_gap),
300 r.getDimensionPixelSize(R.dimen.workspace_height_gap));
Michael Jurkaf6440da2011-04-05 14:50:34 -0700301
Winson Chung4b825dcd2011-06-19 12:41:22 -0700302 return minGap * (numCells - 1) + cellHeight * numCells;
Michael Jurkaf6440da2011-04-05 14:50:34 -0700303 }
304
Adam Cohen2801caf2011-05-13 20:57:39 -0700305 public void enableHardwareLayers() {
Michael Jurkaca993832012-06-29 15:17:04 -0700306 mShortcutsAndWidgets.setLayerType(LAYER_TYPE_HARDWARE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700307 }
308
309 public void disableHardwareLayers() {
Michael Jurkaca993832012-06-29 15:17:04 -0700310 mShortcutsAndWidgets.setLayerType(LAYER_TYPE_NONE, sPaint);
Michael Jurkad51f33a2012-06-28 15:35:26 -0700311 }
312
313 public void buildHardwareLayer() {
314 mShortcutsAndWidgets.buildLayer();
Adam Cohen2801caf2011-05-13 20:57:39 -0700315 }
316
317 public void setGridSize(int x, int y) {
318 mCountX = x;
319 mCountY = y;
320 mOccupied = new boolean[mCountX][mCountY];
Adam Cohen482ed822012-03-02 14:15:13 -0800321 mTmpOccupied = new boolean[mCountX][mCountY];
Adam Cohen7fbec102012-03-27 12:42:19 -0700322 mTempRectStack.clear();
Adam Cohen76fc0852011-06-17 13:26:23 -0700323 requestLayout();
Adam Cohen2801caf2011-05-13 20:57:39 -0700324 }
325
Patrick Dubroy96864c32011-03-10 17:17:23 -0800326 private void invalidateBubbleTextView(BubbleTextView icon) {
327 final int padding = icon.getPressedOrFocusedBackgroundPadding();
Winson Chung4b825dcd2011-06-19 12:41:22 -0700328 invalidate(icon.getLeft() + getPaddingLeft() - padding,
329 icon.getTop() + getPaddingTop() - padding,
330 icon.getRight() + getPaddingLeft() + padding,
331 icon.getBottom() + getPaddingTop() + padding);
Patrick Dubroy96864c32011-03-10 17:17:23 -0800332 }
333
Adam Cohenb5ba0972011-09-07 18:02:31 -0700334 void setOverScrollAmount(float r, boolean left) {
335 if (left && mOverScrollForegroundDrawable != mOverScrollLeft) {
336 mOverScrollForegroundDrawable = mOverScrollLeft;
337 } else if (!left && mOverScrollForegroundDrawable != mOverScrollRight) {
338 mOverScrollForegroundDrawable = mOverScrollRight;
339 }
340
341 mForegroundAlpha = (int) Math.round((r * 255));
342 mOverScrollForegroundDrawable.setAlpha(mForegroundAlpha);
343 invalidate();
344 }
345
Patrick Dubroy96864c32011-03-10 17:17:23 -0800346 void setPressedOrFocusedIcon(BubbleTextView icon) {
347 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
348 // requires an expanded clip rect (due to the glow's blur radius)
349 BubbleTextView oldIcon = mPressedOrFocusedIcon;
350 mPressedOrFocusedIcon = icon;
351 if (oldIcon != null) {
352 invalidateBubbleTextView(oldIcon);
353 }
354 if (mPressedOrFocusedIcon != null) {
355 invalidateBubbleTextView(mPressedOrFocusedIcon);
356 }
357 }
358
Michael Jurka33945b22010-12-21 18:19:38 -0800359 void setIsDragOverlapping(boolean isDragOverlapping) {
360 if (mIsDragOverlapping != isDragOverlapping) {
361 mIsDragOverlapping = isDragOverlapping;
362 invalidate();
363 }
364 }
365
366 boolean getIsDragOverlapping() {
367 return mIsDragOverlapping;
368 }
369
Adam Cohenebea84d2011-11-09 17:20:41 -0800370 protected void setOverscrollTransformsDirty(boolean dirty) {
371 mScrollingTransformsDirty = dirty;
372 }
373
374 protected void resetOverscrollTransforms() {
375 if (mScrollingTransformsDirty) {
376 setOverscrollTransformsDirty(false);
377 setTranslationX(0);
378 setRotationY(0);
379 // It doesn't matter if we pass true or false here, the important thing is that we
380 // pass 0, which results in the overscroll drawable not being drawn any more.
381 setOverScrollAmount(0, false);
382 setPivotX(getMeasuredWidth() / 2);
383 setPivotY(getMeasuredHeight() / 2);
384 }
385 }
386
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700387 @Override
Patrick Dubroy1262e362010-10-06 15:49:50 -0700388 protected void onDraw(Canvas canvas) {
Michael Jurka3e7c7632010-10-02 16:01:03 -0700389 // When we're large, we are either drawn in a "hover" state (ie when dragging an item to
390 // a neighboring page) or with just a normal background (if backgroundAlpha > 0.0f)
391 // When we're small, we are either drawn normally or in the "accepts drops" state (during
392 // a drag). However, we also drag the mini hover background *over* one of those two
393 // backgrounds
Winson Chungb26f3d62011-06-02 10:49:29 -0700394 if (mBackgroundAlpha > 0.0f) {
Adam Cohenf34bab52010-09-30 14:11:56 -0700395 Drawable bg;
Michael Jurka33945b22010-12-21 18:19:38 -0800396
397 if (mIsDragOverlapping) {
398 // In the mini case, we draw the active_glow bg *over* the active background
Michael Jurkabdf78552011-10-31 14:34:25 -0700399 bg = mActiveGlowBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700400 } else {
Michael Jurkabdf78552011-10-31 14:34:25 -0700401 bg = mNormalBackground;
Adam Cohenf34bab52010-09-30 14:11:56 -0700402 }
Michael Jurka33945b22010-12-21 18:19:38 -0800403
404 bg.setAlpha((int) (mBackgroundAlpha * mBackgroundAlphaMultiplier * 255));
405 bg.setBounds(mBackgroundRect);
406 bg.draw(canvas);
Michael Jurkaa63c4522010-08-19 13:52:27 -0700407 }
Romain Guya6abce82009-11-10 02:54:41 -0800408
Patrick Dubroy8e58e912010-10-14 13:21:48 -0700409 final Paint paint = mDragOutlinePaint;
Joe Onorato4be866d2010-10-10 11:26:02 -0700410 for (int i = 0; i < mDragOutlines.length; i++) {
Chet Haase472b2812010-10-14 07:02:04 -0700411 final float alpha = mDragOutlineAlphas[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700412 if (alpha > 0) {
Adam Cohend41fbf52012-02-16 23:53:59 -0800413 final Rect r = mDragOutlines[i];
Joe Onorato4be866d2010-10-10 11:26:02 -0700414 final Bitmap b = (Bitmap) mDragOutlineAnims[i].getTag();
Chet Haase472b2812010-10-14 07:02:04 -0700415 paint.setAlpha((int)(alpha + .5f));
Adam Cohend41fbf52012-02-16 23:53:59 -0800416 canvas.drawBitmap(b, null, r, paint);
Winson Chung150fbab2010-09-29 17:14:26 -0700417 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700418 }
Patrick Dubroy96864c32011-03-10 17:17:23 -0800419
420 // We draw the pressed or focused BubbleTextView's background in CellLayout because it
421 // requires an expanded clip rect (due to the glow's blur radius)
422 if (mPressedOrFocusedIcon != null) {
423 final int padding = mPressedOrFocusedIcon.getPressedOrFocusedBackgroundPadding();
424 final Bitmap b = mPressedOrFocusedIcon.getPressedOrFocusedBackground();
425 if (b != null) {
426 canvas.drawBitmap(b,
Winson Chung4b825dcd2011-06-19 12:41:22 -0700427 mPressedOrFocusedIcon.getLeft() + getPaddingLeft() - padding,
428 mPressedOrFocusedIcon.getTop() + getPaddingTop() - padding,
Patrick Dubroy96864c32011-03-10 17:17:23 -0800429 null);
430 }
431 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700432
Adam Cohen482ed822012-03-02 14:15:13 -0800433 if (DEBUG_VISUALIZE_OCCUPIED) {
434 int[] pt = new int[2];
435 ColorDrawable cd = new ColorDrawable(Color.RED);
Adam Cohene7587d22012-05-24 18:50:02 -0700436 cd.setBounds(0, 0, mCellWidth, mCellHeight);
Adam Cohen482ed822012-03-02 14:15:13 -0800437 for (int i = 0; i < mCountX; i++) {
438 for (int j = 0; j < mCountY; j++) {
439 if (mOccupied[i][j]) {
440 cellToPoint(i, j, pt);
441 canvas.save();
442 canvas.translate(pt[0], pt[1]);
443 cd.draw(canvas);
444 canvas.restore();
445 }
446 }
447 }
448 }
449
Andrew Flynn850d2e72012-04-26 16:51:20 -0700450 int previewOffset = FolderRingAnimator.sPreviewSize;
451
Adam Cohen69ce2e52011-07-03 19:25:21 -0700452 // The folder outer / inner ring image(s)
453 for (int i = 0; i < mFolderOuterRings.size(); i++) {
454 FolderRingAnimator fra = mFolderOuterRings.get(i);
455
456 // Draw outer ring
457 Drawable d = FolderRingAnimator.sSharedOuterRingDrawable;
458 int width = (int) fra.getOuterRingSize();
459 int height = width;
460 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
461
462 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700463 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700464
465 canvas.save();
466 canvas.translate(centerX - width / 2, centerY - height / 2);
467 d.setBounds(0, 0, width, height);
468 d.draw(canvas);
469 canvas.restore();
470
471 // Draw inner ring
472 d = FolderRingAnimator.sSharedInnerRingDrawable;
473 width = (int) fra.getInnerRingSize();
474 height = width;
475 cellToPoint(fra.mCellX, fra.mCellY, mTempLocation);
476
477 centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700478 centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohen69ce2e52011-07-03 19:25:21 -0700479 canvas.save();
480 canvas.translate(centerX - width / 2, centerY - width / 2);
481 d.setBounds(0, 0, width, height);
482 d.draw(canvas);
483 canvas.restore();
484 }
Adam Cohenc51934b2011-07-26 21:07:43 -0700485
486 if (mFolderLeaveBehindCell[0] >= 0 && mFolderLeaveBehindCell[1] >= 0) {
487 Drawable d = FolderIcon.sSharedFolderLeaveBehind;
488 int width = d.getIntrinsicWidth();
489 int height = d.getIntrinsicHeight();
490
491 cellToPoint(mFolderLeaveBehindCell[0], mFolderLeaveBehindCell[1], mTempLocation);
492 int centerX = mTempLocation[0] + mCellWidth / 2;
Andrew Flynn850d2e72012-04-26 16:51:20 -0700493 int centerY = mTempLocation[1] + previewOffset / 2;
Adam Cohenc51934b2011-07-26 21:07:43 -0700494
495 canvas.save();
496 canvas.translate(centerX - width / 2, centerY - width / 2);
497 d.setBounds(0, 0, width, height);
498 d.draw(canvas);
499 canvas.restore();
500 }
Adam Cohen69ce2e52011-07-03 19:25:21 -0700501 }
502
Adam Cohenb5ba0972011-09-07 18:02:31 -0700503 @Override
504 protected void dispatchDraw(Canvas canvas) {
505 super.dispatchDraw(canvas);
506 if (mForegroundAlpha > 0) {
507 mOverScrollForegroundDrawable.setBounds(mForegroundRect);
508 Paint p = ((NinePatchDrawable) mOverScrollForegroundDrawable).getPaint();
Romain Guy8a0bff52012-05-06 13:14:33 -0700509 p.setXfermode(sAddBlendMode);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700510 mOverScrollForegroundDrawable.draw(canvas);
511 p.setXfermode(null);
512 }
513 }
514
Adam Cohen69ce2e52011-07-03 19:25:21 -0700515 public void showFolderAccept(FolderRingAnimator fra) {
516 mFolderOuterRings.add(fra);
517 }
518
519 public void hideFolderAccept(FolderRingAnimator fra) {
520 if (mFolderOuterRings.contains(fra)) {
521 mFolderOuterRings.remove(fra);
522 }
523 invalidate();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700524 }
525
Adam Cohenc51934b2011-07-26 21:07:43 -0700526 public void setFolderLeaveBehindCell(int x, int y) {
527 mFolderLeaveBehindCell[0] = x;
528 mFolderLeaveBehindCell[1] = y;
529 invalidate();
530 }
531
532 public void clearFolderLeaveBehind() {
533 mFolderLeaveBehindCell[0] = -1;
534 mFolderLeaveBehindCell[1] = -1;
535 invalidate();
536 }
537
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700538 @Override
Michael Jurkae6235dd2011-10-04 15:02:05 -0700539 public boolean shouldDelayChildPressedState() {
540 return false;
541 }
542
543 @Override
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700544 public void cancelLongPress() {
545 super.cancelLongPress();
546
547 // Cancel long press for all children
548 final int count = getChildCount();
549 for (int i = 0; i < count; i++) {
550 final View child = getChildAt(i);
551 child.cancelLongPress();
552 }
553 }
554
Michael Jurkadee05892010-07-27 10:01:56 -0700555 public void setOnInterceptTouchListener(View.OnTouchListener listener) {
556 mInterceptTouchListener = listener;
557 }
558
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800559 int getCountX() {
Adam Cohend22015c2010-07-26 22:02:18 -0700560 return mCountX;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800561 }
562
563 int getCountY() {
Adam Cohend22015c2010-07-26 22:02:18 -0700564 return mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800565 }
566
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800567 public void setIsHotseat(boolean isHotseat) {
568 mIsHotseat = isHotseat;
569 }
570
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800571 public boolean addViewToCellLayout(View child, int index, int childId, LayoutParams params,
Andrew Flynn850d2e72012-04-26 16:51:20 -0700572 boolean markCells) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700573 final LayoutParams lp = params;
574
Andrew Flynnde38e422012-05-08 11:22:15 -0700575 // Hotseat icons - remove text
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800576 if (child instanceof BubbleTextView) {
577 BubbleTextView bubbleChild = (BubbleTextView) child;
578
Andrew Flynnde38e422012-05-08 11:22:15 -0700579 Resources res = getResources();
580 if (mIsHotseat) {
581 bubbleChild.setTextColor(res.getColor(android.R.color.transparent));
582 } else {
583 bubbleChild.setTextColor(res.getColor(R.color.workspace_icon_text_color));
Andrew Flynn0dca1ec2012-02-29 13:33:22 -0800584 }
585 }
586
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587 // Generate an id for each view, this assumes we have at most 256x256 cells
588 // per workspace screen
Adam Cohend22015c2010-07-26 22:02:18 -0700589 if (lp.cellX >= 0 && lp.cellX <= mCountX - 1 && lp.cellY >= 0 && lp.cellY <= mCountY - 1) {
Winson Chungaafa03c2010-06-11 17:34:16 -0700590 // If the horizontal or vertical span is set to -1, it is taken to
591 // mean that it spans the extent of the CellLayout
Adam Cohend22015c2010-07-26 22:02:18 -0700592 if (lp.cellHSpan < 0) lp.cellHSpan = mCountX;
593 if (lp.cellVSpan < 0) lp.cellVSpan = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800594
Winson Chungaafa03c2010-06-11 17:34:16 -0700595 child.setId(childId);
596
Michael Jurkaa52570f2012-03-20 03:18:20 -0700597 mShortcutsAndWidgets.addView(child, index, lp);
Michael Jurkadee05892010-07-27 10:01:56 -0700598
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700599 if (markCells) markCellsAsOccupiedForView(child);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700600
Winson Chungaafa03c2010-06-11 17:34:16 -0700601 return true;
602 }
603 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800604 }
Michael Jurka3e7c7632010-10-02 16:01:03 -0700605
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800606 @Override
Michael Jurka0280c3b2010-09-17 15:00:07 -0700607 public void removeAllViews() {
608 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700609 mShortcutsAndWidgets.removeAllViews();
Michael Jurka0280c3b2010-09-17 15:00:07 -0700610 }
611
612 @Override
613 public void removeAllViewsInLayout() {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700614 if (mShortcutsAndWidgets.getChildCount() > 0) {
Michael Jurka7cfc2822011-08-02 20:19:24 -0700615 clearOccupiedCells();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700616 mShortcutsAndWidgets.removeAllViewsInLayout();
Michael Jurka7cfc2822011-08-02 20:19:24 -0700617 }
Michael Jurka0280c3b2010-09-17 15:00:07 -0700618 }
619
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700620 public void removeViewWithoutMarkingCells(View view) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700621 mShortcutsAndWidgets.removeView(view);
Michael Jurkaf3ca3ab2010-10-20 17:08:24 -0700622 }
623
Michael Jurka0280c3b2010-09-17 15:00:07 -0700624 @Override
625 public void removeView(View view) {
626 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700627 mShortcutsAndWidgets.removeView(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700628 }
629
630 @Override
631 public void removeViewAt(int index) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700632 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(index));
633 mShortcutsAndWidgets.removeViewAt(index);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700634 }
635
636 @Override
637 public void removeViewInLayout(View view) {
638 markCellsAsUnoccupiedForView(view);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700639 mShortcutsAndWidgets.removeViewInLayout(view);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700640 }
641
642 @Override
643 public void removeViews(int start, int count) {
644 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700645 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700646 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700647 mShortcutsAndWidgets.removeViews(start, count);
Michael Jurka0280c3b2010-09-17 15:00:07 -0700648 }
649
650 @Override
651 public void removeViewsInLayout(int start, int count) {
652 for (int i = start; i < start + count; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700653 markCellsAsUnoccupiedForView(mShortcutsAndWidgets.getChildAt(i));
Michael Jurka0280c3b2010-09-17 15:00:07 -0700654 }
Michael Jurkaa52570f2012-03-20 03:18:20 -0700655 mShortcutsAndWidgets.removeViewsInLayout(start, count);
Michael Jurkaabded662011-03-04 12:06:57 -0800656 }
657
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800658 @Override
659 protected void onAttachedToWindow() {
660 super.onAttachedToWindow();
661 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
662 }
663
Michael Jurkaaf442092010-06-10 17:01:57 -0700664 public void setTagToCellInfoForPoint(int touchX, int touchY) {
665 final CellInfo cellInfo = mCellInfo;
Winson Chungeecf02d2012-03-02 17:14:58 -0800666 Rect frame = mRect;
Michael Jurka8b805b12012-04-18 14:23:14 -0700667 final int x = touchX + getScrollX();
668 final int y = touchY + getScrollY();
Michael Jurkaa52570f2012-03-20 03:18:20 -0700669 final int count = mShortcutsAndWidgets.getChildCount();
Michael Jurkaaf442092010-06-10 17:01:57 -0700670
671 boolean found = false;
672 for (int i = count - 1; i >= 0; i--) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700673 final View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohend4844c32011-02-18 19:25:06 -0800674 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurkaaf442092010-06-10 17:01:57 -0700675
Adam Cohen1b607ed2011-03-03 17:26:50 -0800676 if ((child.getVisibility() == VISIBLE || child.getAnimation() != null) &&
677 lp.isLockedToGrid) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700678 child.getHitRect(frame);
Winson Chung0be025d2011-05-23 17:45:09 -0700679
Winson Chungeecf02d2012-03-02 17:14:58 -0800680 float scale = child.getScaleX();
681 frame = new Rect(child.getLeft(), child.getTop(), child.getRight(),
682 child.getBottom());
Winson Chung0be025d2011-05-23 17:45:09 -0700683 // The child hit rect is relative to the CellLayoutChildren parent, so we need to
684 // offset that by this CellLayout's padding to test an (x,y) point that is relative
685 // to this view.
Michael Jurka8b805b12012-04-18 14:23:14 -0700686 frame.offset(getPaddingLeft(), getPaddingTop());
Winson Chungeecf02d2012-03-02 17:14:58 -0800687 frame.inset((int) (frame.width() * (1f - scale) / 2),
688 (int) (frame.height() * (1f - scale) / 2));
Winson Chung0be025d2011-05-23 17:45:09 -0700689
Michael Jurkaaf442092010-06-10 17:01:57 -0700690 if (frame.contains(x, y)) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700691 cellInfo.cell = child;
692 cellInfo.cellX = lp.cellX;
693 cellInfo.cellY = lp.cellY;
694 cellInfo.spanX = lp.cellHSpan;
695 cellInfo.spanY = lp.cellVSpan;
Michael Jurkaaf442092010-06-10 17:01:57 -0700696 found = true;
Michael Jurkaaf442092010-06-10 17:01:57 -0700697 break;
698 }
699 }
700 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700701
Michael Jurkad771c962011-08-09 15:00:48 -0700702 mLastDownOnOccupiedCell = found;
703
Michael Jurkaaf442092010-06-10 17:01:57 -0700704 if (!found) {
Winson Chung0be025d2011-05-23 17:45:09 -0700705 final int cellXY[] = mTmpXY;
Michael Jurkaaf442092010-06-10 17:01:57 -0700706 pointToCellExact(x, y, cellXY);
707
Michael Jurkaaf442092010-06-10 17:01:57 -0700708 cellInfo.cell = null;
709 cellInfo.cellX = cellXY[0];
710 cellInfo.cellY = cellXY[1];
711 cellInfo.spanX = 1;
712 cellInfo.spanY = 1;
Michael Jurkaaf442092010-06-10 17:01:57 -0700713 }
714 setTag(cellInfo);
715 }
716
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800717 @Override
718 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohenc1997fd2011-08-15 18:26:39 -0700719 // First we clear the tag to ensure that on every touch down we start with a fresh slate,
720 // even in the case where we return early. Not clearing here was causing bugs whereby on
721 // long-press we'd end up picking up an item from a previous drag operation.
722 final int action = ev.getAction();
723
724 if (action == MotionEvent.ACTION_DOWN) {
725 clearTagCellInfo();
726 }
727
Michael Jurkadee05892010-07-27 10:01:56 -0700728 if (mInterceptTouchListener != null && mInterceptTouchListener.onTouch(this, ev)) {
729 return true;
730 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800731
732 if (action == MotionEvent.ACTION_DOWN) {
Michael Jurkaaf442092010-06-10 17:01:57 -0700733 setTagToCellInfoForPoint((int) ev.getX(), (int) ev.getY());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800734 }
Winson Chungeecf02d2012-03-02 17:14:58 -0800735
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800736 return false;
737 }
738
Adam Cohenc1997fd2011-08-15 18:26:39 -0700739 private void clearTagCellInfo() {
740 final CellInfo cellInfo = mCellInfo;
741 cellInfo.cell = null;
742 cellInfo.cellX = -1;
743 cellInfo.cellY = -1;
744 cellInfo.spanX = 0;
745 cellInfo.spanY = 0;
746 setTag(cellInfo);
747 }
748
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749 public CellInfo getTag() {
Michael Jurka0280c3b2010-09-17 15:00:07 -0700750 return (CellInfo) super.getTag();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800751 }
752
Patrick Dubroy6569f2c2010-07-12 14:25:18 -0700753 /**
Winson Chungaafa03c2010-06-11 17:34:16 -0700754 * Given a point, return the cell that strictly encloses that point
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800755 * @param x X coordinate of the point
756 * @param y Y coordinate of the point
757 * @param result Array of 2 ints to hold the x and y coordinate of the cell
758 */
759 void pointToCellExact(int x, int y, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700760 final int hStartPadding = getPaddingLeft();
761 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800762
763 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
764 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
765
Adam Cohend22015c2010-07-26 22:02:18 -0700766 final int xAxis = mCountX;
767 final int yAxis = mCountY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800768
769 if (result[0] < 0) result[0] = 0;
770 if (result[0] >= xAxis) result[0] = xAxis - 1;
771 if (result[1] < 0) result[1] = 0;
772 if (result[1] >= yAxis) result[1] = yAxis - 1;
773 }
Winson Chungaafa03c2010-06-11 17:34:16 -0700774
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800775 /**
776 * Given a point, return the cell that most closely encloses that point
777 * @param x X coordinate of the point
778 * @param y Y coordinate of the point
779 * @param result Array of 2 ints to hold the x and y coordinate of the cell
780 */
781 void pointToCellRounded(int x, int y, int[] result) {
782 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
783 }
784
785 /**
786 * Given a cell coordinate, return the point that represents the upper left corner of that cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700787 *
788 * @param cellX X coordinate of the cell
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800789 * @param cellY Y coordinate of the cell
Winson Chungaafa03c2010-06-11 17:34:16 -0700790 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800791 * @param result Array of 2 ints to hold the x and y coordinate of the point
792 */
793 void cellToPoint(int cellX, int cellY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700794 final int hStartPadding = getPaddingLeft();
795 final int vStartPadding = getPaddingTop();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800796
797 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
798 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
799 }
800
Adam Cohene3e27a82011-04-15 12:07:39 -0700801 /**
Adam Cohen482ed822012-03-02 14:15:13 -0800802 * Given a cell coordinate, return the point that represents the center of the cell
Adam Cohene3e27a82011-04-15 12:07:39 -0700803 *
804 * @param cellX X coordinate of the cell
805 * @param cellY Y coordinate of the cell
806 *
807 * @param result Array of 2 ints to hold the x and y coordinate of the point
808 */
809 void cellToCenterPoint(int cellX, int cellY, int[] result) {
Adam Cohen47a876d2012-03-19 13:21:41 -0700810 regionToCenterPoint(cellX, cellY, 1, 1, result);
811 }
812
813 /**
814 * Given a cell coordinate and span return the point that represents the center of the regio
815 *
816 * @param cellX X coordinate of the cell
817 * @param cellY Y coordinate of the cell
818 *
819 * @param result Array of 2 ints to hold the x and y coordinate of the point
820 */
821 void regionToCenterPoint(int cellX, int cellY, int spanX, int spanY, int[] result) {
Winson Chung4b825dcd2011-06-19 12:41:22 -0700822 final int hStartPadding = getPaddingLeft();
823 final int vStartPadding = getPaddingTop();
Adam Cohen47a876d2012-03-19 13:21:41 -0700824 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap) +
825 (spanX * mCellWidth + (spanX - 1) * mWidthGap) / 2;
826 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap) +
827 (spanY * mCellHeight + (spanY - 1) * mHeightGap) / 2;
Adam Cohene3e27a82011-04-15 12:07:39 -0700828 }
829
Adam Cohen19f37922012-03-21 11:59:11 -0700830 /**
831 * Given a cell coordinate and span fills out a corresponding pixel rect
832 *
833 * @param cellX X coordinate of the cell
834 * @param cellY Y coordinate of the cell
835 * @param result Rect in which to write the result
836 */
837 void regionToRect(int cellX, int cellY, int spanX, int spanY, Rect result) {
838 final int hStartPadding = getPaddingLeft();
839 final int vStartPadding = getPaddingTop();
840 final int left = hStartPadding + cellX * (mCellWidth + mWidthGap);
841 final int top = vStartPadding + cellY * (mCellHeight + mHeightGap);
842 result.set(left, top, left + (spanX * mCellWidth + (spanX - 1) * mWidthGap),
843 top + (spanY * mCellHeight + (spanY - 1) * mHeightGap));
844 }
845
Adam Cohen482ed822012-03-02 14:15:13 -0800846 public float getDistanceFromCell(float x, float y, int[] cell) {
847 cellToCenterPoint(cell[0], cell[1], mTmpPoint);
848 float distance = (float) Math.sqrt( Math.pow(x - mTmpPoint[0], 2) +
849 Math.pow(y - mTmpPoint[1], 2));
850 return distance;
851 }
852
Romain Guy84f296c2009-11-04 15:00:44 -0800853 int getCellWidth() {
854 return mCellWidth;
855 }
856
857 int getCellHeight() {
858 return mCellHeight;
859 }
860
Adam Cohend4844c32011-02-18 19:25:06 -0800861 int getWidthGap() {
862 return mWidthGap;
863 }
864
865 int getHeightGap() {
866 return mHeightGap;
867 }
868
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700869 Rect getContentRect(Rect r) {
870 if (r == null) {
871 r = new Rect();
872 }
873 int left = getPaddingLeft();
874 int top = getPaddingTop();
Michael Jurka8b805b12012-04-18 14:23:14 -0700875 int right = left + getWidth() - getPaddingLeft() - getPaddingRight();
876 int bottom = top + getHeight() - getPaddingTop() - getPaddingBottom();
Adam Cohen7f4eabe2011-04-21 16:19:16 -0700877 r.set(left, top, right, bottom);
878 return r;
879 }
880
Adam Cohena897f392012-04-27 18:12:05 -0700881 static void getMetrics(Rect metrics, Resources res, int measureWidth, int measureHeight,
882 int countX, int countY, int orientation) {
883 int numWidthGaps = countX - 1;
884 int numHeightGaps = countY - 1;
Adam Cohenf4bd5792012-04-27 11:35:29 -0700885
886 int widthGap;
887 int heightGap;
888 int cellWidth;
889 int cellHeight;
890 int paddingLeft;
891 int paddingRight;
892 int paddingTop;
893 int paddingBottom;
894
Adam Cohena897f392012-04-27 18:12:05 -0700895 int maxGap = res.getDimensionPixelSize(R.dimen.workspace_max_gap);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700896 if (orientation == LANDSCAPE) {
897 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_land);
898 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_land);
899 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_land);
900 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_land);
901 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_land);
902 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_land);
903 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_land);
904 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_land);
905 } else {
906 // PORTRAIT
907 cellWidth = res.getDimensionPixelSize(R.dimen.workspace_cell_width_port);
908 cellHeight = res.getDimensionPixelSize(R.dimen.workspace_cell_height_port);
909 widthGap = res.getDimensionPixelSize(R.dimen.workspace_width_gap_port);
910 heightGap = res.getDimensionPixelSize(R.dimen.workspace_height_gap_port);
911 paddingLeft = res.getDimensionPixelSize(R.dimen.cell_layout_left_padding_port);
912 paddingRight = res.getDimensionPixelSize(R.dimen.cell_layout_right_padding_port);
913 paddingTop = res.getDimensionPixelSize(R.dimen.cell_layout_top_padding_port);
914 paddingBottom = res.getDimensionPixelSize(R.dimen.cell_layout_bottom_padding_port);
915 }
916
917 if (widthGap < 0 || heightGap < 0) {
918 int hSpace = measureWidth - paddingLeft - paddingRight;
919 int vSpace = measureHeight - paddingTop - paddingBottom;
Adam Cohena897f392012-04-27 18:12:05 -0700920 int hFreeSpace = hSpace - (countX * cellWidth);
921 int vFreeSpace = vSpace - (countY * cellHeight);
922 widthGap = Math.min(maxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
923 heightGap = Math.min(maxGap, numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Adam Cohenf4bd5792012-04-27 11:35:29 -0700924 }
925 metrics.set(cellWidth, cellHeight, widthGap, heightGap);
926 }
927
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800928 @Override
929 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800930 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700931 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
932
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800933 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
934 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungaafa03c2010-06-11 17:34:16 -0700935
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800936 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
937 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
938 }
939
Adam Cohend22015c2010-07-26 22:02:18 -0700940 int numWidthGaps = mCountX - 1;
941 int numHeightGaps = mCountY - 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800942
Adam Cohen234c4cd2011-07-17 21:03:04 -0700943 if (mOriginalWidthGap < 0 || mOriginalHeightGap < 0) {
Michael Jurkadd13e3d2012-05-01 12:38:17 -0700944 int hSpace = widthSpecSize - getPaddingLeft() - getPaddingRight();
945 int vSpace = heightSpecSize - getPaddingTop() - getPaddingBottom();
Adam Cohenf4bd5792012-04-27 11:35:29 -0700946 int hFreeSpace = hSpace - (mCountX * mCellWidth);
947 int vFreeSpace = vSpace - (mCountY * mCellHeight);
Winson Chung4b825dcd2011-06-19 12:41:22 -0700948 mWidthGap = Math.min(mMaxGap, numWidthGaps > 0 ? (hFreeSpace / numWidthGaps) : 0);
949 mHeightGap = Math.min(mMaxGap,numHeightGaps > 0 ? (vFreeSpace / numHeightGaps) : 0);
Michael Jurkaa52570f2012-03-20 03:18:20 -0700950 mShortcutsAndWidgets.setCellDimensions(mCellWidth, mCellHeight, mWidthGap, mHeightGap);
Adam Cohen234c4cd2011-07-17 21:03:04 -0700951 } else {
952 mWidthGap = mOriginalWidthGap;
953 mHeightGap = mOriginalHeightGap;
Winson Chungece7f5b2010-10-22 14:54:12 -0700954 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700955
Michael Jurka8c920dd2011-01-20 14:16:56 -0800956 // Initial values correspond to widthSpecMode == MeasureSpec.EXACTLY
957 int newWidth = widthSpecSize;
958 int newHeight = heightSpecSize;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700959 if (widthSpecMode == MeasureSpec.AT_MOST) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700960 newWidth = getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700961 ((mCountX - 1) * mWidthGap);
Michael Jurka8b805b12012-04-18 14:23:14 -0700962 newHeight = getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Winson Chungece7f5b2010-10-22 14:54:12 -0700963 ((mCountY - 1) * mHeightGap);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700964 setMeasuredDimension(newWidth, newHeight);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700965 }
Michael Jurka8c920dd2011-01-20 14:16:56 -0800966
967 int count = getChildCount();
968 for (int i = 0; i < count; i++) {
969 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -0700970 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(newWidth - getPaddingLeft() -
971 getPaddingRight(), MeasureSpec.EXACTLY);
972 int childheightMeasureSpec = MeasureSpec.makeMeasureSpec(newHeight - getPaddingTop() -
973 getPaddingBottom(), MeasureSpec.EXACTLY);
Michael Jurka8c920dd2011-01-20 14:16:56 -0800974 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
975 }
976 setMeasuredDimension(newWidth, newHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800977 }
978
979 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700980 protected void onLayout(boolean changed, int l, int t, int r, int b) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800981 int count = getChildCount();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800982 for (int i = 0; i < count; i++) {
Michael Jurka8c920dd2011-01-20 14:16:56 -0800983 View child = getChildAt(i);
Michael Jurka8b805b12012-04-18 14:23:14 -0700984 child.layout(getPaddingLeft(), getPaddingTop(),
985 r - l - getPaddingRight(), b - t - getPaddingBottom());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800986 }
987 }
988
989 @Override
Michael Jurkadee05892010-07-27 10:01:56 -0700990 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
991 super.onSizeChanged(w, h, oldw, oldh);
Michael Jurka18014792010-10-14 09:01:34 -0700992 mBackgroundRect.set(0, 0, w, h);
Adam Cohenb5ba0972011-09-07 18:02:31 -0700993 mForegroundRect.set(mForegroundPadding, mForegroundPadding,
994 w - 2 * mForegroundPadding, h - 2 * mForegroundPadding);
Michael Jurkadee05892010-07-27 10:01:56 -0700995 }
996
997 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800998 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -0700999 mShortcutsAndWidgets.setChildrenDrawingCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001000 }
1001
1002 @Override
1003 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001004 mShortcutsAndWidgets.setChildrenDrawnWithCacheEnabled(enabled);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001005 }
1006
Michael Jurka5f1c5092010-09-03 14:15:02 -07001007 public float getBackgroundAlpha() {
1008 return mBackgroundAlpha;
Michael Jurkadee05892010-07-27 10:01:56 -07001009 }
1010
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001011 public void setBackgroundAlphaMultiplier(float multiplier) {
Michael Jurkaa3d30ad2012-05-08 13:43:43 -07001012 if (mBackgroundAlphaMultiplier != multiplier) {
1013 mBackgroundAlphaMultiplier = multiplier;
1014 invalidate();
1015 }
Adam Cohen1b0aaac2010-10-28 11:11:18 -07001016 }
1017
Adam Cohenddb82192010-11-10 16:32:54 -08001018 public float getBackgroundAlphaMultiplier() {
1019 return mBackgroundAlphaMultiplier;
1020 }
1021
Michael Jurka5f1c5092010-09-03 14:15:02 -07001022 public void setBackgroundAlpha(float alpha) {
Michael Jurkaafaa0502011-12-13 18:22:50 -08001023 if (mBackgroundAlpha != alpha) {
1024 mBackgroundAlpha = alpha;
1025 invalidate();
1026 }
Michael Jurkadee05892010-07-27 10:01:56 -07001027 }
1028
Michael Jurkaa52570f2012-03-20 03:18:20 -07001029 public void setShortcutAndWidgetAlpha(float alpha) {
Michael Jurka0142d492010-08-25 17:46:15 -07001030 final int childCount = getChildCount();
1031 for (int i = 0; i < childCount; i++) {
Michael Jurkadee05892010-07-27 10:01:56 -07001032 getChildAt(i).setAlpha(alpha);
1033 }
1034 }
1035
Michael Jurkaa52570f2012-03-20 03:18:20 -07001036 public ShortcutAndWidgetContainer getShortcutsAndWidgets() {
1037 if (getChildCount() > 0) {
1038 return (ShortcutAndWidgetContainer) getChildAt(0);
1039 }
1040 return null;
1041 }
1042
Patrick Dubroy440c3602010-07-13 17:50:32 -07001043 public View getChildAt(int x, int y) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001044 return mShortcutsAndWidgets.getChildAt(x, y);
Patrick Dubroy440c3602010-07-13 17:50:32 -07001045 }
1046
Adam Cohen76fc0852011-06-17 13:26:23 -07001047 public boolean animateChildToPosition(final View child, int cellX, int cellY, int duration,
Adam Cohen482ed822012-03-02 14:15:13 -08001048 int delay, boolean permanent, boolean adjustOccupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001049 ShortcutAndWidgetContainer clc = getShortcutsAndWidgets();
Adam Cohen482ed822012-03-02 14:15:13 -08001050 boolean[][] occupied = mOccupied;
1051 if (!permanent) {
1052 occupied = mTmpOccupied;
1053 }
1054
Adam Cohen19f37922012-03-21 11:59:11 -07001055 if (clc.indexOfChild(child) != -1) {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001056 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
1057 final ItemInfo info = (ItemInfo) child.getTag();
1058
1059 // We cancel any existing animations
1060 if (mReorderAnimators.containsKey(lp)) {
1061 mReorderAnimators.get(lp).cancel();
1062 mReorderAnimators.remove(lp);
1063 }
1064
Adam Cohen482ed822012-03-02 14:15:13 -08001065 final int oldX = lp.x;
1066 final int oldY = lp.y;
1067 if (adjustOccupied) {
1068 occupied[lp.cellX][lp.cellY] = false;
1069 occupied[cellX][cellY] = true;
1070 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001071 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001072 if (permanent) {
1073 lp.cellX = info.cellX = cellX;
1074 lp.cellY = info.cellY = cellY;
1075 } else {
1076 lp.tmpCellX = cellX;
1077 lp.tmpCellY = cellY;
1078 }
Adam Cohenbfbfd262011-06-13 16:55:12 -07001079 clc.setupLp(lp);
1080 lp.isLockedToGrid = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001081 final int newX = lp.x;
1082 final int newY = lp.y;
Adam Cohenbfbfd262011-06-13 16:55:12 -07001083
Adam Cohen76fc0852011-06-17 13:26:23 -07001084 lp.x = oldX;
1085 lp.y = oldY;
Adam Cohen76fc0852011-06-17 13:26:23 -07001086
Adam Cohen482ed822012-03-02 14:15:13 -08001087 // Exit early if we're not actually moving the view
1088 if (oldX == newX && oldY == newY) {
1089 lp.isLockedToGrid = true;
1090 return true;
1091 }
1092
Michael Jurka2ecf9952012-06-18 12:52:28 -07001093 ValueAnimator va = LauncherAnimUtils.ofFloat(0f, 1f);
Adam Cohen482ed822012-03-02 14:15:13 -08001094 va.setDuration(duration);
1095 mReorderAnimators.put(lp, va);
1096
1097 va.addUpdateListener(new AnimatorUpdateListener() {
1098 @Override
Adam Cohenbfbfd262011-06-13 16:55:12 -07001099 public void onAnimationUpdate(ValueAnimator animation) {
Adam Cohen482ed822012-03-02 14:15:13 -08001100 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohen19f37922012-03-21 11:59:11 -07001101 lp.x = (int) ((1 - r) * oldX + r * newX);
1102 lp.y = (int) ((1 - r) * oldY + r * newY);
Adam Cohen6b8a02d2012-03-22 15:13:40 -07001103 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001104 }
1105 });
Adam Cohen482ed822012-03-02 14:15:13 -08001106 va.addListener(new AnimatorListenerAdapter() {
Adam Cohenbfbfd262011-06-13 16:55:12 -07001107 boolean cancelled = false;
1108 public void onAnimationEnd(Animator animation) {
1109 // If the animation was cancelled, it means that another animation
1110 // has interrupted this one, and we don't want to lock the item into
1111 // place just yet.
1112 if (!cancelled) {
1113 lp.isLockedToGrid = true;
Adam Cohen482ed822012-03-02 14:15:13 -08001114 child.requestLayout();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001115 }
1116 if (mReorderAnimators.containsKey(lp)) {
1117 mReorderAnimators.remove(lp);
1118 }
1119 }
1120 public void onAnimationCancel(Animator animation) {
1121 cancelled = true;
1122 }
1123 });
Adam Cohen482ed822012-03-02 14:15:13 -08001124 va.setStartDelay(delay);
1125 va.start();
Adam Cohenbfbfd262011-06-13 16:55:12 -07001126 return true;
1127 }
1128 return false;
1129 }
1130
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001131 /**
1132 * Estimate where the top left cell of the dragged item will land if it is dropped.
1133 *
1134 * @param originX The X value of the top left corner of the item
1135 * @param originY The Y value of the top left corner of the item
1136 * @param spanX The number of horizontal cells that the item spans
1137 * @param spanY The number of vertical cells that the item spans
1138 * @param result The estimated drop cell X and Y.
1139 */
1140 void estimateDropCell(int originX, int originY, int spanX, int spanY, int[] result) {
Adam Cohend22015c2010-07-26 22:02:18 -07001141 final int countX = mCountX;
1142 final int countY = mCountY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001143
Michael Jurkaa63c4522010-08-19 13:52:27 -07001144 // pointToCellRounded takes the top left of a cell but will pad that with
1145 // cellWidth/2 and cellHeight/2 when finding the matching cell
1146 pointToCellRounded(originX, originY, result);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001147
1148 // If the item isn't fully on this screen, snap to the edges
1149 int rightOverhang = result[0] + spanX - countX;
1150 if (rightOverhang > 0) {
1151 result[0] -= rightOverhang; // Snap to right
1152 }
1153 result[0] = Math.max(0, result[0]); // Snap to left
1154 int bottomOverhang = result[1] + spanY - countY;
1155 if (bottomOverhang > 0) {
1156 result[1] -= bottomOverhang; // Snap to bottom
1157 }
1158 result[1] = Math.max(0, result[1]); // Snap to top
1159 }
1160
Adam Cohen482ed822012-03-02 14:15:13 -08001161 void visualizeDropLocation(View v, Bitmap dragOutline, int originX, int originY, int cellX,
1162 int cellY, int spanX, int spanY, boolean resize, Point dragOffset, Rect dragRegion) {
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001163 final int oldDragCellX = mDragCell[0];
1164 final int oldDragCellY = mDragCell[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001165
Winson Chungb8c69f32011-10-19 21:36:08 -07001166 if (v != null && dragOffset == null) {
Winson Chunga9abd0e2010-10-27 17:18:37 -07001167 mDragCenter.set(originX + (v.getWidth() / 2), originY + (v.getHeight() / 2));
1168 } else {
1169 mDragCenter.set(originX, originY);
1170 }
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001171
Adam Cohen2801caf2011-05-13 20:57:39 -07001172 if (dragOutline == null && v == null) {
Adam Cohen2801caf2011-05-13 20:57:39 -07001173 return;
1174 }
1175
Adam Cohen482ed822012-03-02 14:15:13 -08001176 if (cellX != oldDragCellX || cellY != oldDragCellY) {
1177 mDragCell[0] = cellX;
1178 mDragCell[1] = cellY;
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001179 // Find the top left corner of the rect the object will occupy
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001180 final int[] topLeft = mTmpPoint;
Adam Cohen482ed822012-03-02 14:15:13 -08001181 cellToPoint(cellX, cellY, topLeft);
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001182
Joe Onorato4be866d2010-10-10 11:26:02 -07001183 int left = topLeft[0];
1184 int top = topLeft[1];
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001185
Winson Chungb8c69f32011-10-19 21:36:08 -07001186 if (v != null && dragOffset == null) {
Adam Cohen99e8b402011-03-25 19:23:43 -07001187 // When drawing the drag outline, it did not account for margin offsets
1188 // added by the view's parent.
1189 MarginLayoutParams lp = (MarginLayoutParams) v.getLayoutParams();
1190 left += lp.leftMargin;
1191 top += lp.topMargin;
Winson Chung150fbab2010-09-29 17:14:26 -07001192
Adam Cohen99e8b402011-03-25 19:23:43 -07001193 // Offsets due to the size difference between the View and the dragOutline.
1194 // There is a size difference to account for the outer blur, which may lie
1195 // outside the bounds of the view.
Winson Chunga9abd0e2010-10-27 17:18:37 -07001196 top += (v.getHeight() - dragOutline.getHeight()) / 2;
Adam Cohenae915ce2011-08-25 13:47:22 -07001197 // We center about the x axis
1198 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1199 - dragOutline.getWidth()) / 2;
Adam Cohen66396872011-04-15 17:50:36 -07001200 } else {
Winson Chungb8c69f32011-10-19 21:36:08 -07001201 if (dragOffset != null && dragRegion != null) {
1202 // Center the drag region *horizontally* in the cell and apply a drag
1203 // outline offset
1204 left += dragOffset.x + ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1205 - dragRegion.width()) / 2;
1206 top += dragOffset.y;
1207 } else {
1208 // Center the drag outline in the cell
1209 left += ((mCellWidth * spanX) + ((spanX - 1) * mWidthGap)
1210 - dragOutline.getWidth()) / 2;
1211 top += ((mCellHeight * spanY) + ((spanY - 1) * mHeightGap)
1212 - dragOutline.getHeight()) / 2;
1213 }
Winson Chunga9abd0e2010-10-27 17:18:37 -07001214 }
Joe Onorato4be866d2010-10-10 11:26:02 -07001215 final int oldIndex = mDragOutlineCurrent;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001216 mDragOutlineAnims[oldIndex].animateOut();
1217 mDragOutlineCurrent = (oldIndex + 1) % mDragOutlines.length;
Adam Cohend41fbf52012-02-16 23:53:59 -08001218 Rect r = mDragOutlines[mDragOutlineCurrent];
1219 r.set(left, top, left + dragOutline.getWidth(), top + dragOutline.getHeight());
1220 if (resize) {
Adam Cohen482ed822012-03-02 14:15:13 -08001221 cellToRect(cellX, cellY, spanX, spanY, r);
Adam Cohend41fbf52012-02-16 23:53:59 -08001222 }
Winson Chung150fbab2010-09-29 17:14:26 -07001223
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07001224 mDragOutlineAnims[mDragOutlineCurrent].setTag(dragOutline);
1225 mDragOutlineAnims[mDragOutlineCurrent].animateIn();
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07001226 }
1227 }
1228
Adam Cohene0310962011-04-18 16:15:31 -07001229 public void clearDragOutlines() {
1230 final int oldIndex = mDragOutlineCurrent;
1231 mDragOutlineAnims[oldIndex].animateOut();
Adam Cohend41fbf52012-02-16 23:53:59 -08001232 mDragCell[0] = mDragCell[1] = -1;
Adam Cohene0310962011-04-18 16:15:31 -07001233 }
1234
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001235 /**
Jeff Sharkey70864282009-04-07 21:08:40 -07001236 * Find a vacant area that will fit the given bounds nearest the requested
1237 * cell location. Uses Euclidean distance to score multiple vacant areas.
Winson Chungaafa03c2010-06-11 17:34:16 -07001238 *
Romain Guy51afc022009-05-04 18:03:43 -07001239 * @param pixelX The X location at which you want to search for a vacant area.
1240 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -07001241 * @param spanX Horizontal span of the object.
1242 * @param spanY Vertical span of the object.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001243 * @param result Array in which to place the result, or null (in which case a new array will
1244 * be allocated)
Jeff Sharkey70864282009-04-07 21:08:40 -07001245 * @return The X, Y cell of a vacant area that can contain this object,
1246 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001247 */
Adam Cohend41fbf52012-02-16 23:53:59 -08001248 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
1249 int[] result) {
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001250 return findNearestVacantArea(pixelX, pixelY, spanX, spanY, null, result);
Michael Jurka6a1435d2010-09-27 17:35:12 -07001251 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001252
Michael Jurka6a1435d2010-09-27 17:35:12 -07001253 /**
1254 * Find a vacant area that will fit the given bounds nearest the requested
1255 * cell location. Uses Euclidean distance to score multiple vacant areas.
1256 *
1257 * @param pixelX The X location at which you want to search for a vacant area.
1258 * @param pixelY The Y location at which you want to search for a vacant area.
Adam Cohend41fbf52012-02-16 23:53:59 -08001259 * @param minSpanX The minimum horizontal span required
1260 * @param minSpanY The minimum vertical span required
1261 * @param spanX Horizontal span of the object.
1262 * @param spanY Vertical span of the object.
1263 * @param result Array in which to place the result, or null (in which case a new array will
1264 * be allocated)
1265 * @return The X, Y cell of a vacant area that can contain this object,
1266 * nearest the requested location.
1267 */
1268 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1269 int spanY, int[] result, int[] resultSpan) {
1270 return findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null,
1271 result, resultSpan);
1272 }
1273
1274 /**
1275 * Find a vacant area that will fit the given bounds nearest the requested
1276 * cell location. Uses Euclidean distance to score multiple vacant areas.
1277 *
1278 * @param pixelX The X location at which you want to search for a vacant area.
1279 * @param pixelY The Y location at which you want to search for a vacant area.
Michael Jurka6a1435d2010-09-27 17:35:12 -07001280 * @param spanX Horizontal span of the object.
1281 * @param spanY Vertical span of the object.
Adam Cohendf035382011-04-11 17:22:04 -07001282 * @param ignoreOccupied If true, the result can be an occupied cell
1283 * @param result Array in which to place the result, or null (in which case a new array will
1284 * be allocated)
Michael Jurka6a1435d2010-09-27 17:35:12 -07001285 * @return The X, Y cell of a vacant area that can contain this object,
1286 * nearest the requested location.
1287 */
Adam Cohendf035382011-04-11 17:22:04 -07001288 int[] findNearestArea(int pixelX, int pixelY, int spanX, int spanY, View ignoreView,
1289 boolean ignoreOccupied, int[] result) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001290 return findNearestArea(pixelX, pixelY, spanX, spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001291 spanX, spanY, ignoreView, ignoreOccupied, result, null, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08001292 }
1293
1294 private final Stack<Rect> mTempRectStack = new Stack<Rect>();
1295 private void lazyInitTempRectStack() {
1296 if (mTempRectStack.isEmpty()) {
1297 for (int i = 0; i < mCountX * mCountY; i++) {
1298 mTempRectStack.push(new Rect());
1299 }
1300 }
1301 }
Adam Cohen482ed822012-03-02 14:15:13 -08001302
Adam Cohend41fbf52012-02-16 23:53:59 -08001303 private void recycleTempRects(Stack<Rect> used) {
1304 while (!used.isEmpty()) {
1305 mTempRectStack.push(used.pop());
1306 }
1307 }
1308
1309 /**
1310 * Find a vacant area that will fit the given bounds nearest the requested
1311 * cell location. Uses Euclidean distance to score multiple vacant areas.
1312 *
1313 * @param pixelX The X location at which you want to search for a vacant area.
1314 * @param pixelY The Y location at which you want to search for a vacant area.
1315 * @param minSpanX The minimum horizontal span required
1316 * @param minSpanY The minimum vertical span required
1317 * @param spanX Horizontal span of the object.
1318 * @param spanY Vertical span of the object.
1319 * @param ignoreOccupied If true, the result can be an occupied cell
1320 * @param result Array in which to place the result, or null (in which case a new array will
1321 * be allocated)
1322 * @return The X, Y cell of a vacant area that can contain this object,
1323 * nearest the requested location.
1324 */
1325 int[] findNearestArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08001326 View ignoreView, boolean ignoreOccupied, int[] result, int[] resultSpan,
1327 boolean[][] occupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001328 lazyInitTempRectStack();
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001329 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08001330 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001331
Adam Cohene3e27a82011-04-15 12:07:39 -07001332 // For items with a spanX / spanY > 1, the passed in point (pixelX, pixelY) corresponds
1333 // to the center of the item, but we are searching based on the top-left cell, so
1334 // we translate the point over to correspond to the top-left.
1335 pixelX -= (mCellWidth + mWidthGap) * (spanX - 1) / 2f;
1336 pixelY -= (mCellHeight + mHeightGap) * (spanY - 1) / 2f;
1337
Jeff Sharkey70864282009-04-07 21:08:40 -07001338 // Keep track of best-scoring drop area
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001339 final int[] bestXY = result != null ? result : new int[2];
Jeff Sharkey70864282009-04-07 21:08:40 -07001340 double bestDistance = Double.MAX_VALUE;
Adam Cohend41fbf52012-02-16 23:53:59 -08001341 final Rect bestRect = new Rect(-1, -1, -1, -1);
1342 final Stack<Rect> validRegions = new Stack<Rect>();
Winson Chungaafa03c2010-06-11 17:34:16 -07001343
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001344 final int countX = mCountX;
1345 final int countY = mCountY;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07001346
Adam Cohend41fbf52012-02-16 23:53:59 -08001347 if (minSpanX <= 0 || minSpanY <= 0 || spanX <= 0 || spanY <= 0 ||
1348 spanX < minSpanX || spanY < minSpanY) {
1349 return bestXY;
1350 }
1351
1352 for (int y = 0; y < countY - (minSpanY - 1); y++) {
Michael Jurkac28de512010-08-13 11:27:44 -07001353 inner:
Adam Cohend41fbf52012-02-16 23:53:59 -08001354 for (int x = 0; x < countX - (minSpanX - 1); x++) {
1355 int ySize = -1;
1356 int xSize = -1;
Adam Cohendf035382011-04-11 17:22:04 -07001357 if (ignoreOccupied) {
Adam Cohend41fbf52012-02-16 23:53:59 -08001358 // First, let's see if this thing fits anywhere
1359 for (int i = 0; i < minSpanX; i++) {
1360 for (int j = 0; j < minSpanY; j++) {
Adam Cohendf035382011-04-11 17:22:04 -07001361 if (occupied[x + i][y + j]) {
Adam Cohendf035382011-04-11 17:22:04 -07001362 continue inner;
1363 }
Michael Jurkac28de512010-08-13 11:27:44 -07001364 }
1365 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001366 xSize = minSpanX;
1367 ySize = minSpanY;
1368
1369 // We know that the item will fit at _some_ acceptable size, now let's see
1370 // how big we can make it. We'll alternate between incrementing x and y spans
1371 // until we hit a limit.
1372 boolean incX = true;
1373 boolean hitMaxX = xSize >= spanX;
1374 boolean hitMaxY = ySize >= spanY;
1375 while (!(hitMaxX && hitMaxY)) {
1376 if (incX && !hitMaxX) {
1377 for (int j = 0; j < ySize; j++) {
1378 if (x + xSize > countX -1 || occupied[x + xSize][y + j]) {
1379 // We can't move out horizontally
1380 hitMaxX = true;
1381 }
1382 }
1383 if (!hitMaxX) {
1384 xSize++;
1385 }
1386 } else if (!hitMaxY) {
1387 for (int i = 0; i < xSize; i++) {
1388 if (y + ySize > countY - 1 || occupied[x + i][y + ySize]) {
1389 // We can't move out vertically
1390 hitMaxY = true;
1391 }
1392 }
1393 if (!hitMaxY) {
1394 ySize++;
1395 }
1396 }
1397 hitMaxX |= xSize >= spanX;
1398 hitMaxY |= ySize >= spanY;
1399 incX = !incX;
1400 }
1401 incX = true;
1402 hitMaxX = xSize >= spanX;
1403 hitMaxY = ySize >= spanY;
Michael Jurkac28de512010-08-13 11:27:44 -07001404 }
Winson Chung0be025d2011-05-23 17:45:09 -07001405 final int[] cellXY = mTmpXY;
Adam Cohene3e27a82011-04-15 12:07:39 -07001406 cellToCenterPoint(x, y, cellXY);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001407
Adam Cohend41fbf52012-02-16 23:53:59 -08001408 // We verify that the current rect is not a sub-rect of any of our previous
1409 // candidates. In this case, the current rect is disqualified in favour of the
1410 // containing rect.
1411 Rect currentRect = mTempRectStack.pop();
1412 currentRect.set(x, y, x + xSize, y + ySize);
1413 boolean contained = false;
1414 for (Rect r : validRegions) {
1415 if (r.contains(currentRect)) {
1416 contained = true;
1417 break;
1418 }
1419 }
1420 validRegions.push(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001421 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2)
1422 + Math.pow(cellXY[1] - pixelY, 2));
Adam Cohen482ed822012-03-02 14:15:13 -08001423
Adam Cohend41fbf52012-02-16 23:53:59 -08001424 if ((distance <= bestDistance && !contained) ||
1425 currentRect.contains(bestRect)) {
Michael Jurkac28de512010-08-13 11:27:44 -07001426 bestDistance = distance;
1427 bestXY[0] = x;
1428 bestXY[1] = y;
Adam Cohend41fbf52012-02-16 23:53:59 -08001429 if (resultSpan != null) {
1430 resultSpan[0] = xSize;
1431 resultSpan[1] = ySize;
1432 }
1433 bestRect.set(currentRect);
Michael Jurkac28de512010-08-13 11:27:44 -07001434 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001435 }
1436 }
Michael Jurkac6ee42e2010-09-30 12:04:50 -07001437 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08001438 markCellsAsOccupiedForView(ignoreView, occupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001439
Adam Cohenc0dcf592011-06-01 15:30:43 -07001440 // Return -1, -1 if no suitable location found
1441 if (bestDistance == Double.MAX_VALUE) {
1442 bestXY[0] = -1;
1443 bestXY[1] = -1;
Jeff Sharkey70864282009-04-07 21:08:40 -07001444 }
Adam Cohend41fbf52012-02-16 23:53:59 -08001445 recycleTempRects(validRegions);
Adam Cohenc0dcf592011-06-01 15:30:43 -07001446 return bestXY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001447 }
Winson Chungaafa03c2010-06-11 17:34:16 -07001448
Adam Cohen482ed822012-03-02 14:15:13 -08001449 /**
1450 * Find a vacant area that will fit the given bounds nearest the requested
1451 * cell location, and will also weigh in a suggested direction vector of the
1452 * desired location. This method computers distance based on unit grid distances,
1453 * not pixel distances.
1454 *
Adam Cohen47a876d2012-03-19 13:21:41 -07001455 * @param cellX The X cell nearest to which you want to search for a vacant area.
1456 * @param cellY The Y cell nearest which you want to search for a vacant area.
Adam Cohen482ed822012-03-02 14:15:13 -08001457 * @param spanX Horizontal span of the object.
1458 * @param spanY Vertical span of the object.
Adam Cohen47a876d2012-03-19 13:21:41 -07001459 * @param direction The favored direction in which the views should move from x, y
1460 * @param exactDirectionOnly If this parameter is true, then only solutions where the direction
1461 * matches exactly. Otherwise we find the best matching direction.
1462 * @param occoupied The array which represents which cells in the CellLayout are occupied
1463 * @param blockOccupied The array which represents which cells in the specified block (cellX,
1464 * cellY, spanX, spanY) are occupied. This is used when try to move a group of views.
Adam Cohen482ed822012-03-02 14:15:13 -08001465 * @param result Array in which to place the result, or null (in which case a new array will
1466 * be allocated)
1467 * @return The X, Y cell of a vacant area that can contain this object,
1468 * nearest the requested location.
1469 */
1470 private int[] findNearestArea(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen47a876d2012-03-19 13:21:41 -07001471 boolean[][] occupied, boolean blockOccupied[][], int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001472 // Keep track of best-scoring drop area
1473 final int[] bestXY = result != null ? result : new int[2];
1474 float bestDistance = Float.MAX_VALUE;
1475 int bestDirectionScore = Integer.MIN_VALUE;
1476
1477 final int countX = mCountX;
1478 final int countY = mCountY;
1479
1480 for (int y = 0; y < countY - (spanY - 1); y++) {
1481 inner:
1482 for (int x = 0; x < countX - (spanX - 1); x++) {
1483 // First, let's see if this thing fits anywhere
1484 for (int i = 0; i < spanX; i++) {
1485 for (int j = 0; j < spanY; j++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001486 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
Adam Cohen482ed822012-03-02 14:15:13 -08001487 continue inner;
1488 }
1489 }
1490 }
1491
1492 float distance = (float)
1493 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1494 int[] curDirection = mTmpPoint;
Adam Cohen47a876d2012-03-19 13:21:41 -07001495 computeDirectionVector(x - cellX, y - cellY, curDirection);
1496 // The direction score is just the dot product of the two candidate direction
1497 // and that passed in.
Adam Cohen482ed822012-03-02 14:15:13 -08001498 int curDirectionScore = direction[0] * curDirection[0] +
1499 direction[1] * curDirection[1];
Adam Cohen47a876d2012-03-19 13:21:41 -07001500 boolean exactDirectionOnly = false;
1501 boolean directionMatches = direction[0] == curDirection[0] &&
1502 direction[0] == curDirection[0];
1503 if ((directionMatches || !exactDirectionOnly) &&
1504 Float.compare(distance, bestDistance) < 0 || (Float.compare(distance,
Adam Cohen482ed822012-03-02 14:15:13 -08001505 bestDistance) == 0 && curDirectionScore > bestDirectionScore)) {
1506 bestDistance = distance;
1507 bestDirectionScore = curDirectionScore;
1508 bestXY[0] = x;
1509 bestXY[1] = y;
1510 }
1511 }
1512 }
1513
1514 // Return -1, -1 if no suitable location found
1515 if (bestDistance == Float.MAX_VALUE) {
1516 bestXY[0] = -1;
1517 bestXY[1] = -1;
1518 }
1519 return bestXY;
1520 }
1521
Adam Cohen47a876d2012-03-19 13:21:41 -07001522 private int[] findNearestAreaInDirection(int cellX, int cellY, int spanX, int spanY,
1523 int[] direction,boolean[][] occupied,
1524 boolean blockOccupied[][], int[] result) {
1525 // Keep track of best-scoring drop area
1526 final int[] bestXY = result != null ? result : new int[2];
1527 bestXY[0] = -1;
1528 bestXY[1] = -1;
1529 float bestDistance = Float.MAX_VALUE;
1530
1531 // We use this to march in a single direction
Adam Cohen5b53f292012-03-29 14:30:35 -07001532 if ((direction[0] != 0 && direction[1] != 0) ||
1533 (direction[0] == 0 && direction[1] == 0)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001534 return bestXY;
1535 }
1536
1537 // This will only incrememnet one of x or y based on the assertion above
1538 int x = cellX + direction[0];
1539 int y = cellY + direction[1];
1540 while (x >= 0 && x + spanX <= mCountX && y >= 0 && y + spanY <= mCountY) {
1541
1542 boolean fail = false;
1543 for (int i = 0; i < spanX; i++) {
1544 for (int j = 0; j < spanY; j++) {
1545 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1546 fail = true;
1547 }
1548 }
1549 }
1550 if (!fail) {
1551 float distance = (float)
1552 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1553 if (Float.compare(distance, bestDistance) < 0) {
1554 bestDistance = distance;
1555 bestXY[0] = x;
1556 bestXY[1] = y;
1557 }
1558 }
1559 x += direction[0];
1560 y += direction[1];
1561 }
1562 return bestXY;
1563 }
1564
Adam Cohen482ed822012-03-02 14:15:13 -08001565 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001566 int[] direction, ItemConfiguration currentState) {
1567 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001568 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001569 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001570 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1571
Adam Cohen8baab352012-03-20 17:39:21 -07001572 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001573
1574 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001575 c.x = mTempLocation[0];
1576 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001577 success = true;
1578
1579 }
Adam Cohen8baab352012-03-20 17:39:21 -07001580 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001581 return success;
1582 }
1583
Adam Cohen47a876d2012-03-19 13:21:41 -07001584 // This method looks in the specified direction to see if there is an additional view
1585 // immediately adjecent in that direction
1586 private boolean addViewInDirection(ArrayList<View> views, Rect boundingRect, int[] direction,
Adam Cohen19f37922012-03-21 11:59:11 -07001587 boolean[][] occupied, View dragView, ItemConfiguration currentState) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001588 boolean found = false;
1589
Michael Jurkaa52570f2012-03-20 03:18:20 -07001590 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen47a876d2012-03-19 13:21:41 -07001591 Rect r0 = new Rect(boundingRect);
1592 Rect r1 = new Rect();
1593
1594 int deltaX = 0;
1595 int deltaY = 0;
1596 if (direction[1] < 0) {
1597 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom);
1598 deltaY = -1;
1599 } else if (direction[1] > 0) {
1600 r0.set(r0.left, r0.top, r0.right, r0.bottom + 1);
1601 deltaY = 1;
1602 } else if (direction[0] < 0) {
1603 r0.set(r0.left - 1, r0.top, r0.right, r0.bottom);
1604 deltaX = -1;
1605 } else if (direction[0] > 0) {
1606 r0.set(r0.left, r0.top, r0.right + 1, r0.bottom);
1607 deltaX = 1;
1608 }
1609
1610 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001611 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001612 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001613 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001614
Adam Cohen8baab352012-03-20 17:39:21 -07001615 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1616 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001617 if (Rect.intersects(r0, r1)) {
1618 if (!lp.canReorder) {
1619 return false;
1620 }
1621 boolean pushed = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001622 for (int x = c.x; x < c.x + c.spanX; x++) {
1623 for (int y = c.y; y < c.y + c.spanY; y++) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001624 boolean inBounds = x - deltaX >= 0 && x -deltaX < mCountX
1625 && y - deltaY >= 0 && y - deltaY < mCountY;
1626 if (inBounds && occupied[x - deltaX][y - deltaY]) {
1627 pushed = true;
1628 }
1629 }
1630 }
1631 if (pushed) {
1632 views.add(child);
Adam Cohen8baab352012-03-20 17:39:21 -07001633 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001634 found = true;
1635 }
1636 }
1637 }
1638 return found;
1639 }
1640
Adam Cohen482ed822012-03-02 14:15:13 -08001641 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001642 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001643 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001644
Adam Cohen8baab352012-03-20 17:39:21 -07001645 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001646 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001647 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001648 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001649 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001650 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001651 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001652 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001653 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001654 }
1655 }
Adam Cohen8baab352012-03-20 17:39:21 -07001656
1657 @SuppressWarnings("unchecked")
1658 ArrayList<View> dup = (ArrayList<View>) views.clone();
1659 // We try and expand the group of views in the direction vector passed, based on
1660 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001661 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001662 currentState)) {
1663 }
1664
1665 // Mark the occupied state as false for the group of views we want to move.
1666 for (View v: dup) {
1667 CellAndSpan c = currentState.map.get(v);
1668 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1669 }
1670
Adam Cohen47a876d2012-03-19 13:21:41 -07001671 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1672 int top = boundingRect.top;
1673 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001674 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
1675 // for tetris-style interlocking.
1676 for (View v: dup) {
1677 CellAndSpan c = currentState.map.get(v);
1678 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001679 }
1680
Adam Cohen482ed822012-03-02 14:15:13 -08001681 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1682
Adam Cohen8baab352012-03-20 17:39:21 -07001683 if (push) {
1684 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1685 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1686 } else {
1687 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1688 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1689 }
Adam Cohen482ed822012-03-02 14:15:13 -08001690
Adam Cohen8baab352012-03-20 17:39:21 -07001691 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001692 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001693 int deltaX = mTempLocation[0] - boundingRect.left;
1694 int deltaY = mTempLocation[1] - boundingRect.top;
1695 for (View v: dup) {
1696 CellAndSpan c = currentState.map.get(v);
1697 c.x += deltaX;
1698 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001699 }
1700 success = true;
1701 }
Adam Cohen8baab352012-03-20 17:39:21 -07001702
1703 // In either case, we set the occupied array as marked for the location of the views
1704 for (View v: dup) {
1705 CellAndSpan c = currentState.map.get(v);
1706 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001707 }
1708 return success;
1709 }
1710
1711 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1712 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1713 }
1714
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001715 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1716 // to push items in each of the cardinal directions, in an order based on the direction vector
1717 // passed.
1718 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1719 int[] direction, View ignoreView, ItemConfiguration solution) {
1720 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
1721 // If the direction vector has two non-zero components, we try pushing
1722 // separately in each of the components.
1723 int temp = direction[1];
1724 direction[1] = 0;
1725 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1726 ignoreView, solution)) {
1727 return true;
1728 }
1729 direction[1] = temp;
1730 temp = direction[0];
1731 direction[0] = 0;
1732 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1733 ignoreView, solution)) {
1734 return true;
1735 }
1736 // Revert the direction
1737 direction[0] = temp;
1738
1739 // Now we try pushing in each component of the opposite direction
1740 direction[0] *= -1;
1741 direction[1] *= -1;
1742 temp = direction[1];
1743 direction[1] = 0;
1744 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1745 ignoreView, solution)) {
1746 return true;
1747 }
1748
1749 direction[1] = temp;
1750 temp = direction[0];
1751 direction[0] = 0;
1752 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1753 ignoreView, solution)) {
1754 return true;
1755 }
1756 // revert the direction
1757 direction[0] = temp;
1758 direction[0] *= -1;
1759 direction[1] *= -1;
1760
1761 } else {
1762 // If the direction vector has a single non-zero component, we push first in the
1763 // direction of the vector
1764 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1765 ignoreView, solution)) {
1766 return true;
1767 }
1768
1769 // Then we try the opposite direction
1770 direction[0] *= -1;
1771 direction[1] *= -1;
1772 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1773 ignoreView, solution)) {
1774 return true;
1775 }
1776 // Switch the direction back
1777 direction[0] *= -1;
1778 direction[1] *= -1;
1779
1780 // If we have failed to find a push solution with the above, then we try
1781 // to find a solution by pushing along the perpendicular axis.
1782
1783 // Swap the components
1784 int temp = direction[1];
1785 direction[1] = direction[0];
1786 direction[0] = temp;
1787 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1788 ignoreView, solution)) {
1789 return true;
1790 }
1791
1792 // Then we try the opposite direction
1793 direction[0] *= -1;
1794 direction[1] *= -1;
1795 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1796 ignoreView, solution)) {
1797 return true;
1798 }
1799 // Switch the direction back
1800 direction[0] *= -1;
1801 direction[1] *= -1;
1802
1803 // Swap the components back
1804 temp = direction[1];
1805 direction[1] = direction[0];
1806 direction[0] = temp;
1807 }
1808 return false;
1809 }
1810
Adam Cohen482ed822012-03-02 14:15:13 -08001811 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001812 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001813 // Return early if get invalid cell positions
1814 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001815
Adam Cohen8baab352012-03-20 17:39:21 -07001816 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001817 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001818
Adam Cohen8baab352012-03-20 17:39:21 -07001819 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001820 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001821 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001822 if (c != null) {
1823 c.x = cellX;
1824 c.y = cellY;
1825 }
Adam Cohen482ed822012-03-02 14:15:13 -08001826 }
Adam Cohen482ed822012-03-02 14:15:13 -08001827 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1828 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001829 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001830 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001831 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001832 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001833 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001834 if (Rect.intersects(r0, r1)) {
1835 if (!lp.canReorder) {
1836 return false;
1837 }
1838 mIntersectingViews.add(child);
1839 }
1840 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001841
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001842 // First we try to find a solution which respects the push mechanic. That is,
1843 // we try to find a solution such that no displaced item travels through another item
1844 // without also displacing that item.
1845 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001846 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001847 return true;
1848 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001849
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001850 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohen19f37922012-03-21 11:59:11 -07001851 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1852 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001853 return true;
1854 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001855
Adam Cohen482ed822012-03-02 14:15:13 -08001856 // Ok, they couldn't move as a block, let's move them individually
1857 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001858 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001859 return false;
1860 }
1861 }
1862 return true;
1863 }
1864
1865 /*
1866 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1867 * the provided point and the provided cell
1868 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001869 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001870 double angle = Math.atan(((float) deltaY) / deltaX);
1871
1872 result[0] = 0;
1873 result[1] = 0;
1874 if (Math.abs(Math.cos(angle)) > 0.5f) {
1875 result[0] = (int) Math.signum(deltaX);
1876 }
1877 if (Math.abs(Math.sin(angle)) > 0.5f) {
1878 result[1] = (int) Math.signum(deltaY);
1879 }
1880 }
1881
Adam Cohen8baab352012-03-20 17:39:21 -07001882 private void copyOccupiedArray(boolean[][] occupied) {
1883 for (int i = 0; i < mCountX; i++) {
1884 for (int j = 0; j < mCountY; j++) {
1885 occupied[i][j] = mOccupied[i][j];
1886 }
1887 }
1888 }
1889
Adam Cohen482ed822012-03-02 14:15:13 -08001890 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1891 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001892 // Copy the current state into the solution. This solution will be manipulated as necessary.
1893 copyCurrentStateToSolution(solution, false);
1894 // Copy the current occupied array into the temporary occupied array. This array will be
1895 // manipulated as necessary to find a solution.
1896 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001897
1898 // We find the nearest cell into which we would place the dragged item, assuming there's
1899 // nothing in its way.
1900 int result[] = new int[2];
1901 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1902
1903 boolean success = false;
1904 // First we try the exact nearest position of the item being dragged,
1905 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001906 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1907 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001908
1909 if (!success) {
1910 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1911 // x, then 1 in y etc.
1912 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1913 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1914 dragView, false, solution);
1915 } else if (spanY > minSpanY) {
1916 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1917 dragView, true, solution);
1918 }
1919 solution.isSolution = false;
1920 } else {
1921 solution.isSolution = true;
1922 solution.dragViewX = result[0];
1923 solution.dragViewY = result[1];
1924 solution.dragViewSpanX = spanX;
1925 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001926 }
1927 return solution;
1928 }
1929
1930 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001931 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001932 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001933 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001934 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001935 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001936 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001937 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001938 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001939 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001940 }
Adam Cohen8baab352012-03-20 17:39:21 -07001941 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001942 }
1943 }
1944
1945 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1946 for (int i = 0; i < mCountX; i++) {
1947 for (int j = 0; j < mCountY; j++) {
1948 mTmpOccupied[i][j] = false;
1949 }
1950 }
1951
Michael Jurkaa52570f2012-03-20 03:18:20 -07001952 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001953 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001954 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001955 if (child == dragView) continue;
1956 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001957 CellAndSpan c = solution.map.get(child);
1958 if (c != null) {
1959 lp.tmpCellX = c.x;
1960 lp.tmpCellY = c.y;
1961 lp.cellHSpan = c.spanX;
1962 lp.cellVSpan = c.spanY;
1963 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001964 }
1965 }
1966 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1967 solution.dragViewSpanY, mTmpOccupied, true);
1968 }
1969
1970 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1971 commitDragView) {
1972
1973 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1974 for (int i = 0; i < mCountX; i++) {
1975 for (int j = 0; j < mCountY; j++) {
1976 occupied[i][j] = false;
1977 }
1978 }
1979
Michael Jurkaa52570f2012-03-20 03:18:20 -07001980 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001981 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001982 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001983 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001984 CellAndSpan c = solution.map.get(child);
1985 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07001986 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
1987 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07001988 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001989 }
1990 }
1991 if (commitDragView) {
1992 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1993 solution.dragViewSpanY, occupied, true);
1994 }
1995 }
1996
Adam Cohen19f37922012-03-21 11:59:11 -07001997 // This method starts or changes the reorder hint animations
1998 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
1999 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002000 for (int i = 0; i < childCount; i++) {
2001 View child = mShortcutsAndWidgets.getChildAt(i);
2002 if (child == dragView) continue;
2003 CellAndSpan c = solution.map.get(child);
2004 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2005 if (c != null) {
2006 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
2007 c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002008 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002009 }
2010 }
2011 }
2012
2013 // Class which represents the reorder hint animations. These animations show that an item is
2014 // in a temporary state, and hint at where the item will return to.
2015 class ReorderHintAnimation {
2016 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002017 float finalDeltaX;
2018 float finalDeltaY;
2019 float initDeltaX;
2020 float initDeltaY;
2021 float finalScale;
2022 float initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002023 private static final int DURATION = 300;
Adam Cohene7587d22012-05-24 18:50:02 -07002024 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002025
2026 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
2027 int spanX, int spanY) {
2028 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2029 final int x0 = mTmpPoint[0];
2030 final int y0 = mTmpPoint[1];
2031 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2032 final int x1 = mTmpPoint[0];
2033 final int y1 = mTmpPoint[1];
2034 final int dX = x1 - x0;
2035 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002036 finalDeltaX = 0;
2037 finalDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07002038 if (dX == dY && dX == 0) {
2039 } else {
2040 if (dY == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002041 finalDeltaX = - Math.signum(dX) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002042 } else if (dX == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002043 finalDeltaY = - Math.signum(dY) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002044 } else {
2045 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend024f982012-05-23 18:26:45 -07002046 finalDeltaX = (int) (- Math.signum(dX) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002047 Math.abs(Math.cos(angle) * mReorderHintAnimationMagnitude));
Adam Cohend024f982012-05-23 18:26:45 -07002048 finalDeltaY = (int) (- Math.signum(dY) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002049 Math.abs(Math.sin(angle) * mReorderHintAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002050 }
2051 }
Adam Cohend024f982012-05-23 18:26:45 -07002052 initDeltaX = child.getTranslationX();
2053 initDeltaY = child.getTranslationY();
2054 finalScale = 1.0f - 4.0f / child.getWidth();
2055 initScale = child.getScaleX();
2056
Brandon Keely50e6e562012-05-08 16:28:49 -07002057 child.setPivotY(child.getMeasuredHeight() * 0.5f);
2058 child.setPivotX(child.getMeasuredWidth() * 0.5f);
Adam Cohen19f37922012-03-21 11:59:11 -07002059 this.child = child;
2060 }
2061
Adam Cohend024f982012-05-23 18:26:45 -07002062 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002063 if (mShakeAnimators.containsKey(child)) {
2064 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002065 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002066 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002067 if (finalDeltaX == 0 && finalDeltaY == 0) {
2068 completeAnimationImmediately();
2069 return;
2070 }
Adam Cohen19f37922012-03-21 11:59:11 -07002071 }
Adam Cohend024f982012-05-23 18:26:45 -07002072 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002073 return;
2074 }
Michael Jurka2ecf9952012-06-18 12:52:28 -07002075 ValueAnimator va = LauncherAnimUtils.ofFloat(0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002076 a = va;
Adam Cohen19f37922012-03-21 11:59:11 -07002077 va.setRepeatMode(ValueAnimator.REVERSE);
2078 va.setRepeatCount(ValueAnimator.INFINITE);
Adam Cohen7bdfc972012-05-22 16:50:35 -07002079 va.setDuration(DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002080 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002081 va.addUpdateListener(new AnimatorUpdateListener() {
2082 @Override
2083 public void onAnimationUpdate(ValueAnimator animation) {
2084 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohend024f982012-05-23 18:26:45 -07002085 float x = r * finalDeltaX + (1 - r) * initDeltaX;
2086 float y = r * finalDeltaY + (1 - r) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002087 child.setTranslationX(x);
2088 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002089 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002090 child.setScaleX(s);
2091 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002092 }
2093 });
2094 va.addListener(new AnimatorListenerAdapter() {
2095 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002096 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002097 initDeltaX = 0;
2098 initDeltaY = 0;
2099 initScale = 1.0f;
Adam Cohen19f37922012-03-21 11:59:11 -07002100 }
2101 });
Adam Cohen19f37922012-03-21 11:59:11 -07002102 mShakeAnimators.put(child, this);
2103 va.start();
2104 }
2105
Adam Cohend024f982012-05-23 18:26:45 -07002106 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002107 if (a != null) {
2108 a.cancel();
2109 }
Adam Cohen19f37922012-03-21 11:59:11 -07002110 }
Adam Cohene7587d22012-05-24 18:50:02 -07002111
Brandon Keely50e6e562012-05-08 16:28:49 -07002112 private void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002113 if (a != null) {
2114 a.cancel();
2115 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002116
Michael Jurka2ecf9952012-06-18 12:52:28 -07002117 AnimatorSet s = LauncherAnimUtils.createAnimatorSet();
Adam Cohene7587d22012-05-24 18:50:02 -07002118 a = s;
Brandon Keely50e6e562012-05-08 16:28:49 -07002119 s.playTogether(
Michael Jurka2ecf9952012-06-18 12:52:28 -07002120 LauncherAnimUtils.ofFloat(child, "scaleX", 1f),
2121 LauncherAnimUtils.ofFloat(child, "scaleY", 1f),
2122 LauncherAnimUtils.ofFloat(child, "translationX", 0f),
2123 LauncherAnimUtils.ofFloat(child, "translationY", 0f)
Brandon Keely50e6e562012-05-08 16:28:49 -07002124 );
2125 s.setDuration(REORDER_ANIMATION_DURATION);
2126 s.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2127 s.start();
2128 }
Adam Cohen19f37922012-03-21 11:59:11 -07002129 }
2130
2131 private void completeAndClearReorderHintAnimations() {
2132 for (ReorderHintAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002133 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002134 }
2135 mShakeAnimators.clear();
2136 }
2137
Adam Cohen482ed822012-03-02 14:15:13 -08002138 private void commitTempPlacement() {
2139 for (int i = 0; i < mCountX; i++) {
2140 for (int j = 0; j < mCountY; j++) {
2141 mOccupied[i][j] = mTmpOccupied[i][j];
2142 }
2143 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002144 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002145 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002146 View child = mShortcutsAndWidgets.getChildAt(i);
2147 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2148 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002149 // We do a null check here because the item info can be null in the case of the
2150 // AllApps button in the hotseat.
2151 if (info != null) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07002152 if (info.cellX != lp.tmpCellX || info.cellY != lp.tmpCellY ||
2153 info.spanX != lp.cellHSpan || info.spanY != lp.cellVSpan) {
2154 info.requiresDbUpdate = true;
2155 }
Adam Cohen2acce882012-03-28 19:03:19 -07002156 info.cellX = lp.cellX = lp.tmpCellX;
2157 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002158 info.spanX = lp.cellHSpan;
2159 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002160 }
Adam Cohen482ed822012-03-02 14:15:13 -08002161 }
Adam Cohen2acce882012-03-28 19:03:19 -07002162 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002163 }
2164
2165 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002166 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002167 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002168 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002169 lp.useTmpCoords = useTempCoords;
2170 }
2171 }
2172
Adam Cohen482ed822012-03-02 14:15:13 -08002173 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2174 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2175 int[] result = new int[2];
2176 int[] resultSpan = new int[2];
2177 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2178 resultSpan);
2179 if (result[0] >= 0 && result[1] >= 0) {
2180 copyCurrentStateToSolution(solution, false);
2181 solution.dragViewX = result[0];
2182 solution.dragViewY = result[1];
2183 solution.dragViewSpanX = resultSpan[0];
2184 solution.dragViewSpanY = resultSpan[1];
2185 solution.isSolution = true;
2186 } else {
2187 solution.isSolution = false;
2188 }
2189 return solution;
2190 }
2191
2192 public void prepareChildForDrag(View child) {
2193 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002194 }
2195
Adam Cohen19f37922012-03-21 11:59:11 -07002196 /* This seems like it should be obvious and straight-forward, but when the direction vector
2197 needs to match with the notion of the dragView pushing other views, we have to employ
2198 a slightly more subtle notion of the direction vector. The question is what two points is
2199 the vector between? The center of the dragView and its desired destination? Not quite, as
2200 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2201 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2202 or right, which helps make pushing feel right.
2203 */
2204 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2205 int spanY, View dragView, int[] resultDirection) {
2206 int[] targetDestination = new int[2];
2207
2208 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2209 Rect dragRect = new Rect();
2210 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2211 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2212
2213 Rect dropRegionRect = new Rect();
2214 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2215 dragView, dropRegionRect, mIntersectingViews);
2216
2217 int dropRegionSpanX = dropRegionRect.width();
2218 int dropRegionSpanY = dropRegionRect.height();
2219
2220 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2221 dropRegionRect.height(), dropRegionRect);
2222
2223 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2224 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2225
2226 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2227 deltaX = 0;
2228 }
2229 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2230 deltaY = 0;
2231 }
2232
2233 if (deltaX == 0 && deltaY == 0) {
2234 // No idea what to do, give a random direction.
2235 resultDirection[0] = 1;
2236 resultDirection[1] = 0;
2237 } else {
2238 computeDirectionVector(deltaX, deltaY, resultDirection);
2239 }
2240 }
2241
2242 // For a given cell and span, fetch the set of views intersecting the region.
2243 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2244 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2245 if (boundingRect != null) {
2246 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2247 }
2248 intersectingViews.clear();
2249 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2250 Rect r1 = new Rect();
2251 final int count = mShortcutsAndWidgets.getChildCount();
2252 for (int i = 0; i < count; i++) {
2253 View child = mShortcutsAndWidgets.getChildAt(i);
2254 if (child == dragView) continue;
2255 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2256 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2257 if (Rect.intersects(r0, r1)) {
2258 mIntersectingViews.add(child);
2259 if (boundingRect != null) {
2260 boundingRect.union(r1);
2261 }
2262 }
2263 }
2264 }
2265
2266 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2267 View dragView, int[] result) {
2268 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2269 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2270 mIntersectingViews);
2271 return !mIntersectingViews.isEmpty();
2272 }
2273
2274 void revertTempState() {
2275 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2276 final int count = mShortcutsAndWidgets.getChildCount();
2277 for (int i = 0; i < count; i++) {
2278 View child = mShortcutsAndWidgets.getChildAt(i);
2279 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2280 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2281 lp.tmpCellX = lp.cellX;
2282 lp.tmpCellY = lp.cellY;
2283 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2284 0, false, false);
2285 }
2286 }
2287 completeAndClearReorderHintAnimations();
2288 setItemPlacementDirty(false);
2289 }
2290
Adam Cohenbebf0422012-04-11 18:06:28 -07002291 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2292 View dragView, int[] direction, boolean commit) {
2293 int[] pixelXY = new int[2];
2294 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2295
2296 // First we determine if things have moved enough to cause a different layout
2297 ItemConfiguration swapSolution = simpleSwap(pixelXY[0], pixelXY[1], spanX, spanY,
2298 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2299
2300 setUseTempCoords(true);
2301 if (swapSolution != null && swapSolution.isSolution) {
2302 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2303 // committing anything or animating anything as we just want to determine if a solution
2304 // exists
2305 copySolutionToTempState(swapSolution, dragView);
2306 setItemPlacementDirty(true);
2307 animateItemsToSolution(swapSolution, dragView, commit);
2308
2309 if (commit) {
2310 commitTempPlacement();
2311 completeAndClearReorderHintAnimations();
2312 setItemPlacementDirty(false);
2313 } else {
2314 beginOrAdjustHintAnimations(swapSolution, dragView,
2315 REORDER_ANIMATION_DURATION);
2316 }
2317 mShortcutsAndWidgets.requestLayout();
2318 }
2319 return swapSolution.isSolution;
2320 }
2321
Adam Cohen482ed822012-03-02 14:15:13 -08002322 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2323 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002324 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002325 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002326
2327 if (resultSpan == null) {
2328 resultSpan = new int[2];
2329 }
2330
Adam Cohen19f37922012-03-21 11:59:11 -07002331 // When we are checking drop validity or actually dropping, we don't recompute the
2332 // direction vector, since we want the solution to match the preview, and it's possible
2333 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002334 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2335 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002336 mDirectionVector[0] = mPreviousReorderDirection[0];
2337 mDirectionVector[1] = mPreviousReorderDirection[1];
2338 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002339 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2340 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2341 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002342 }
2343 } else {
2344 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2345 mPreviousReorderDirection[0] = mDirectionVector[0];
2346 mPreviousReorderDirection[1] = mDirectionVector[1];
2347 }
2348
Adam Cohen482ed822012-03-02 14:15:13 -08002349 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2350 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2351
2352 // We attempt the approach which doesn't shuffle views at all
2353 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2354 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2355
2356 ItemConfiguration finalSolution = null;
2357 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2358 finalSolution = swapSolution;
2359 } else if (noShuffleSolution.isSolution) {
2360 finalSolution = noShuffleSolution;
2361 }
2362
2363 boolean foundSolution = true;
2364 if (!DESTRUCTIVE_REORDER) {
2365 setUseTempCoords(true);
2366 }
2367
2368 if (finalSolution != null) {
2369 result[0] = finalSolution.dragViewX;
2370 result[1] = finalSolution.dragViewY;
2371 resultSpan[0] = finalSolution.dragViewSpanX;
2372 resultSpan[1] = finalSolution.dragViewSpanY;
2373
2374 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2375 // committing anything or animating anything as we just want to determine if a solution
2376 // exists
2377 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2378 if (!DESTRUCTIVE_REORDER) {
2379 copySolutionToTempState(finalSolution, dragView);
2380 }
2381 setItemPlacementDirty(true);
2382 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2383
Adam Cohen19f37922012-03-21 11:59:11 -07002384 if (!DESTRUCTIVE_REORDER &&
2385 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002386 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002387 completeAndClearReorderHintAnimations();
2388 setItemPlacementDirty(false);
2389 } else {
2390 beginOrAdjustHintAnimations(finalSolution, dragView,
2391 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002392 }
2393 }
2394 } else {
2395 foundSolution = false;
2396 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2397 }
2398
2399 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2400 setUseTempCoords(false);
2401 }
Adam Cohen482ed822012-03-02 14:15:13 -08002402
Michael Jurkaa52570f2012-03-20 03:18:20 -07002403 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002404 return result;
2405 }
2406
Adam Cohen19f37922012-03-21 11:59:11 -07002407 void setItemPlacementDirty(boolean dirty) {
2408 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002409 }
Adam Cohen19f37922012-03-21 11:59:11 -07002410 boolean isItemPlacementDirty() {
2411 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002412 }
2413
2414 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002415 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002416 boolean isSolution = false;
2417 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2418
2419 int area() {
2420 return dragViewSpanX * dragViewSpanY;
2421 }
Adam Cohen8baab352012-03-20 17:39:21 -07002422 }
2423
2424 private class CellAndSpan {
2425 int x, y;
2426 int spanX, spanY;
2427
2428 public CellAndSpan(int x, int y, int spanX, int spanY) {
2429 this.x = x;
2430 this.y = y;
2431 this.spanX = spanX;
2432 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002433 }
2434 }
2435
Adam Cohendf035382011-04-11 17:22:04 -07002436 /**
2437 * Find a vacant area that will fit the given bounds nearest the requested
2438 * cell location. Uses Euclidean distance to score multiple vacant areas.
2439 *
2440 * @param pixelX The X location at which you want to search for a vacant area.
2441 * @param pixelY The Y location at which you want to search for a vacant area.
2442 * @param spanX Horizontal span of the object.
2443 * @param spanY Vertical span of the object.
2444 * @param ignoreView Considers space occupied by this view as unoccupied
2445 * @param result Previously returned value to possibly recycle.
2446 * @return The X, Y cell of a vacant area that can contain this object,
2447 * nearest the requested location.
2448 */
2449 int[] findNearestVacantArea(
2450 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2451 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2452 }
2453
2454 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002455 * Find a vacant area that will fit the given bounds nearest the requested
2456 * cell location. Uses Euclidean distance to score multiple vacant areas.
2457 *
2458 * @param pixelX The X location at which you want to search for a vacant area.
2459 * @param pixelY The Y location at which you want to search for a vacant area.
2460 * @param minSpanX The minimum horizontal span required
2461 * @param minSpanY The minimum vertical span required
2462 * @param spanX Horizontal span of the object.
2463 * @param spanY Vertical span of the object.
2464 * @param ignoreView Considers space occupied by this view as unoccupied
2465 * @param result Previously returned value to possibly recycle.
2466 * @return The X, Y cell of a vacant area that can contain this object,
2467 * nearest the requested location.
2468 */
2469 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2470 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002471 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2472 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002473 }
2474
2475 /**
Adam Cohendf035382011-04-11 17:22:04 -07002476 * Find a starting cell position that will fit the given bounds nearest the requested
2477 * cell location. Uses Euclidean distance to score multiple vacant areas.
2478 *
2479 * @param pixelX The X location at which you want to search for a vacant area.
2480 * @param pixelY The Y location at which you want to search for a vacant area.
2481 * @param spanX Horizontal span of the object.
2482 * @param spanY Vertical span of the object.
2483 * @param ignoreView Considers space occupied by this view as unoccupied
2484 * @param result Previously returned value to possibly recycle.
2485 * @return The X, Y cell of a vacant area that can contain this object,
2486 * nearest the requested location.
2487 */
2488 int[] findNearestArea(
2489 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2490 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2491 }
2492
Michael Jurka0280c3b2010-09-17 15:00:07 -07002493 boolean existsEmptyCell() {
2494 return findCellForSpan(null, 1, 1);
2495 }
2496
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002497 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002498 * Finds the upper-left coordinate of the first rectangle in the grid that can
2499 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2500 * then this method will only return coordinates for rectangles that contain the cell
2501 * (intersectX, intersectY)
2502 *
2503 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2504 * can be found.
2505 * @param spanX The horizontal span of the cell we want to find.
2506 * @param spanY The vertical span of the cell we want to find.
2507 *
2508 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002509 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002510 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002511 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002512 }
2513
2514 /**
2515 * Like above, but ignores any cells occupied by the item "ignoreView"
2516 *
2517 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2518 * can be found.
2519 * @param spanX The horizontal span of the cell we want to find.
2520 * @param spanY The vertical span of the cell we want to find.
2521 * @param ignoreView The home screen item we should treat as not occupying any space
2522 * @return
2523 */
2524 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002525 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2526 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002527 }
2528
2529 /**
2530 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2531 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2532 *
2533 * @param spanX The horizontal span of the cell we want to find.
2534 * @param spanY The vertical span of the cell we want to find.
2535 * @param ignoreView The home screen item we should treat as not occupying any space
2536 * @param intersectX The X coordinate of the cell that we should try to overlap
2537 * @param intersectX The Y coordinate of the cell that we should try to overlap
2538 *
2539 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2540 */
2541 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2542 int intersectX, int intersectY) {
2543 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002544 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002545 }
2546
2547 /**
2548 * The superset of the above two methods
2549 */
2550 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002551 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002552 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002553 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002554
Michael Jurka28750fb2010-09-24 17:43:49 -07002555 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002556 while (true) {
2557 int startX = 0;
2558 if (intersectX >= 0) {
2559 startX = Math.max(startX, intersectX - (spanX - 1));
2560 }
2561 int endX = mCountX - (spanX - 1);
2562 if (intersectX >= 0) {
2563 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2564 }
2565 int startY = 0;
2566 if (intersectY >= 0) {
2567 startY = Math.max(startY, intersectY - (spanY - 1));
2568 }
2569 int endY = mCountY - (spanY - 1);
2570 if (intersectY >= 0) {
2571 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2572 }
2573
Winson Chungbbc60d82010-11-11 16:34:41 -08002574 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002575 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002576 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002577 for (int i = 0; i < spanX; i++) {
2578 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002579 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002580 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002581 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002582 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002583 continue inner;
2584 }
2585 }
2586 }
2587 if (cellXY != null) {
2588 cellXY[0] = x;
2589 cellXY[1] = y;
2590 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002591 foundCell = true;
2592 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002593 }
2594 }
2595 if (intersectX == -1 && intersectY == -1) {
2596 break;
2597 } else {
2598 // if we failed to find anything, try again but without any requirements of
2599 // intersecting
2600 intersectX = -1;
2601 intersectY = -1;
2602 continue;
2603 }
2604 }
2605
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002606 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002607 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002608 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002609 }
2610
2611 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002612 * A drag event has begun over this layout.
2613 * It may have begun over this layout (in which case onDragChild is called first),
2614 * or it may have begun on another layout.
2615 */
2616 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002617 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002618 mDragging = true;
2619 }
2620
2621 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002622 * Called when drag has left this CellLayout or has been completed (successfully or not)
2623 */
2624 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002625 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002626 // This can actually be called when we aren't in a drag, e.g. when adding a new
2627 // item to this layout via the customize drawer.
2628 // Guard against that case.
2629 if (mDragging) {
2630 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002631 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002632
2633 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002634 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002635 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2636 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002637 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002638 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002639 }
2640
2641 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002642 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002643 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002644 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002645 *
2646 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002647 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002648 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002649 if (child != null) {
2650 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002651 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002652 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002653 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002654 }
2655
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002656 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002657 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002658 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002659 * @param cellX X coordinate of upper left corner expressed as a cell position
2660 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002661 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002662 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002663 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002664 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002665 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002666 final int cellWidth = mCellWidth;
2667 final int cellHeight = mCellHeight;
2668 final int widthGap = mWidthGap;
2669 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002670
Winson Chung4b825dcd2011-06-19 12:41:22 -07002671 final int hStartPadding = getPaddingLeft();
2672 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002673
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002674 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2675 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2676
2677 int x = hStartPadding + cellX * (cellWidth + widthGap);
2678 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002679
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002680 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002681 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002682
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002683 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002684 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002685 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002686 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002687 * @param width Width in pixels
2688 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002689 * @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 -08002690 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002691 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002692 return rectToCell(getResources(), width, height, result);
2693 }
2694
2695 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002696 // Always assume we're working with the smallest span to make sure we
2697 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002698 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2699 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002700 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002701
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002702 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002703 int spanX = (int) Math.ceil(width / (float) smallerSize);
2704 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002705
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002706 if (result == null) {
2707 return new int[] { spanX, spanY };
2708 }
2709 result[0] = spanX;
2710 result[1] = spanY;
2711 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002712 }
2713
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002714 public int[] cellSpansToSize(int hSpans, int vSpans) {
2715 int[] size = new int[2];
2716 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2717 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2718 return size;
2719 }
2720
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002721 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002722 * Calculate the grid spans needed to fit given item
2723 */
2724 public void calculateSpans(ItemInfo info) {
2725 final int minWidth;
2726 final int minHeight;
2727
2728 if (info instanceof LauncherAppWidgetInfo) {
2729 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2730 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2731 } else if (info instanceof PendingAddWidgetInfo) {
2732 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2733 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2734 } else {
2735 // It's not a widget, so it must be 1x1
2736 info.spanX = info.spanY = 1;
2737 return;
2738 }
2739 int[] spans = rectToCell(minWidth, minHeight, null);
2740 info.spanX = spans[0];
2741 info.spanY = spans[1];
2742 }
2743
2744 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002745 * Find the first vacant cell, if there is one.
2746 *
2747 * @param vacant Holds the x and y coordinate of the vacant cell
2748 * @param spanX Horizontal cell span.
2749 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002750 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002751 * @return True if a vacant cell was found
2752 */
2753 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002754
Michael Jurka0280c3b2010-09-17 15:00:07 -07002755 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002756 }
2757
2758 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2759 int xCount, int yCount, boolean[][] occupied) {
2760
Adam Cohen2801caf2011-05-13 20:57:39 -07002761 for (int y = 0; y < yCount; y++) {
2762 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002763 boolean available = !occupied[x][y];
2764out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2765 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2766 available = available && !occupied[i][j];
2767 if (!available) break out;
2768 }
2769 }
2770
2771 if (available) {
2772 vacant[0] = x;
2773 vacant[1] = y;
2774 return true;
2775 }
2776 }
2777 }
2778
2779 return false;
2780 }
2781
Michael Jurka0280c3b2010-09-17 15:00:07 -07002782 private void clearOccupiedCells() {
2783 for (int x = 0; x < mCountX; x++) {
2784 for (int y = 0; y < mCountY; y++) {
2785 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002786 }
2787 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002788 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002789
Adam Cohend41fbf52012-02-16 23:53:59 -08002790 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002791 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002792 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002793 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002794
Adam Cohend4844c32011-02-18 19:25:06 -08002795 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002796 markCellsAsOccupiedForView(view, mOccupied);
2797 }
2798 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002799 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002800 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002801 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002802 }
2803
Adam Cohend4844c32011-02-18 19:25:06 -08002804 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002805 markCellsAsUnoccupiedForView(view, mOccupied);
2806 }
2807 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002808 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002809 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002810 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002811 }
2812
Adam Cohen482ed822012-03-02 14:15:13 -08002813 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2814 boolean value) {
2815 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002816 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2817 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002818 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002819 }
2820 }
2821 }
2822
Adam Cohen2801caf2011-05-13 20:57:39 -07002823 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002824 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002825 (Math.max((mCountX - 1), 0) * mWidthGap);
2826 }
2827
2828 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002829 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002830 (Math.max((mCountY - 1), 0) * mHeightGap);
2831 }
2832
Michael Jurka66d72172011-04-12 16:29:25 -07002833 public boolean isOccupied(int x, int y) {
2834 if (x < mCountX && y < mCountY) {
2835 return mOccupied[x][y];
2836 } else {
2837 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2838 }
2839 }
2840
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002841 @Override
2842 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2843 return new CellLayout.LayoutParams(getContext(), attrs);
2844 }
2845
2846 @Override
2847 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2848 return p instanceof CellLayout.LayoutParams;
2849 }
2850
2851 @Override
2852 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2853 return new CellLayout.LayoutParams(p);
2854 }
2855
Winson Chungaafa03c2010-06-11 17:34:16 -07002856 public static class CellLayoutAnimationController extends LayoutAnimationController {
2857 public CellLayoutAnimationController(Animation animation, float delay) {
2858 super(animation, delay);
2859 }
2860
2861 @Override
2862 protected long getDelayForView(View view) {
2863 return (int) (Math.random() * 150);
2864 }
2865 }
2866
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002867 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2868 /**
2869 * Horizontal location of the item in the grid.
2870 */
2871 @ViewDebug.ExportedProperty
2872 public int cellX;
2873
2874 /**
2875 * Vertical location of the item in the grid.
2876 */
2877 @ViewDebug.ExportedProperty
2878 public int cellY;
2879
2880 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002881 * Temporary horizontal location of the item in the grid during reorder
2882 */
2883 public int tmpCellX;
2884
2885 /**
2886 * Temporary vertical location of the item in the grid during reorder
2887 */
2888 public int tmpCellY;
2889
2890 /**
2891 * Indicates that the temporary coordinates should be used to layout the items
2892 */
2893 public boolean useTmpCoords;
2894
2895 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002896 * Number of cells spanned horizontally by the item.
2897 */
2898 @ViewDebug.ExportedProperty
2899 public int cellHSpan;
2900
2901 /**
2902 * Number of cells spanned vertically by the item.
2903 */
2904 @ViewDebug.ExportedProperty
2905 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002906
Adam Cohen1b607ed2011-03-03 17:26:50 -08002907 /**
2908 * Indicates whether the item will set its x, y, width and height parameters freely,
2909 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2910 */
Adam Cohend4844c32011-02-18 19:25:06 -08002911 public boolean isLockedToGrid = true;
2912
Adam Cohen482ed822012-03-02 14:15:13 -08002913 /**
2914 * Indicates whether this item can be reordered. Always true except in the case of the
2915 * the AllApps button.
2916 */
2917 public boolean canReorder = true;
2918
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002919 // X coordinate of the view in the layout.
2920 @ViewDebug.ExportedProperty
2921 int x;
2922 // Y coordinate of the view in the layout.
2923 @ViewDebug.ExportedProperty
2924 int y;
2925
Romain Guy84f296c2009-11-04 15:00:44 -08002926 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002927
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002928 public LayoutParams(Context c, AttributeSet attrs) {
2929 super(c, attrs);
2930 cellHSpan = 1;
2931 cellVSpan = 1;
2932 }
2933
2934 public LayoutParams(ViewGroup.LayoutParams source) {
2935 super(source);
2936 cellHSpan = 1;
2937 cellVSpan = 1;
2938 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002939
2940 public LayoutParams(LayoutParams source) {
2941 super(source);
2942 this.cellX = source.cellX;
2943 this.cellY = source.cellY;
2944 this.cellHSpan = source.cellHSpan;
2945 this.cellVSpan = source.cellVSpan;
2946 }
2947
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002948 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002949 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002950 this.cellX = cellX;
2951 this.cellY = cellY;
2952 this.cellHSpan = cellHSpan;
2953 this.cellVSpan = cellVSpan;
2954 }
2955
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002956 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002957 if (isLockedToGrid) {
2958 final int myCellHSpan = cellHSpan;
2959 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002960 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2961 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002962
Adam Cohend4844c32011-02-18 19:25:06 -08002963 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2964 leftMargin - rightMargin;
2965 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2966 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002967 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2968 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002969 }
2970 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002971
Winson Chungaafa03c2010-06-11 17:34:16 -07002972 public String toString() {
2973 return "(" + this.cellX + ", " + this.cellY + ")";
2974 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002975
2976 public void setWidth(int width) {
2977 this.width = width;
2978 }
2979
2980 public int getWidth() {
2981 return width;
2982 }
2983
2984 public void setHeight(int height) {
2985 this.height = height;
2986 }
2987
2988 public int getHeight() {
2989 return height;
2990 }
2991
2992 public void setX(int x) {
2993 this.x = x;
2994 }
2995
2996 public int getX() {
2997 return x;
2998 }
2999
3000 public void setY(int y) {
3001 this.y = y;
3002 }
3003
3004 public int getY() {
3005 return y;
3006 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003007 }
3008
Michael Jurka0280c3b2010-09-17 15:00:07 -07003009 // This class stores info for two purposes:
3010 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
3011 // its spanX, spanY, and the screen it is on
3012 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
3013 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
3014 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07003015 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003016 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07003017 int cellX = -1;
3018 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003019 int spanX;
3020 int spanY;
3021 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07003022 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003023
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003024 @Override
3025 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07003026 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
3027 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003028 }
3029 }
Michael Jurkad771c962011-08-09 15:00:48 -07003030
3031 public boolean lastDownOnOccupiedCell() {
3032 return mLastDownOnOccupiedCell;
3033 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003034}