blob: 3ad13369f411f69750bcf6124815bfc64b57e1e6 [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) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001541 boolean fail = false;
1542 for (int i = 0; i < spanX; i++) {
1543 for (int j = 0; j < spanY; j++) {
1544 if (occupied[x + i][y + j] && (blockOccupied == null || blockOccupied[i][j])) {
1545 fail = true;
1546 }
1547 }
1548 }
1549 if (!fail) {
1550 float distance = (float)
1551 Math.sqrt((x - cellX) * (x - cellX) + (y - cellY) * (y - cellY));
1552 if (Float.compare(distance, bestDistance) < 0) {
1553 bestDistance = distance;
1554 bestXY[0] = x;
1555 bestXY[1] = y;
1556 }
1557 }
1558 x += direction[0];
1559 y += direction[1];
1560 }
1561 return bestXY;
1562 }
1563
Adam Cohen482ed822012-03-02 14:15:13 -08001564 private boolean addViewToTempLocation(View v, Rect rectOccupiedByPotentialDrop,
Adam Cohen8baab352012-03-20 17:39:21 -07001565 int[] direction, ItemConfiguration currentState) {
1566 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001567 boolean success = false;
Adam Cohen8baab352012-03-20 17:39:21 -07001568 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
Adam Cohen482ed822012-03-02 14:15:13 -08001569 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1570
Adam Cohen8baab352012-03-20 17:39:21 -07001571 findNearestArea(c.x, c.y, c.spanX, c.spanY, direction, mTmpOccupied, null, mTempLocation);
Adam Cohen482ed822012-03-02 14:15:13 -08001572
1573 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001574 c.x = mTempLocation[0];
1575 c.y = mTempLocation[1];
Adam Cohen482ed822012-03-02 14:15:13 -08001576 success = true;
1577
1578 }
Adam Cohen8baab352012-03-20 17:39:21 -07001579 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001580 return success;
1581 }
1582
Adam Cohena56dc102012-07-13 13:41:42 -07001583 // This method looks in the specified direction to see if there are additional views adjacent
1584 // to the current set of views in the. If there is, then these views are added to the current
1585 // set of views. This is performed iteratively, giving a cascading push behaviour.
Adam Cohen47a876d2012-03-19 13:21:41 -07001586 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
Adam Cohena56dc102012-07-13 13:41:42 -07001594 // First, we consider the rect of the views that we are trying to translate
Adam Cohen47a876d2012-03-19 13:21:41 -07001595 int deltaX = 0;
1596 int deltaY = 0;
1597 if (direction[1] < 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001598 r0.set(r0.left, r0.top - 1, r0.right, r0.bottom - 1);
Adam Cohen47a876d2012-03-19 13:21:41 -07001599 deltaY = -1;
1600 } else if (direction[1] > 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001601 r0.set(r0.left, r0.top + 1, r0.right, r0.bottom + 1);
Adam Cohen47a876d2012-03-19 13:21:41 -07001602 deltaY = 1;
1603 } else if (direction[0] < 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001604 r0.set(r0.left - 1, r0.top, r0.right - 1, r0.bottom);
Adam Cohen47a876d2012-03-19 13:21:41 -07001605 deltaX = -1;
1606 } else if (direction[0] > 0) {
Adam Cohena56dc102012-07-13 13:41:42 -07001607 r0.set(r0.left + 1, r0.top, r0.right + 1, r0.bottom);
Adam Cohen47a876d2012-03-19 13:21:41 -07001608 deltaX = 1;
1609 }
1610
Adam Cohena56dc102012-07-13 13:41:42 -07001611 // Now we see which views, if any, are being overlapped by shifting the current group
1612 // of views in the desired direction.
Adam Cohen47a876d2012-03-19 13:21:41 -07001613 for (int i = 0; i < childCount; i++) {
Adam Cohena56dc102012-07-13 13:41:42 -07001614 // We don't need to worry about views already in our group, or the current drag view.
Michael Jurkaa52570f2012-03-20 03:18:20 -07001615 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen19f37922012-03-21 11:59:11 -07001616 if (views.contains(child) || child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001617 CellAndSpan c = currentState.map.get(child);
Adam Cohen47a876d2012-03-19 13:21:41 -07001618
Adam Cohen8baab352012-03-20 17:39:21 -07001619 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1620 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen47a876d2012-03-19 13:21:41 -07001621 if (Rect.intersects(r0, r1)) {
1622 if (!lp.canReorder) {
1623 return false;
1624 }
Adam Cohena56dc102012-07-13 13:41:42 -07001625 // First we verify that the view in question is at the border of the extents
1626 // of the block of items we are pushing
1627 if ((direction[0] < 0 && c.x == r0.left) ||
1628 (direction[0] > 0 && c.x == r0.right - 1) ||
1629 (direction[1] < 0 && c.y == r0.top) ||
1630 (direction[1] > 0 && c.y == r0.bottom - 1)) {
1631 boolean pushed = false;
1632 // Since the bounding rect is a course description of the region (there can
1633 // be holes at the edge of the block), we need to check to verify that a solid
1634 // piece is intersecting. This ensures that interlocking is possible.
1635 for (int x = c.x; x < c.x + c.spanX; x++) {
1636 for (int y = c.y; y < c.y + c.spanY; y++) {
1637 if (occupied[x - deltaX][y - deltaY]) {
1638 pushed = true;
1639 break;
1640 }
1641 if (pushed) break;
Adam Cohen47a876d2012-03-19 13:21:41 -07001642 }
1643 }
Adam Cohena56dc102012-07-13 13:41:42 -07001644 if (pushed) {
1645 views.add(child);
1646 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
1647 found = true;
1648 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001649 }
1650 }
1651 }
1652 return found;
1653 }
1654
Adam Cohen482ed822012-03-02 14:15:13 -08001655 private boolean addViewsToTempLocation(ArrayList<View> views, Rect rectOccupiedByPotentialDrop,
Adam Cohen19f37922012-03-21 11:59:11 -07001656 int[] direction, boolean push, View dragView, ItemConfiguration currentState) {
Adam Cohen482ed822012-03-02 14:15:13 -08001657 if (views.size() == 0) return true;
Adam Cohen482ed822012-03-02 14:15:13 -08001658
Adam Cohen8baab352012-03-20 17:39:21 -07001659 boolean success = false;
Adam Cohen482ed822012-03-02 14:15:13 -08001660 Rect boundingRect = null;
Adam Cohen8baab352012-03-20 17:39:21 -07001661 // We construct a rect which represents the entire group of views passed in
Adam Cohen482ed822012-03-02 14:15:13 -08001662 for (View v: views) {
Adam Cohen8baab352012-03-20 17:39:21 -07001663 CellAndSpan c = currentState.map.get(v);
Adam Cohen482ed822012-03-02 14:15:13 -08001664 if (boundingRect == null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001665 boundingRect = new Rect(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001666 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001667 boundingRect.union(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001668 }
1669 }
Adam Cohen8baab352012-03-20 17:39:21 -07001670
1671 @SuppressWarnings("unchecked")
1672 ArrayList<View> dup = (ArrayList<View>) views.clone();
1673 // We try and expand the group of views in the direction vector passed, based on
1674 // whether they are physically adjacent, ie. based on "push mechanics".
Adam Cohen19f37922012-03-21 11:59:11 -07001675 while (push && addViewInDirection(dup, boundingRect, direction, mTmpOccupied, dragView,
Adam Cohen8baab352012-03-20 17:39:21 -07001676 currentState)) {
1677 }
1678
1679 // Mark the occupied state as false for the group of views we want to move.
1680 for (View v: dup) {
1681 CellAndSpan c = currentState.map.get(v);
1682 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, false);
1683 }
1684
Adam Cohen47a876d2012-03-19 13:21:41 -07001685 boolean[][] blockOccupied = new boolean[boundingRect.width()][boundingRect.height()];
1686 int top = boundingRect.top;
1687 int left = boundingRect.left;
Adam Cohen8baab352012-03-20 17:39:21 -07001688 // We mark more precisely which parts of the bounding rect are truly occupied, allowing
Adam Cohena56dc102012-07-13 13:41:42 -07001689 // for interlocking.
Adam Cohen8baab352012-03-20 17:39:21 -07001690 for (View v: dup) {
1691 CellAndSpan c = currentState.map.get(v);
1692 markCellsForView(c.x - left, c.y - top, c.spanX, c.spanY, blockOccupied, true);
Adam Cohen47a876d2012-03-19 13:21:41 -07001693 }
1694
Adam Cohen482ed822012-03-02 14:15:13 -08001695 markCellsForRect(rectOccupiedByPotentialDrop, mTmpOccupied, true);
1696
Adam Cohen8baab352012-03-20 17:39:21 -07001697 if (push) {
1698 findNearestAreaInDirection(boundingRect.left, boundingRect.top, boundingRect.width(),
1699 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1700 } else {
1701 findNearestArea(boundingRect.left, boundingRect.top, boundingRect.width(),
1702 boundingRect.height(), direction, mTmpOccupied, blockOccupied, mTempLocation);
1703 }
Adam Cohen482ed822012-03-02 14:15:13 -08001704
Adam Cohen8baab352012-03-20 17:39:21 -07001705 // If we successfuly found a location by pushing the block of views, we commit it
Adam Cohen482ed822012-03-02 14:15:13 -08001706 if (mTempLocation[0] >= 0 && mTempLocation[1] >= 0) {
Adam Cohen8baab352012-03-20 17:39:21 -07001707 int deltaX = mTempLocation[0] - boundingRect.left;
1708 int deltaY = mTempLocation[1] - boundingRect.top;
1709 for (View v: dup) {
1710 CellAndSpan c = currentState.map.get(v);
1711 c.x += deltaX;
1712 c.y += deltaY;
Adam Cohen482ed822012-03-02 14:15:13 -08001713 }
1714 success = true;
1715 }
Adam Cohen8baab352012-03-20 17:39:21 -07001716
1717 // In either case, we set the occupied array as marked for the location of the views
1718 for (View v: dup) {
1719 CellAndSpan c = currentState.map.get(v);
1720 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001721 }
1722 return success;
1723 }
1724
1725 private void markCellsForRect(Rect r, boolean[][] occupied, boolean value) {
1726 markCellsForView(r.left, r.top, r.width(), r.height(), occupied, value);
1727 }
1728
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001729 // This method tries to find a reordering solution which satisfies the push mechanic by trying
1730 // to push items in each of the cardinal directions, in an order based on the direction vector
1731 // passed.
1732 private boolean attemptPushInDirection(ArrayList<View> intersectingViews, Rect occupied,
1733 int[] direction, View ignoreView, ItemConfiguration solution) {
1734 if ((Math.abs(direction[0]) + Math.abs(direction[1])) > 1) {
1735 // If the direction vector has two non-zero components, we try pushing
1736 // separately in each of the components.
1737 int temp = direction[1];
1738 direction[1] = 0;
1739 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1740 ignoreView, solution)) {
1741 return true;
1742 }
1743 direction[1] = temp;
1744 temp = direction[0];
1745 direction[0] = 0;
1746 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1747 ignoreView, solution)) {
1748 return true;
1749 }
1750 // Revert the direction
1751 direction[0] = temp;
1752
1753 // Now we try pushing in each component of the opposite direction
1754 direction[0] *= -1;
1755 direction[1] *= -1;
1756 temp = direction[1];
1757 direction[1] = 0;
1758 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1759 ignoreView, solution)) {
1760 return true;
1761 }
1762
1763 direction[1] = temp;
1764 temp = direction[0];
1765 direction[0] = 0;
1766 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1767 ignoreView, solution)) {
1768 return true;
1769 }
1770 // revert the direction
1771 direction[0] = temp;
1772 direction[0] *= -1;
1773 direction[1] *= -1;
1774
1775 } else {
1776 // If the direction vector has a single non-zero component, we push first in the
1777 // direction of the vector
1778 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1779 ignoreView, solution)) {
1780 return true;
1781 }
1782
1783 // Then we try the opposite direction
1784 direction[0] *= -1;
1785 direction[1] *= -1;
1786 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1787 ignoreView, solution)) {
1788 return true;
1789 }
1790 // Switch the direction back
1791 direction[0] *= -1;
1792 direction[1] *= -1;
1793
1794 // If we have failed to find a push solution with the above, then we try
1795 // to find a solution by pushing along the perpendicular axis.
1796
1797 // Swap the components
1798 int temp = direction[1];
1799 direction[1] = direction[0];
1800 direction[0] = temp;
1801 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1802 ignoreView, solution)) {
1803 return true;
1804 }
1805
1806 // Then we try the opposite direction
1807 direction[0] *= -1;
1808 direction[1] *= -1;
1809 if (addViewsToTempLocation(intersectingViews, occupied, direction, true,
1810 ignoreView, solution)) {
1811 return true;
1812 }
1813 // Switch the direction back
1814 direction[0] *= -1;
1815 direction[1] *= -1;
1816
1817 // Swap the components back
1818 temp = direction[1];
1819 direction[1] = direction[0];
1820 direction[0] = temp;
1821 }
1822 return false;
1823 }
1824
Adam Cohen482ed822012-03-02 14:15:13 -08001825 private boolean rearrangementExists(int cellX, int cellY, int spanX, int spanY, int[] direction,
Adam Cohen8baab352012-03-20 17:39:21 -07001826 View ignoreView, ItemConfiguration solution) {
Winson Chunge3e03bc2012-05-01 15:10:11 -07001827 // Return early if get invalid cell positions
1828 if (cellX < 0 || cellY < 0) return false;
Adam Cohen482ed822012-03-02 14:15:13 -08001829
Adam Cohen8baab352012-03-20 17:39:21 -07001830 mIntersectingViews.clear();
Adam Cohen482ed822012-03-02 14:15:13 -08001831 mOccupiedRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001832
Adam Cohen8baab352012-03-20 17:39:21 -07001833 // Mark the desired location of the view currently being dragged.
Adam Cohen482ed822012-03-02 14:15:13 -08001834 if (ignoreView != null) {
Adam Cohen8baab352012-03-20 17:39:21 -07001835 CellAndSpan c = solution.map.get(ignoreView);
Adam Cohen19f37922012-03-21 11:59:11 -07001836 if (c != null) {
1837 c.x = cellX;
1838 c.y = cellY;
1839 }
Adam Cohen482ed822012-03-02 14:15:13 -08001840 }
Adam Cohen482ed822012-03-02 14:15:13 -08001841 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
1842 Rect r1 = new Rect();
Adam Cohen8baab352012-03-20 17:39:21 -07001843 for (View child: solution.map.keySet()) {
Adam Cohen482ed822012-03-02 14:15:13 -08001844 if (child == ignoreView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001845 CellAndSpan c = solution.map.get(child);
Adam Cohen482ed822012-03-02 14:15:13 -08001846 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001847 r1.set(c.x, c.y, c.x + c.spanX, c.y + c.spanY);
Adam Cohen482ed822012-03-02 14:15:13 -08001848 if (Rect.intersects(r0, r1)) {
1849 if (!lp.canReorder) {
1850 return false;
1851 }
1852 mIntersectingViews.add(child);
1853 }
1854 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001855
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001856 // First we try to find a solution which respects the push mechanic. That is,
1857 // we try to find a solution such that no displaced item travels through another item
1858 // without also displacing that item.
1859 if (attemptPushInDirection(mIntersectingViews, mOccupiedRect, direction, ignoreView,
Adam Cohen19f37922012-03-21 11:59:11 -07001860 solution)) {
Adam Cohen47a876d2012-03-19 13:21:41 -07001861 return true;
1862 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001863
Adam Cohen4abc5bd2012-05-29 21:06:03 -07001864 // Next we try moving the views as a block, but without requiring the push mechanic.
Adam Cohen19f37922012-03-21 11:59:11 -07001865 if (addViewsToTempLocation(mIntersectingViews, mOccupiedRect, direction, false, ignoreView,
1866 solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001867 return true;
1868 }
Adam Cohen47a876d2012-03-19 13:21:41 -07001869
Adam Cohen482ed822012-03-02 14:15:13 -08001870 // Ok, they couldn't move as a block, let's move them individually
1871 for (View v : mIntersectingViews) {
Adam Cohen8baab352012-03-20 17:39:21 -07001872 if (!addViewToTempLocation(v, mOccupiedRect, direction, solution)) {
Adam Cohen482ed822012-03-02 14:15:13 -08001873 return false;
1874 }
1875 }
1876 return true;
1877 }
1878
1879 /*
1880 * Returns a pair (x, y), where x,y are in {-1, 0, 1} corresponding to vector between
1881 * the provided point and the provided cell
1882 */
Adam Cohen47a876d2012-03-19 13:21:41 -07001883 private void computeDirectionVector(float deltaX, float deltaY, int[] result) {
Adam Cohen482ed822012-03-02 14:15:13 -08001884 double angle = Math.atan(((float) deltaY) / deltaX);
1885
1886 result[0] = 0;
1887 result[1] = 0;
1888 if (Math.abs(Math.cos(angle)) > 0.5f) {
1889 result[0] = (int) Math.signum(deltaX);
1890 }
1891 if (Math.abs(Math.sin(angle)) > 0.5f) {
1892 result[1] = (int) Math.signum(deltaY);
1893 }
1894 }
1895
Adam Cohen8baab352012-03-20 17:39:21 -07001896 private void copyOccupiedArray(boolean[][] occupied) {
1897 for (int i = 0; i < mCountX; i++) {
1898 for (int j = 0; j < mCountY; j++) {
1899 occupied[i][j] = mOccupied[i][j];
1900 }
1901 }
1902 }
1903
Adam Cohen482ed822012-03-02 14:15:13 -08001904 ItemConfiguration simpleSwap(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX,
1905 int spanY, int[] direction, View dragView, boolean decX, ItemConfiguration solution) {
Adam Cohen8baab352012-03-20 17:39:21 -07001906 // Copy the current state into the solution. This solution will be manipulated as necessary.
1907 copyCurrentStateToSolution(solution, false);
1908 // Copy the current occupied array into the temporary occupied array. This array will be
1909 // manipulated as necessary to find a solution.
1910 copyOccupiedArray(mTmpOccupied);
Adam Cohen482ed822012-03-02 14:15:13 -08001911
1912 // We find the nearest cell into which we would place the dragged item, assuming there's
1913 // nothing in its way.
1914 int result[] = new int[2];
1915 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
1916
1917 boolean success = false;
1918 // First we try the exact nearest position of the item being dragged,
1919 // we will then want to try to move this around to other neighbouring positions
Adam Cohen8baab352012-03-20 17:39:21 -07001920 success = rearrangementExists(result[0], result[1], spanX, spanY, direction, dragView,
1921 solution);
Adam Cohen482ed822012-03-02 14:15:13 -08001922
1923 if (!success) {
1924 // We try shrinking the widget down to size in an alternating pattern, shrink 1 in
1925 // x, then 1 in y etc.
1926 if (spanX > minSpanX && (minSpanY == spanY || decX)) {
1927 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX - 1, spanY, direction,
1928 dragView, false, solution);
1929 } else if (spanY > minSpanY) {
1930 return simpleSwap(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY - 1, direction,
1931 dragView, true, solution);
1932 }
1933 solution.isSolution = false;
1934 } else {
1935 solution.isSolution = true;
1936 solution.dragViewX = result[0];
1937 solution.dragViewY = result[1];
1938 solution.dragViewSpanX = spanX;
1939 solution.dragViewSpanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08001940 }
1941 return solution;
1942 }
1943
1944 private void copyCurrentStateToSolution(ItemConfiguration solution, boolean temp) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001945 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001946 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001947 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001948 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001949 CellAndSpan c;
Adam Cohen482ed822012-03-02 14:15:13 -08001950 if (temp) {
Adam Cohen8baab352012-03-20 17:39:21 -07001951 c = new CellAndSpan(lp.tmpCellX, lp.tmpCellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001952 } else {
Adam Cohen8baab352012-03-20 17:39:21 -07001953 c = new CellAndSpan(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan);
Adam Cohen482ed822012-03-02 14:15:13 -08001954 }
Adam Cohen8baab352012-03-20 17:39:21 -07001955 solution.map.put(child, c);
Adam Cohen482ed822012-03-02 14:15:13 -08001956 }
1957 }
1958
1959 private void copySolutionToTempState(ItemConfiguration solution, View dragView) {
1960 for (int i = 0; i < mCountX; i++) {
1961 for (int j = 0; j < mCountY; j++) {
1962 mTmpOccupied[i][j] = false;
1963 }
1964 }
1965
Michael Jurkaa52570f2012-03-20 03:18:20 -07001966 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001967 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001968 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001969 if (child == dragView) continue;
1970 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Adam Cohen8baab352012-03-20 17:39:21 -07001971 CellAndSpan c = solution.map.get(child);
1972 if (c != null) {
1973 lp.tmpCellX = c.x;
1974 lp.tmpCellY = c.y;
1975 lp.cellHSpan = c.spanX;
1976 lp.cellVSpan = c.spanY;
1977 markCellsForView(c.x, c.y, c.spanX, c.spanY, mTmpOccupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08001978 }
1979 }
1980 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
1981 solution.dragViewSpanY, mTmpOccupied, true);
1982 }
1983
1984 private void animateItemsToSolution(ItemConfiguration solution, View dragView, boolean
1985 commitDragView) {
1986
1987 boolean[][] occupied = DESTRUCTIVE_REORDER ? mOccupied : mTmpOccupied;
1988 for (int i = 0; i < mCountX; i++) {
1989 for (int j = 0; j < mCountY; j++) {
1990 occupied[i][j] = false;
1991 }
1992 }
1993
Michael Jurkaa52570f2012-03-20 03:18:20 -07001994 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08001995 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07001996 View child = mShortcutsAndWidgets.getChildAt(i);
Adam Cohen482ed822012-03-02 14:15:13 -08001997 if (child == dragView) continue;
Adam Cohen8baab352012-03-20 17:39:21 -07001998 CellAndSpan c = solution.map.get(child);
1999 if (c != null) {
Adam Cohen19f37922012-03-21 11:59:11 -07002000 animateChildToPosition(child, c.x, c.y, REORDER_ANIMATION_DURATION, 0,
2001 DESTRUCTIVE_REORDER, false);
Adam Cohen8baab352012-03-20 17:39:21 -07002002 markCellsForView(c.x, c.y, c.spanX, c.spanY, occupied, true);
Adam Cohen482ed822012-03-02 14:15:13 -08002003 }
2004 }
2005 if (commitDragView) {
2006 markCellsForView(solution.dragViewX, solution.dragViewY, solution.dragViewSpanX,
2007 solution.dragViewSpanY, occupied, true);
2008 }
2009 }
2010
Adam Cohen19f37922012-03-21 11:59:11 -07002011 // This method starts or changes the reorder hint animations
2012 private void beginOrAdjustHintAnimations(ItemConfiguration solution, View dragView, int delay) {
2013 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen19f37922012-03-21 11:59:11 -07002014 for (int i = 0; i < childCount; i++) {
2015 View child = mShortcutsAndWidgets.getChildAt(i);
2016 if (child == dragView) continue;
2017 CellAndSpan c = solution.map.get(child);
2018 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2019 if (c != null) {
2020 ReorderHintAnimation rha = new ReorderHintAnimation(child, lp.cellX, lp.cellY,
2021 c.x, c.y, c.spanX, c.spanY);
Adam Cohend024f982012-05-23 18:26:45 -07002022 rha.animate();
Adam Cohen19f37922012-03-21 11:59:11 -07002023 }
2024 }
2025 }
2026
2027 // Class which represents the reorder hint animations. These animations show that an item is
2028 // in a temporary state, and hint at where the item will return to.
2029 class ReorderHintAnimation {
2030 View child;
Adam Cohend024f982012-05-23 18:26:45 -07002031 float finalDeltaX;
2032 float finalDeltaY;
2033 float initDeltaX;
2034 float initDeltaY;
2035 float finalScale;
2036 float initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002037 private static final int DURATION = 300;
Adam Cohene7587d22012-05-24 18:50:02 -07002038 Animator a;
Adam Cohen19f37922012-03-21 11:59:11 -07002039
2040 public ReorderHintAnimation(View child, int cellX0, int cellY0, int cellX1, int cellY1,
2041 int spanX, int spanY) {
2042 regionToCenterPoint(cellX0, cellY0, spanX, spanY, mTmpPoint);
2043 final int x0 = mTmpPoint[0];
2044 final int y0 = mTmpPoint[1];
2045 regionToCenterPoint(cellX1, cellY1, spanX, spanY, mTmpPoint);
2046 final int x1 = mTmpPoint[0];
2047 final int y1 = mTmpPoint[1];
2048 final int dX = x1 - x0;
2049 final int dY = y1 - y0;
Adam Cohend024f982012-05-23 18:26:45 -07002050 finalDeltaX = 0;
2051 finalDeltaY = 0;
Adam Cohen19f37922012-03-21 11:59:11 -07002052 if (dX == dY && dX == 0) {
2053 } else {
2054 if (dY == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002055 finalDeltaX = - Math.signum(dX) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002056 } else if (dX == 0) {
Adam Cohend024f982012-05-23 18:26:45 -07002057 finalDeltaY = - Math.signum(dY) * mReorderHintAnimationMagnitude;
Adam Cohen19f37922012-03-21 11:59:11 -07002058 } else {
2059 double angle = Math.atan( (float) (dY) / dX);
Adam Cohend024f982012-05-23 18:26:45 -07002060 finalDeltaX = (int) (- Math.signum(dX) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002061 Math.abs(Math.cos(angle) * mReorderHintAnimationMagnitude));
Adam Cohend024f982012-05-23 18:26:45 -07002062 finalDeltaY = (int) (- Math.signum(dY) *
Adam Cohenfe41ac62012-05-23 14:00:37 -07002063 Math.abs(Math.sin(angle) * mReorderHintAnimationMagnitude));
Adam Cohen19f37922012-03-21 11:59:11 -07002064 }
2065 }
Adam Cohend024f982012-05-23 18:26:45 -07002066 initDeltaX = child.getTranslationX();
2067 initDeltaY = child.getTranslationY();
2068 finalScale = 1.0f - 4.0f / child.getWidth();
2069 initScale = child.getScaleX();
2070
Brandon Keely50e6e562012-05-08 16:28:49 -07002071 child.setPivotY(child.getMeasuredHeight() * 0.5f);
2072 child.setPivotX(child.getMeasuredWidth() * 0.5f);
Adam Cohen19f37922012-03-21 11:59:11 -07002073 this.child = child;
2074 }
2075
Adam Cohend024f982012-05-23 18:26:45 -07002076 void animate() {
Adam Cohen19f37922012-03-21 11:59:11 -07002077 if (mShakeAnimators.containsKey(child)) {
2078 ReorderHintAnimation oldAnimation = mShakeAnimators.get(child);
Adam Cohend024f982012-05-23 18:26:45 -07002079 oldAnimation.cancel();
Adam Cohen19f37922012-03-21 11:59:11 -07002080 mShakeAnimators.remove(child);
Adam Cohene7587d22012-05-24 18:50:02 -07002081 if (finalDeltaX == 0 && finalDeltaY == 0) {
2082 completeAnimationImmediately();
2083 return;
2084 }
Adam Cohen19f37922012-03-21 11:59:11 -07002085 }
Adam Cohend024f982012-05-23 18:26:45 -07002086 if (finalDeltaX == 0 && finalDeltaY == 0) {
Adam Cohen19f37922012-03-21 11:59:11 -07002087 return;
2088 }
Michael Jurka2ecf9952012-06-18 12:52:28 -07002089 ValueAnimator va = LauncherAnimUtils.ofFloat(0f, 1f);
Adam Cohene7587d22012-05-24 18:50:02 -07002090 a = va;
Adam Cohen19f37922012-03-21 11:59:11 -07002091 va.setRepeatMode(ValueAnimator.REVERSE);
2092 va.setRepeatCount(ValueAnimator.INFINITE);
Adam Cohen7bdfc972012-05-22 16:50:35 -07002093 va.setDuration(DURATION);
Adam Cohend024f982012-05-23 18:26:45 -07002094 va.setStartDelay((int) (Math.random() * 60));
Adam Cohen19f37922012-03-21 11:59:11 -07002095 va.addUpdateListener(new AnimatorUpdateListener() {
2096 @Override
2097 public void onAnimationUpdate(ValueAnimator animation) {
2098 float r = ((Float) animation.getAnimatedValue()).floatValue();
Adam Cohend024f982012-05-23 18:26:45 -07002099 float x = r * finalDeltaX + (1 - r) * initDeltaX;
2100 float y = r * finalDeltaY + (1 - r) * initDeltaY;
Adam Cohen19f37922012-03-21 11:59:11 -07002101 child.setTranslationX(x);
2102 child.setTranslationY(y);
Adam Cohend024f982012-05-23 18:26:45 -07002103 float s = r * finalScale + (1 - r) * initScale;
Brandon Keely50e6e562012-05-08 16:28:49 -07002104 child.setScaleX(s);
2105 child.setScaleY(s);
Adam Cohen19f37922012-03-21 11:59:11 -07002106 }
2107 });
2108 va.addListener(new AnimatorListenerAdapter() {
2109 public void onAnimationRepeat(Animator animation) {
Adam Cohen19f37922012-03-21 11:59:11 -07002110 // We make sure to end only after a full period
Adam Cohend024f982012-05-23 18:26:45 -07002111 initDeltaX = 0;
2112 initDeltaY = 0;
2113 initScale = 1.0f;
Adam Cohen19f37922012-03-21 11:59:11 -07002114 }
2115 });
Adam Cohen19f37922012-03-21 11:59:11 -07002116 mShakeAnimators.put(child, this);
2117 va.start();
2118 }
2119
Adam Cohend024f982012-05-23 18:26:45 -07002120 private void cancel() {
Adam Cohene7587d22012-05-24 18:50:02 -07002121 if (a != null) {
2122 a.cancel();
2123 }
Adam Cohen19f37922012-03-21 11:59:11 -07002124 }
Adam Cohene7587d22012-05-24 18:50:02 -07002125
Brandon Keely50e6e562012-05-08 16:28:49 -07002126 private void completeAnimationImmediately() {
Adam Cohene7587d22012-05-24 18:50:02 -07002127 if (a != null) {
2128 a.cancel();
2129 }
Brandon Keely50e6e562012-05-08 16:28:49 -07002130
Michael Jurka2ecf9952012-06-18 12:52:28 -07002131 AnimatorSet s = LauncherAnimUtils.createAnimatorSet();
Adam Cohene7587d22012-05-24 18:50:02 -07002132 a = s;
Brandon Keely50e6e562012-05-08 16:28:49 -07002133 s.playTogether(
Michael Jurka2ecf9952012-06-18 12:52:28 -07002134 LauncherAnimUtils.ofFloat(child, "scaleX", 1f),
2135 LauncherAnimUtils.ofFloat(child, "scaleY", 1f),
2136 LauncherAnimUtils.ofFloat(child, "translationX", 0f),
2137 LauncherAnimUtils.ofFloat(child, "translationY", 0f)
Brandon Keely50e6e562012-05-08 16:28:49 -07002138 );
2139 s.setDuration(REORDER_ANIMATION_DURATION);
2140 s.setInterpolator(new android.view.animation.DecelerateInterpolator(1.5f));
2141 s.start();
2142 }
Adam Cohen19f37922012-03-21 11:59:11 -07002143 }
2144
2145 private void completeAndClearReorderHintAnimations() {
2146 for (ReorderHintAnimation a: mShakeAnimators.values()) {
Brandon Keely50e6e562012-05-08 16:28:49 -07002147 a.completeAnimationImmediately();
Adam Cohen19f37922012-03-21 11:59:11 -07002148 }
2149 mShakeAnimators.clear();
2150 }
2151
Adam Cohen482ed822012-03-02 14:15:13 -08002152 private void commitTempPlacement() {
2153 for (int i = 0; i < mCountX; i++) {
2154 for (int j = 0; j < mCountY; j++) {
2155 mOccupied[i][j] = mTmpOccupied[i][j];
2156 }
2157 }
Michael Jurkaa52570f2012-03-20 03:18:20 -07002158 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002159 for (int i = 0; i < childCount; i++) {
Adam Cohenea889a22012-03-27 16:45:39 -07002160 View child = mShortcutsAndWidgets.getChildAt(i);
2161 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2162 ItemInfo info = (ItemInfo) child.getTag();
Adam Cohen2acce882012-03-28 19:03:19 -07002163 // We do a null check here because the item info can be null in the case of the
2164 // AllApps button in the hotseat.
2165 if (info != null) {
Adam Cohen487f7dd2012-06-28 18:12:10 -07002166 if (info.cellX != lp.tmpCellX || info.cellY != lp.tmpCellY ||
2167 info.spanX != lp.cellHSpan || info.spanY != lp.cellVSpan) {
2168 info.requiresDbUpdate = true;
2169 }
Adam Cohen2acce882012-03-28 19:03:19 -07002170 info.cellX = lp.cellX = lp.tmpCellX;
2171 info.cellY = lp.cellY = lp.tmpCellY;
Adam Cohenbebf0422012-04-11 18:06:28 -07002172 info.spanX = lp.cellHSpan;
2173 info.spanY = lp.cellVSpan;
Adam Cohen2acce882012-03-28 19:03:19 -07002174 }
Adam Cohen482ed822012-03-02 14:15:13 -08002175 }
Adam Cohen2acce882012-03-28 19:03:19 -07002176 mLauncher.getWorkspace().updateItemLocationsInDatabase(this);
Adam Cohen482ed822012-03-02 14:15:13 -08002177 }
2178
2179 public void setUseTempCoords(boolean useTempCoords) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002180 int childCount = mShortcutsAndWidgets.getChildCount();
Adam Cohen482ed822012-03-02 14:15:13 -08002181 for (int i = 0; i < childCount; i++) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002182 LayoutParams lp = (LayoutParams) mShortcutsAndWidgets.getChildAt(i).getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002183 lp.useTmpCoords = useTempCoords;
2184 }
2185 }
2186
Adam Cohen482ed822012-03-02 14:15:13 -08002187 ItemConfiguration findConfigurationNoShuffle(int pixelX, int pixelY, int minSpanX, int minSpanY,
2188 int spanX, int spanY, View dragView, ItemConfiguration solution) {
2189 int[] result = new int[2];
2190 int[] resultSpan = new int[2];
2191 findNearestVacantArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, null, result,
2192 resultSpan);
2193 if (result[0] >= 0 && result[1] >= 0) {
2194 copyCurrentStateToSolution(solution, false);
2195 solution.dragViewX = result[0];
2196 solution.dragViewY = result[1];
2197 solution.dragViewSpanX = resultSpan[0];
2198 solution.dragViewSpanY = resultSpan[1];
2199 solution.isSolution = true;
2200 } else {
2201 solution.isSolution = false;
2202 }
2203 return solution;
2204 }
2205
2206 public void prepareChildForDrag(View child) {
2207 markCellsAsUnoccupiedForView(child);
Adam Cohen482ed822012-03-02 14:15:13 -08002208 }
2209
Adam Cohen19f37922012-03-21 11:59:11 -07002210 /* This seems like it should be obvious and straight-forward, but when the direction vector
2211 needs to match with the notion of the dragView pushing other views, we have to employ
2212 a slightly more subtle notion of the direction vector. The question is what two points is
2213 the vector between? The center of the dragView and its desired destination? Not quite, as
2214 this doesn't necessarily coincide with the interaction of the dragView and items occupying
2215 those cells. Instead we use some heuristics to often lock the vector to up, down, left
2216 or right, which helps make pushing feel right.
2217 */
2218 private void getDirectionVectorForDrop(int dragViewCenterX, int dragViewCenterY, int spanX,
2219 int spanY, View dragView, int[] resultDirection) {
2220 int[] targetDestination = new int[2];
2221
2222 findNearestArea(dragViewCenterX, dragViewCenterY, spanX, spanY, targetDestination);
2223 Rect dragRect = new Rect();
2224 regionToRect(targetDestination[0], targetDestination[1], spanX, spanY, dragRect);
2225 dragRect.offset(dragViewCenterX - dragRect.centerX(), dragViewCenterY - dragRect.centerY());
2226
2227 Rect dropRegionRect = new Rect();
2228 getViewsIntersectingRegion(targetDestination[0], targetDestination[1], spanX, spanY,
2229 dragView, dropRegionRect, mIntersectingViews);
2230
2231 int dropRegionSpanX = dropRegionRect.width();
2232 int dropRegionSpanY = dropRegionRect.height();
2233
2234 regionToRect(dropRegionRect.left, dropRegionRect.top, dropRegionRect.width(),
2235 dropRegionRect.height(), dropRegionRect);
2236
2237 int deltaX = (dropRegionRect.centerX() - dragViewCenterX) / spanX;
2238 int deltaY = (dropRegionRect.centerY() - dragViewCenterY) / spanY;
2239
2240 if (dropRegionSpanX == mCountX || spanX == mCountX) {
2241 deltaX = 0;
2242 }
2243 if (dropRegionSpanY == mCountY || spanY == mCountY) {
2244 deltaY = 0;
2245 }
2246
2247 if (deltaX == 0 && deltaY == 0) {
2248 // No idea what to do, give a random direction.
2249 resultDirection[0] = 1;
2250 resultDirection[1] = 0;
2251 } else {
2252 computeDirectionVector(deltaX, deltaY, resultDirection);
2253 }
2254 }
2255
2256 // For a given cell and span, fetch the set of views intersecting the region.
2257 private void getViewsIntersectingRegion(int cellX, int cellY, int spanX, int spanY,
2258 View dragView, Rect boundingRect, ArrayList<View> intersectingViews) {
2259 if (boundingRect != null) {
2260 boundingRect.set(cellX, cellY, cellX + spanX, cellY + spanY);
2261 }
2262 intersectingViews.clear();
2263 Rect r0 = new Rect(cellX, cellY, cellX + spanX, cellY + spanY);
2264 Rect r1 = new Rect();
2265 final int count = mShortcutsAndWidgets.getChildCount();
2266 for (int i = 0; i < count; i++) {
2267 View child = mShortcutsAndWidgets.getChildAt(i);
2268 if (child == dragView) continue;
2269 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2270 r1.set(lp.cellX, lp.cellY, lp.cellX + lp.cellHSpan, lp.cellY + lp.cellVSpan);
2271 if (Rect.intersects(r0, r1)) {
2272 mIntersectingViews.add(child);
2273 if (boundingRect != null) {
2274 boundingRect.union(r1);
2275 }
2276 }
2277 }
2278 }
2279
2280 boolean isNearestDropLocationOccupied(int pixelX, int pixelY, int spanX, int spanY,
2281 View dragView, int[] result) {
2282 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
2283 getViewsIntersectingRegion(result[0], result[1], spanX, spanY, dragView, null,
2284 mIntersectingViews);
2285 return !mIntersectingViews.isEmpty();
2286 }
2287
2288 void revertTempState() {
2289 if (!isItemPlacementDirty() || DESTRUCTIVE_REORDER) return;
2290 final int count = mShortcutsAndWidgets.getChildCount();
2291 for (int i = 0; i < count; i++) {
2292 View child = mShortcutsAndWidgets.getChildAt(i);
2293 LayoutParams lp = (LayoutParams) child.getLayoutParams();
2294 if (lp.tmpCellX != lp.cellX || lp.tmpCellY != lp.cellY) {
2295 lp.tmpCellX = lp.cellX;
2296 lp.tmpCellY = lp.cellY;
2297 animateChildToPosition(child, lp.cellX, lp.cellY, REORDER_ANIMATION_DURATION,
2298 0, false, false);
2299 }
2300 }
2301 completeAndClearReorderHintAnimations();
2302 setItemPlacementDirty(false);
2303 }
2304
Adam Cohenbebf0422012-04-11 18:06:28 -07002305 boolean createAreaForResize(int cellX, int cellY, int spanX, int spanY,
2306 View dragView, int[] direction, boolean commit) {
2307 int[] pixelXY = new int[2];
2308 regionToCenterPoint(cellX, cellY, spanX, spanY, pixelXY);
2309
2310 // First we determine if things have moved enough to cause a different layout
2311 ItemConfiguration swapSolution = simpleSwap(pixelXY[0], pixelXY[1], spanX, spanY,
2312 spanX, spanY, direction, dragView, true, new ItemConfiguration());
2313
2314 setUseTempCoords(true);
2315 if (swapSolution != null && swapSolution.isSolution) {
2316 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2317 // committing anything or animating anything as we just want to determine if a solution
2318 // exists
2319 copySolutionToTempState(swapSolution, dragView);
2320 setItemPlacementDirty(true);
2321 animateItemsToSolution(swapSolution, dragView, commit);
2322
2323 if (commit) {
2324 commitTempPlacement();
2325 completeAndClearReorderHintAnimations();
2326 setItemPlacementDirty(false);
2327 } else {
2328 beginOrAdjustHintAnimations(swapSolution, dragView,
2329 REORDER_ANIMATION_DURATION);
2330 }
2331 mShortcutsAndWidgets.requestLayout();
2332 }
2333 return swapSolution.isSolution;
2334 }
2335
Adam Cohen482ed822012-03-02 14:15:13 -08002336 int[] createArea(int pixelX, int pixelY, int minSpanX, int minSpanY, int spanX, int spanY,
2337 View dragView, int[] result, int resultSpan[], int mode) {
Adam Cohen482ed822012-03-02 14:15:13 -08002338 // First we determine if things have moved enough to cause a different layout
Adam Cohen47a876d2012-03-19 13:21:41 -07002339 result = findNearestArea(pixelX, pixelY, spanX, spanY, result);
Adam Cohen482ed822012-03-02 14:15:13 -08002340
2341 if (resultSpan == null) {
2342 resultSpan = new int[2];
2343 }
2344
Adam Cohen19f37922012-03-21 11:59:11 -07002345 // When we are checking drop validity or actually dropping, we don't recompute the
2346 // direction vector, since we want the solution to match the preview, and it's possible
2347 // that the exact position of the item has changed to result in a new reordering outcome.
Adam Cohenb209e632012-03-27 17:09:36 -07002348 if ((mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL || mode == MODE_ACCEPT_DROP)
2349 && mPreviousReorderDirection[0] != INVALID_DIRECTION) {
Adam Cohen19f37922012-03-21 11:59:11 -07002350 mDirectionVector[0] = mPreviousReorderDirection[0];
2351 mDirectionVector[1] = mPreviousReorderDirection[1];
2352 // We reset this vector after drop
Adam Cohenb209e632012-03-27 17:09:36 -07002353 if (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2354 mPreviousReorderDirection[0] = INVALID_DIRECTION;
2355 mPreviousReorderDirection[1] = INVALID_DIRECTION;
Adam Cohen19f37922012-03-21 11:59:11 -07002356 }
2357 } else {
2358 getDirectionVectorForDrop(pixelX, pixelY, spanX, spanY, dragView, mDirectionVector);
2359 mPreviousReorderDirection[0] = mDirectionVector[0];
2360 mPreviousReorderDirection[1] = mDirectionVector[1];
2361 }
2362
Adam Cohen482ed822012-03-02 14:15:13 -08002363 ItemConfiguration swapSolution = simpleSwap(pixelX, pixelY, minSpanX, minSpanY,
2364 spanX, spanY, mDirectionVector, dragView, true, new ItemConfiguration());
2365
2366 // We attempt the approach which doesn't shuffle views at all
2367 ItemConfiguration noShuffleSolution = findConfigurationNoShuffle(pixelX, pixelY, minSpanX,
2368 minSpanY, spanX, spanY, dragView, new ItemConfiguration());
2369
2370 ItemConfiguration finalSolution = null;
2371 if (swapSolution.isSolution && swapSolution.area() >= noShuffleSolution.area()) {
2372 finalSolution = swapSolution;
2373 } else if (noShuffleSolution.isSolution) {
2374 finalSolution = noShuffleSolution;
2375 }
2376
2377 boolean foundSolution = true;
2378 if (!DESTRUCTIVE_REORDER) {
2379 setUseTempCoords(true);
2380 }
2381
2382 if (finalSolution != null) {
2383 result[0] = finalSolution.dragViewX;
2384 result[1] = finalSolution.dragViewY;
2385 resultSpan[0] = finalSolution.dragViewSpanX;
2386 resultSpan[1] = finalSolution.dragViewSpanY;
2387
2388 // If we're just testing for a possible location (MODE_ACCEPT_DROP), we don't bother
2389 // committing anything or animating anything as we just want to determine if a solution
2390 // exists
2391 if (mode == MODE_DRAG_OVER || mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL) {
2392 if (!DESTRUCTIVE_REORDER) {
2393 copySolutionToTempState(finalSolution, dragView);
2394 }
2395 setItemPlacementDirty(true);
2396 animateItemsToSolution(finalSolution, dragView, mode == MODE_ON_DROP);
2397
Adam Cohen19f37922012-03-21 11:59:11 -07002398 if (!DESTRUCTIVE_REORDER &&
2399 (mode == MODE_ON_DROP || mode == MODE_ON_DROP_EXTERNAL)) {
Adam Cohen482ed822012-03-02 14:15:13 -08002400 commitTempPlacement();
Adam Cohen19f37922012-03-21 11:59:11 -07002401 completeAndClearReorderHintAnimations();
2402 setItemPlacementDirty(false);
2403 } else {
2404 beginOrAdjustHintAnimations(finalSolution, dragView,
2405 REORDER_ANIMATION_DURATION);
Adam Cohen482ed822012-03-02 14:15:13 -08002406 }
2407 }
2408 } else {
2409 foundSolution = false;
2410 result[0] = result[1] = resultSpan[0] = resultSpan[1] = -1;
2411 }
2412
2413 if ((mode == MODE_ON_DROP || !foundSolution) && !DESTRUCTIVE_REORDER) {
2414 setUseTempCoords(false);
2415 }
Adam Cohen482ed822012-03-02 14:15:13 -08002416
Michael Jurkaa52570f2012-03-20 03:18:20 -07002417 mShortcutsAndWidgets.requestLayout();
Adam Cohen482ed822012-03-02 14:15:13 -08002418 return result;
2419 }
2420
Adam Cohen19f37922012-03-21 11:59:11 -07002421 void setItemPlacementDirty(boolean dirty) {
2422 mItemPlacementDirty = dirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002423 }
Adam Cohen19f37922012-03-21 11:59:11 -07002424 boolean isItemPlacementDirty() {
2425 return mItemPlacementDirty;
Adam Cohen482ed822012-03-02 14:15:13 -08002426 }
2427
2428 private class ItemConfiguration {
Adam Cohen8baab352012-03-20 17:39:21 -07002429 HashMap<View, CellAndSpan> map = new HashMap<View, CellAndSpan>();
Adam Cohen482ed822012-03-02 14:15:13 -08002430 boolean isSolution = false;
2431 int dragViewX, dragViewY, dragViewSpanX, dragViewSpanY;
2432
2433 int area() {
2434 return dragViewSpanX * dragViewSpanY;
2435 }
Adam Cohen8baab352012-03-20 17:39:21 -07002436 }
2437
2438 private class CellAndSpan {
2439 int x, y;
2440 int spanX, spanY;
2441
2442 public CellAndSpan(int x, int y, int spanX, int spanY) {
2443 this.x = x;
2444 this.y = y;
2445 this.spanX = spanX;
2446 this.spanY = spanY;
Adam Cohen482ed822012-03-02 14:15:13 -08002447 }
2448 }
2449
Adam Cohendf035382011-04-11 17:22:04 -07002450 /**
2451 * Find a vacant area that will fit the given bounds nearest the requested
2452 * cell location. Uses Euclidean distance to score multiple vacant areas.
2453 *
2454 * @param pixelX The X location at which you want to search for a vacant area.
2455 * @param pixelY The Y location at which you want to search for a vacant area.
2456 * @param spanX Horizontal span of the object.
2457 * @param spanY Vertical span of the object.
2458 * @param ignoreView Considers space occupied by this view as unoccupied
2459 * @param result Previously returned value to possibly recycle.
2460 * @return The X, Y cell of a vacant area that can contain this object,
2461 * nearest the requested location.
2462 */
2463 int[] findNearestVacantArea(
2464 int pixelX, int pixelY, int spanX, int spanY, View ignoreView, int[] result) {
2465 return findNearestArea(pixelX, pixelY, spanX, spanY, ignoreView, true, result);
2466 }
2467
2468 /**
Adam Cohend41fbf52012-02-16 23:53:59 -08002469 * Find a vacant area that will fit the given bounds nearest the requested
2470 * cell location. Uses Euclidean distance to score multiple vacant areas.
2471 *
2472 * @param pixelX The X location at which you want to search for a vacant area.
2473 * @param pixelY The Y location at which you want to search for a vacant area.
2474 * @param minSpanX The minimum horizontal span required
2475 * @param minSpanY The minimum vertical span required
2476 * @param spanX Horizontal span of the object.
2477 * @param spanY Vertical span of the object.
2478 * @param ignoreView Considers space occupied by this view as unoccupied
2479 * @param result Previously returned value to possibly recycle.
2480 * @return The X, Y cell of a vacant area that can contain this object,
2481 * nearest the requested location.
2482 */
2483 int[] findNearestVacantArea(int pixelX, int pixelY, int minSpanX, int minSpanY,
2484 int spanX, int spanY, View ignoreView, int[] result, int[] resultSpan) {
Adam Cohen482ed822012-03-02 14:15:13 -08002485 return findNearestArea(pixelX, pixelY, minSpanX, minSpanY, spanX, spanY, ignoreView, true,
2486 result, resultSpan, mOccupied);
Adam Cohend41fbf52012-02-16 23:53:59 -08002487 }
2488
2489 /**
Adam Cohendf035382011-04-11 17:22:04 -07002490 * Find a starting cell position that will fit the given bounds nearest the requested
2491 * cell location. Uses Euclidean distance to score multiple vacant areas.
2492 *
2493 * @param pixelX The X location at which you want to search for a vacant area.
2494 * @param pixelY The Y location at which you want to search for a vacant area.
2495 * @param spanX Horizontal span of the object.
2496 * @param spanY Vertical span of the object.
2497 * @param ignoreView Considers space occupied by this view as unoccupied
2498 * @param result Previously returned value to possibly recycle.
2499 * @return The X, Y cell of a vacant area that can contain this object,
2500 * nearest the requested location.
2501 */
2502 int[] findNearestArea(
2503 int pixelX, int pixelY, int spanX, int spanY, int[] result) {
2504 return findNearestArea(pixelX, pixelY, spanX, spanY, null, false, result);
2505 }
2506
Michael Jurka0280c3b2010-09-17 15:00:07 -07002507 boolean existsEmptyCell() {
2508 return findCellForSpan(null, 1, 1);
2509 }
2510
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002511 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002512 * Finds the upper-left coordinate of the first rectangle in the grid that can
2513 * hold a cell of the specified dimensions. If intersectX and intersectY are not -1,
2514 * then this method will only return coordinates for rectangles that contain the cell
2515 * (intersectX, intersectY)
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 *
2522 * @return True if a vacant cell of the specified dimension was found, false otherwise.
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002523 */
Michael Jurka0280c3b2010-09-17 15:00:07 -07002524 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Adam Cohen482ed822012-03-02 14:15:13 -08002525 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002526 }
2527
2528 /**
2529 * Like above, but ignores any cells occupied by the item "ignoreView"
2530 *
2531 * @param cellXY The array that will contain the position of a vacant cell if such a cell
2532 * can be found.
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 * @return
2537 */
2538 boolean findCellForSpanIgnoring(int[] cellXY, int spanX, int spanY, View ignoreView) {
Adam Cohen482ed822012-03-02 14:15:13 -08002539 return findCellForSpanThatIntersectsIgnoring(cellXY, spanX, spanY, -1, -1,
2540 ignoreView, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002541 }
2542
2543 /**
2544 * Like above, but if intersectX and intersectY are not -1, then this method will try to
2545 * return coordinates for rectangles that contain the cell [intersectX, intersectY]
2546 *
2547 * @param spanX The horizontal span of the cell we want to find.
2548 * @param spanY The vertical span of the cell we want to find.
2549 * @param ignoreView The home screen item we should treat as not occupying any space
2550 * @param intersectX The X coordinate of the cell that we should try to overlap
2551 * @param intersectX The Y coordinate of the cell that we should try to overlap
2552 *
2553 * @return True if a vacant cell of the specified dimension was found, false otherwise.
2554 */
2555 boolean findCellForSpanThatIntersects(int[] cellXY, int spanX, int spanY,
2556 int intersectX, int intersectY) {
2557 return findCellForSpanThatIntersectsIgnoring(
Adam Cohen482ed822012-03-02 14:15:13 -08002558 cellXY, spanX, spanY, intersectX, intersectY, null, mOccupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002559 }
2560
2561 /**
2562 * The superset of the above two methods
2563 */
2564 boolean findCellForSpanThatIntersectsIgnoring(int[] cellXY, int spanX, int spanY,
Adam Cohen482ed822012-03-02 14:15:13 -08002565 int intersectX, int intersectY, View ignoreView, boolean occupied[][]) {
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002566 // mark space take by ignoreView as available (method checks if ignoreView is null)
Adam Cohen482ed822012-03-02 14:15:13 -08002567 markCellsAsUnoccupiedForView(ignoreView, occupied);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002568
Michael Jurka28750fb2010-09-24 17:43:49 -07002569 boolean foundCell = false;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002570 while (true) {
2571 int startX = 0;
2572 if (intersectX >= 0) {
2573 startX = Math.max(startX, intersectX - (spanX - 1));
2574 }
2575 int endX = mCountX - (spanX - 1);
2576 if (intersectX >= 0) {
2577 endX = Math.min(endX, intersectX + (spanX - 1) + (spanX == 1 ? 1 : 0));
2578 }
2579 int startY = 0;
2580 if (intersectY >= 0) {
2581 startY = Math.max(startY, intersectY - (spanY - 1));
2582 }
2583 int endY = mCountY - (spanY - 1);
2584 if (intersectY >= 0) {
2585 endY = Math.min(endY, intersectY + (spanY - 1) + (spanY == 1 ? 1 : 0));
2586 }
2587
Winson Chungbbc60d82010-11-11 16:34:41 -08002588 for (int y = startY; y < endY && !foundCell; y++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002589 inner:
Winson Chungbbc60d82010-11-11 16:34:41 -08002590 for (int x = startX; x < endX; x++) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002591 for (int i = 0; i < spanX; i++) {
2592 for (int j = 0; j < spanY; j++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002593 if (occupied[x + i][y + j]) {
Winson Chungbbc60d82010-11-11 16:34:41 -08002594 // small optimization: we can skip to after the column we just found
Michael Jurka0280c3b2010-09-17 15:00:07 -07002595 // an occupied cell
Winson Chungbbc60d82010-11-11 16:34:41 -08002596 x += i;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002597 continue inner;
2598 }
2599 }
2600 }
2601 if (cellXY != null) {
2602 cellXY[0] = x;
2603 cellXY[1] = y;
2604 }
Michael Jurka28750fb2010-09-24 17:43:49 -07002605 foundCell = true;
2606 break;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002607 }
2608 }
2609 if (intersectX == -1 && intersectY == -1) {
2610 break;
2611 } else {
2612 // if we failed to find anything, try again but without any requirements of
2613 // intersecting
2614 intersectX = -1;
2615 intersectY = -1;
2616 continue;
2617 }
2618 }
2619
Michael Jurkac6ee42e2010-09-30 12:04:50 -07002620 // re-mark space taken by ignoreView as occupied
Adam Cohen482ed822012-03-02 14:15:13 -08002621 markCellsAsOccupiedForView(ignoreView, occupied);
Michael Jurka28750fb2010-09-24 17:43:49 -07002622 return foundCell;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002623 }
2624
2625 /**
Winson Chungc07918d2011-07-01 15:35:26 -07002626 * A drag event has begun over this layout.
2627 * It may have begun over this layout (in which case onDragChild is called first),
2628 * or it may have begun on another layout.
2629 */
2630 void onDragEnter() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002631 mDragEnforcer.onDragEnter();
Winson Chungc07918d2011-07-01 15:35:26 -07002632 mDragging = true;
2633 }
2634
2635 /**
Michael Jurka0280c3b2010-09-17 15:00:07 -07002636 * Called when drag has left this CellLayout or has been completed (successfully or not)
2637 */
2638 void onDragExit() {
Adam Cohenc6cc61d2012-04-04 12:47:08 -07002639 mDragEnforcer.onDragExit();
Joe Onorato4be866d2010-10-10 11:26:02 -07002640 // This can actually be called when we aren't in a drag, e.g. when adding a new
2641 // item to this layout via the customize drawer.
2642 // Guard against that case.
2643 if (mDragging) {
2644 mDragging = false;
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002645 }
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002646
2647 // Invalidate the drag data
Adam Cohend41fbf52012-02-16 23:53:59 -08002648 mDragCell[0] = mDragCell[1] = -1;
Patrick Dubroy08ae2ec2010-10-14 23:54:22 -07002649 mDragOutlineAnims[mDragOutlineCurrent].animateOut();
2650 mDragOutlineCurrent = (mDragOutlineCurrent + 1) % mDragOutlineAnims.length;
Adam Cohen19f37922012-03-21 11:59:11 -07002651 revertTempState();
Michael Jurka33945b22010-12-21 18:19:38 -08002652 setIsDragOverlapping(false);
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002653 }
2654
2655 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002656 * Mark a child as having been dropped.
Patrick Dubroyde7658b2010-09-27 11:15:43 -07002657 * At the beginning of the drag operation, the child may have been on another
Patrick Dubroyce34a972010-10-19 10:34:32 -07002658 * screen, but it is re-parented before this method is called.
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002659 *
2660 * @param child The child that is being dropped
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002661 */
Adam Cohen716b51e2011-06-30 12:09:54 -07002662 void onDropChild(View child) {
Romain Guyd94533d2009-08-17 10:01:15 -07002663 if (child != null) {
2664 LayoutParams lp = (LayoutParams) child.getLayoutParams();
Romain Guy84f296c2009-11-04 15:00:44 -08002665 lp.dropped = true;
Romain Guyd94533d2009-08-17 10:01:15 -07002666 child.requestLayout();
Romain Guyd94533d2009-08-17 10:01:15 -07002667 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002668 }
2669
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002670 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002671 * Computes a bounding rectangle for a range of cells
Winson Chungaafa03c2010-06-11 17:34:16 -07002672 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002673 * @param cellX X coordinate of upper left corner expressed as a cell position
2674 * @param cellY Y coordinate of upper left corner expressed as a cell position
Winson Chungaafa03c2010-06-11 17:34:16 -07002675 * @param cellHSpan Width in cells
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002676 * @param cellVSpan Height in cells
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002677 * @param resultRect Rect into which to put the results
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002678 */
Adam Cohend41fbf52012-02-16 23:53:59 -08002679 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, Rect resultRect) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002680 final int cellWidth = mCellWidth;
2681 final int cellHeight = mCellHeight;
2682 final int widthGap = mWidthGap;
2683 final int heightGap = mHeightGap;
Winson Chungaafa03c2010-06-11 17:34:16 -07002684
Winson Chung4b825dcd2011-06-19 12:41:22 -07002685 final int hStartPadding = getPaddingLeft();
2686 final int vStartPadding = getPaddingTop();
Winson Chungaafa03c2010-06-11 17:34:16 -07002687
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002688 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
2689 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
2690
2691 int x = hStartPadding + cellX * (cellWidth + widthGap);
2692 int y = vStartPadding + cellY * (cellHeight + heightGap);
Winson Chungaafa03c2010-06-11 17:34:16 -07002693
Patrick Dubroy6569f2c2010-07-12 14:25:18 -07002694 resultRect.set(x, y, x + width, y + height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002695 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002696
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002697 /**
Winson Chungaafa03c2010-06-11 17:34:16 -07002698 * Computes the required horizontal and vertical cell spans to always
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002699 * fit the given rectangle.
Winson Chungaafa03c2010-06-11 17:34:16 -07002700 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002701 * @param width Width in pixels
2702 * @param height Height in pixels
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002703 * @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 -08002704 */
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002705 public int[] rectToCell(int width, int height, int[] result) {
Michael Jurka9987a5c2010-10-08 16:58:12 -07002706 return rectToCell(getResources(), width, height, result);
2707 }
2708
2709 public static int[] rectToCell(Resources resources, int width, int height, int[] result) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002710 // Always assume we're working with the smallest span to make sure we
2711 // reserve enough space in both orientations.
Joe Onorato79e56262009-09-21 15:23:04 -04002712 int actualWidth = resources.getDimensionPixelSize(R.dimen.workspace_cell_width);
2713 int actualHeight = resources.getDimensionPixelSize(R.dimen.workspace_cell_height);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002714 int smallerSize = Math.min(actualWidth, actualHeight);
Joe Onorato79e56262009-09-21 15:23:04 -04002715
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002716 // Always round up to next largest cell
Winson Chung54c725c2011-08-03 12:03:40 -07002717 int spanX = (int) Math.ceil(width / (float) smallerSize);
2718 int spanY = (int) Math.ceil(height / (float) smallerSize);
Joe Onorato79e56262009-09-21 15:23:04 -04002719
Patrick Dubroy8f86ddc2010-07-16 13:55:32 -07002720 if (result == null) {
2721 return new int[] { spanX, spanY };
2722 }
2723 result[0] = spanX;
2724 result[1] = spanY;
2725 return result;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002726 }
2727
Michael Jurkaf12c75c2011-01-25 22:41:40 -08002728 public int[] cellSpansToSize(int hSpans, int vSpans) {
2729 int[] size = new int[2];
2730 size[0] = hSpans * mCellWidth + (hSpans - 1) * mWidthGap;
2731 size[1] = vSpans * mCellHeight + (vSpans - 1) * mHeightGap;
2732 return size;
2733 }
2734
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002735 /**
Patrick Dubroy047379a2010-12-19 22:02:04 -08002736 * Calculate the grid spans needed to fit given item
2737 */
2738 public void calculateSpans(ItemInfo info) {
2739 final int minWidth;
2740 final int minHeight;
2741
2742 if (info instanceof LauncherAppWidgetInfo) {
2743 minWidth = ((LauncherAppWidgetInfo) info).minWidth;
2744 minHeight = ((LauncherAppWidgetInfo) info).minHeight;
2745 } else if (info instanceof PendingAddWidgetInfo) {
2746 minWidth = ((PendingAddWidgetInfo) info).minWidth;
2747 minHeight = ((PendingAddWidgetInfo) info).minHeight;
2748 } else {
2749 // It's not a widget, so it must be 1x1
2750 info.spanX = info.spanY = 1;
2751 return;
2752 }
2753 int[] spans = rectToCell(minWidth, minHeight, null);
2754 info.spanX = spans[0];
2755 info.spanY = spans[1];
2756 }
2757
2758 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002759 * Find the first vacant cell, if there is one.
2760 *
2761 * @param vacant Holds the x and y coordinate of the vacant cell
2762 * @param spanX Horizontal cell span.
2763 * @param spanY Vertical cell span.
Winson Chungaafa03c2010-06-11 17:34:16 -07002764 *
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002765 * @return True if a vacant cell was found
2766 */
2767 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002768
Michael Jurka0280c3b2010-09-17 15:00:07 -07002769 return findVacantCell(vacant, spanX, spanY, mCountX, mCountY, mOccupied);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002770 }
2771
2772 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
2773 int xCount, int yCount, boolean[][] occupied) {
2774
Adam Cohen2801caf2011-05-13 20:57:39 -07002775 for (int y = 0; y < yCount; y++) {
2776 for (int x = 0; x < xCount; x++) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002777 boolean available = !occupied[x][y];
2778out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
2779 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
2780 available = available && !occupied[i][j];
2781 if (!available) break out;
2782 }
2783 }
2784
2785 if (available) {
2786 vacant[0] = x;
2787 vacant[1] = y;
2788 return true;
2789 }
2790 }
2791 }
2792
2793 return false;
2794 }
2795
Michael Jurka0280c3b2010-09-17 15:00:07 -07002796 private void clearOccupiedCells() {
2797 for (int x = 0; x < mCountX; x++) {
2798 for (int y = 0; y < mCountY; y++) {
2799 mOccupied[x][y] = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002800 }
2801 }
Michael Jurka0280c3b2010-09-17 15:00:07 -07002802 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002803
Adam Cohend41fbf52012-02-16 23:53:59 -08002804 public void onMove(View view, int newCellX, int newCellY, int newSpanX, int newSpanY) {
Michael Jurka0280c3b2010-09-17 15:00:07 -07002805 markCellsAsUnoccupiedForView(view);
Adam Cohen482ed822012-03-02 14:15:13 -08002806 markCellsForView(newCellX, newCellY, newSpanX, newSpanY, mOccupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002807 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002808
Adam Cohend4844c32011-02-18 19:25:06 -08002809 public void markCellsAsOccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002810 markCellsAsOccupiedForView(view, mOccupied);
2811 }
2812 public void markCellsAsOccupiedForView(View view, boolean[][] occupied) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002813 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002814 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002815 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, true);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002816 }
2817
Adam Cohend4844c32011-02-18 19:25:06 -08002818 public void markCellsAsUnoccupiedForView(View view) {
Adam Cohen482ed822012-03-02 14:15:13 -08002819 markCellsAsUnoccupiedForView(view, mOccupied);
2820 }
2821 public void markCellsAsUnoccupiedForView(View view, boolean occupied[][]) {
Michael Jurkaa52570f2012-03-20 03:18:20 -07002822 if (view == null || view.getParent() != mShortcutsAndWidgets) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002823 LayoutParams lp = (LayoutParams) view.getLayoutParams();
Adam Cohen482ed822012-03-02 14:15:13 -08002824 markCellsForView(lp.cellX, lp.cellY, lp.cellHSpan, lp.cellVSpan, occupied, false);
Michael Jurka0280c3b2010-09-17 15:00:07 -07002825 }
2826
Adam Cohen482ed822012-03-02 14:15:13 -08002827 private void markCellsForView(int cellX, int cellY, int spanX, int spanY, boolean[][] occupied,
2828 boolean value) {
2829 if (cellX < 0 || cellY < 0) return;
Michael Jurka0280c3b2010-09-17 15:00:07 -07002830 for (int x = cellX; x < cellX + spanX && x < mCountX; x++) {
2831 for (int y = cellY; y < cellY + spanY && y < mCountY; y++) {
Adam Cohen482ed822012-03-02 14:15:13 -08002832 occupied[x][y] = value;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002833 }
2834 }
2835 }
2836
Adam Cohen2801caf2011-05-13 20:57:39 -07002837 public int getDesiredWidth() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002838 return getPaddingLeft() + getPaddingRight() + (mCountX * mCellWidth) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002839 (Math.max((mCountX - 1), 0) * mWidthGap);
2840 }
2841
2842 public int getDesiredHeight() {
Michael Jurka8b805b12012-04-18 14:23:14 -07002843 return getPaddingTop() + getPaddingBottom() + (mCountY * mCellHeight) +
Adam Cohen2801caf2011-05-13 20:57:39 -07002844 (Math.max((mCountY - 1), 0) * mHeightGap);
2845 }
2846
Michael Jurka66d72172011-04-12 16:29:25 -07002847 public boolean isOccupied(int x, int y) {
2848 if (x < mCountX && y < mCountY) {
2849 return mOccupied[x][y];
2850 } else {
2851 throw new RuntimeException("Position exceeds the bound of this CellLayout");
2852 }
2853 }
2854
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002855 @Override
2856 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
2857 return new CellLayout.LayoutParams(getContext(), attrs);
2858 }
2859
2860 @Override
2861 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2862 return p instanceof CellLayout.LayoutParams;
2863 }
2864
2865 @Override
2866 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
2867 return new CellLayout.LayoutParams(p);
2868 }
2869
Winson Chungaafa03c2010-06-11 17:34:16 -07002870 public static class CellLayoutAnimationController extends LayoutAnimationController {
2871 public CellLayoutAnimationController(Animation animation, float delay) {
2872 super(animation, delay);
2873 }
2874
2875 @Override
2876 protected long getDelayForView(View view) {
2877 return (int) (Math.random() * 150);
2878 }
2879 }
2880
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002881 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
2882 /**
2883 * Horizontal location of the item in the grid.
2884 */
2885 @ViewDebug.ExportedProperty
2886 public int cellX;
2887
2888 /**
2889 * Vertical location of the item in the grid.
2890 */
2891 @ViewDebug.ExportedProperty
2892 public int cellY;
2893
2894 /**
Adam Cohen482ed822012-03-02 14:15:13 -08002895 * Temporary horizontal location of the item in the grid during reorder
2896 */
2897 public int tmpCellX;
2898
2899 /**
2900 * Temporary vertical location of the item in the grid during reorder
2901 */
2902 public int tmpCellY;
2903
2904 /**
2905 * Indicates that the temporary coordinates should be used to layout the items
2906 */
2907 public boolean useTmpCoords;
2908
2909 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002910 * Number of cells spanned horizontally by the item.
2911 */
2912 @ViewDebug.ExportedProperty
2913 public int cellHSpan;
2914
2915 /**
2916 * Number of cells spanned vertically by the item.
2917 */
2918 @ViewDebug.ExportedProperty
2919 public int cellVSpan;
Winson Chungaafa03c2010-06-11 17:34:16 -07002920
Adam Cohen1b607ed2011-03-03 17:26:50 -08002921 /**
2922 * Indicates whether the item will set its x, y, width and height parameters freely,
2923 * or whether these will be computed based on cellX, cellY, cellHSpan and cellVSpan.
2924 */
Adam Cohend4844c32011-02-18 19:25:06 -08002925 public boolean isLockedToGrid = true;
2926
Adam Cohen482ed822012-03-02 14:15:13 -08002927 /**
2928 * Indicates whether this item can be reordered. Always true except in the case of the
2929 * the AllApps button.
2930 */
2931 public boolean canReorder = true;
2932
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002933 // X coordinate of the view in the layout.
2934 @ViewDebug.ExportedProperty
2935 int x;
2936 // Y coordinate of the view in the layout.
2937 @ViewDebug.ExportedProperty
2938 int y;
2939
Romain Guy84f296c2009-11-04 15:00:44 -08002940 boolean dropped;
Romain Guyfcb9e712009-10-02 16:06:52 -07002941
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002942 public LayoutParams(Context c, AttributeSet attrs) {
2943 super(c, attrs);
2944 cellHSpan = 1;
2945 cellVSpan = 1;
2946 }
2947
2948 public LayoutParams(ViewGroup.LayoutParams source) {
2949 super(source);
2950 cellHSpan = 1;
2951 cellVSpan = 1;
2952 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002953
2954 public LayoutParams(LayoutParams source) {
2955 super(source);
2956 this.cellX = source.cellX;
2957 this.cellY = source.cellY;
2958 this.cellHSpan = source.cellHSpan;
2959 this.cellVSpan = source.cellVSpan;
2960 }
2961
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002962 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
Romain Guy8f19cdd2010-01-08 15:07:00 -08002963 super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002964 this.cellX = cellX;
2965 this.cellY = cellY;
2966 this.cellHSpan = cellHSpan;
2967 this.cellVSpan = cellVSpan;
2968 }
2969
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002970 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap) {
Adam Cohend4844c32011-02-18 19:25:06 -08002971 if (isLockedToGrid) {
2972 final int myCellHSpan = cellHSpan;
2973 final int myCellVSpan = cellVSpan;
Adam Cohen482ed822012-03-02 14:15:13 -08002974 final int myCellX = useTmpCoords ? tmpCellX : cellX;
2975 final int myCellY = useTmpCoords ? tmpCellY : cellY;
Adam Cohen1b607ed2011-03-03 17:26:50 -08002976
Adam Cohend4844c32011-02-18 19:25:06 -08002977 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
2978 leftMargin - rightMargin;
2979 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
2980 topMargin - bottomMargin;
Winson Chungeecf02d2012-03-02 17:14:58 -08002981 x = (int) (myCellX * (cellWidth + widthGap) + leftMargin);
2982 y = (int) (myCellY * (cellHeight + heightGap) + topMargin);
Adam Cohend4844c32011-02-18 19:25:06 -08002983 }
2984 }
Winson Chungaafa03c2010-06-11 17:34:16 -07002985
Winson Chungaafa03c2010-06-11 17:34:16 -07002986 public String toString() {
2987 return "(" + this.cellX + ", " + this.cellY + ")";
2988 }
Adam Cohen7f4eabe2011-04-21 16:19:16 -07002989
2990 public void setWidth(int width) {
2991 this.width = width;
2992 }
2993
2994 public int getWidth() {
2995 return width;
2996 }
2997
2998 public void setHeight(int height) {
2999 this.height = height;
3000 }
3001
3002 public int getHeight() {
3003 return height;
3004 }
3005
3006 public void setX(int x) {
3007 this.x = x;
3008 }
3009
3010 public int getX() {
3011 return x;
3012 }
3013
3014 public void setY(int y) {
3015 this.y = y;
3016 }
3017
3018 public int getY() {
3019 return y;
3020 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003021 }
3022
Michael Jurka0280c3b2010-09-17 15:00:07 -07003023 // This class stores info for two purposes:
3024 // 1. When dragging items (mDragInfo in Workspace), we store the View, its cellX & cellY,
3025 // its spanX, spanY, and the screen it is on
3026 // 2. When long clicking on an empty cell in a CellLayout, we save information about the
3027 // cellX and cellY coordinates and which page was clicked. We then set this as a tag on
3028 // the CellLayout that was long clicked
Michael Jurkae5fb0f22011-04-11 13:27:46 -07003029 static final class CellInfo {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003030 View cell;
Michael Jurkaa63c4522010-08-19 13:52:27 -07003031 int cellX = -1;
3032 int cellY = -1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003033 int spanX;
3034 int spanY;
3035 int screen;
Winson Chung3d503fb2011-07-13 17:25:49 -07003036 long container;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003037
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003038 @Override
3039 public String toString() {
Winson Chungaafa03c2010-06-11 17:34:16 -07003040 return "Cell[view=" + (cell == null ? "null" : cell.getClass())
3041 + ", x=" + cellX + ", y=" + cellY + "]";
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003042 }
3043 }
Michael Jurkad771c962011-08-09 15:00:48 -07003044
3045 public boolean lastDownOnOccupiedCell() {
3046 return mLastDownOnOccupiedCell;
3047 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08003048}