blob: b8d44a150440c95a88e717db02f565a5f9ea16a0 [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
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.graphics.Rect;
22import android.graphics.RectF;
23import android.util.AttributeSet;
24import android.view.ContextMenu;
25import android.view.MotionEvent;
26import android.view.View;
27import android.view.ViewDebug;
28import android.view.ViewGroup;
29
30import java.util.ArrayList;
31
32public class CellLayout extends ViewGroup {
33 private boolean mPortrait;
34
35 private int mCellWidth;
36 private int mCellHeight;
37
38 private int mLongAxisStartPadding;
39 private int mLongAxisEndPadding;
40
41 private int mShortAxisStartPadding;
42 private int mShortAxisEndPadding;
43
44 private int mShortAxisCells;
45 private int mLongAxisCells;
46
47 private int mWidthGap;
48 private int mHeightGap;
49
50 private final Rect mRect = new Rect();
51 private final CellInfo mCellInfo = new CellInfo();
52
53 int[] mCellXY = new int[2];
54
55 boolean[][] mOccupied;
56
57 private RectF mDragRect = new RectF();
58
59 private boolean mDirtyTag;
60
61 public CellLayout(Context context) {
62 this(context, null);
63 }
64
65 public CellLayout(Context context, AttributeSet attrs) {
66 this(context, attrs, 0);
67 }
68
69 public CellLayout(Context context, AttributeSet attrs, int defStyle) {
70 super(context, attrs, defStyle);
71 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CellLayout, defStyle, 0);
72
73 mCellWidth = a.getDimensionPixelSize(R.styleable.CellLayout_cellWidth, 10);
74 mCellHeight = a.getDimensionPixelSize(R.styleable.CellLayout_cellHeight, 10);
75
76 mLongAxisStartPadding =
77 a.getDimensionPixelSize(R.styleable.CellLayout_longAxisStartPadding, 10);
78 mLongAxisEndPadding =
79 a.getDimensionPixelSize(R.styleable.CellLayout_longAxisEndPadding, 10);
80 mShortAxisStartPadding =
81 a.getDimensionPixelSize(R.styleable.CellLayout_shortAxisStartPadding, 10);
82 mShortAxisEndPadding =
83 a.getDimensionPixelSize(R.styleable.CellLayout_shortAxisEndPadding, 10);
84
85 mShortAxisCells = a.getInt(R.styleable.CellLayout_shortAxisCells, 4);
86 mLongAxisCells = a.getInt(R.styleable.CellLayout_longAxisCells, 4);
87
88 a.recycle();
89
90 setAlwaysDrawnWithCacheEnabled(false);
91
92 if (mOccupied == null) {
93 if (mPortrait) {
94 mOccupied = new boolean[mShortAxisCells][mLongAxisCells];
95 } else {
96 mOccupied = new boolean[mLongAxisCells][mShortAxisCells];
97 }
98 }
99 }
100
Jeff Sharkey83f111d2009-04-20 21:03:13 -0700101 @Override
102 public void cancelLongPress() {
103 super.cancelLongPress();
104
105 // Cancel long press for all children
106 final int count = getChildCount();
107 for (int i = 0; i < count; i++) {
108 final View child = getChildAt(i);
109 child.cancelLongPress();
110 }
111 }
112
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113 int getCountX() {
114 return mPortrait ? mShortAxisCells : mLongAxisCells;
115 }
116
117 int getCountY() {
118 return mPortrait ? mLongAxisCells : mShortAxisCells;
119 }
120
121 @Override
122 public void addView(View child, int index, ViewGroup.LayoutParams params) {
123 // Generate an id for each view, this assumes we have at most 256x256 cells
124 // per workspace screen
125 final LayoutParams cellParams = (LayoutParams) params;
126 child.setId(((getId() & 0xFF) << 16) |
127 (cellParams.cellX & 0xFF) << 8 | (cellParams.cellY & 0xFF));
128
129 super.addView(child, index, params);
130 }
131
132 @Override
133 public void requestChildFocus(View child, View focused) {
134 super.requestChildFocus(child, focused);
135 if (child != null) {
136 Rect r = new Rect();
137 child.getDrawingRect(r);
138 requestRectangleOnScreen(r);
139 }
140 }
141
142 @Override
143 protected void onAttachedToWindow() {
144 super.onAttachedToWindow();
145 mCellInfo.screen = ((ViewGroup) getParent()).indexOfChild(this);
146 }
147
148 @Override
149 public boolean onInterceptTouchEvent(MotionEvent ev) {
150 final int action = ev.getAction();
151 final CellInfo cellInfo = mCellInfo;
152
153 if (action == MotionEvent.ACTION_DOWN) {
154 final Rect frame = mRect;
155 final int x = (int) ev.getX() + mScrollX;
156 final int y = (int) ev.getY() + mScrollY;
157 final int count = getChildCount();
158
159 boolean found = false;
160 for (int i = count - 1; i >= 0; i--) {
161 final View child = getChildAt(i);
162
163 if ((child.getVisibility()) == VISIBLE || child.getAnimation() != null) {
164 child.getHitRect(frame);
165 if (frame.contains(x, y)) {
166 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
167 cellInfo.cell = child;
168 cellInfo.cellX = lp.cellX;
169 cellInfo.cellY = lp.cellY;
170 cellInfo.spanX = lp.cellHSpan;
171 cellInfo.spanY = lp.cellVSpan;
172 cellInfo.valid = true;
173 found = true;
174 mDirtyTag = false;
175 break;
176 }
177 }
178 }
179
180 if (!found) {
181 int cellXY[] = mCellXY;
182 pointToCellExact(x, y, cellXY);
183
184 final boolean portrait = mPortrait;
185 final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
186 final int yCount = portrait ? mLongAxisCells : mShortAxisCells;
187
188 final boolean[][] occupied = mOccupied;
Jeff Sharkey70864282009-04-07 21:08:40 -0700189 findOccupiedCells(xCount, yCount, occupied, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800190
191 cellInfo.cell = null;
192 cellInfo.cellX = cellXY[0];
193 cellInfo.cellY = cellXY[1];
194 cellInfo.spanX = 1;
195 cellInfo.spanY = 1;
196 cellInfo.valid = cellXY[0] >= 0 && cellXY[1] >= 0 && cellXY[0] < xCount &&
197 cellXY[1] < yCount && !occupied[cellXY[0]][cellXY[1]];
198
199 // Instead of finding the interesting vacant cells here, wait until a
200 // caller invokes getTag() to retrieve the result. Finding the vacant
201 // cells is a bit expensive and can generate many new objects, it's
202 // therefore better to defer it until we know we actually need it.
203
204 mDirtyTag = true;
205 }
206 setTag(cellInfo);
207 } else if (action == MotionEvent.ACTION_UP) {
208 cellInfo.cell = null;
209 cellInfo.cellX = -1;
210 cellInfo.cellY = -1;
211 cellInfo.spanX = 0;
212 cellInfo.spanY = 0;
213 cellInfo.valid = false;
214 mDirtyTag = false;
215 setTag(cellInfo);
216 }
217
218 return false;
219 }
220
221 @Override
222 public CellInfo getTag() {
223 final CellInfo info = (CellInfo) super.getTag();
224 if (mDirtyTag && info.valid) {
225 final boolean portrait = mPortrait;
226 final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
227 final int yCount = portrait ? mLongAxisCells : mShortAxisCells;
228
229 final boolean[][] occupied = mOccupied;
Jeff Sharkey70864282009-04-07 21:08:40 -0700230 findOccupiedCells(xCount, yCount, occupied, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800231
232 findIntersectingVacantCells(info, info.cellX, info.cellY, xCount, yCount, occupied);
233
234 mDirtyTag = false;
235 }
236 return info;
237 }
238
239 private static void findIntersectingVacantCells(CellInfo cellInfo, int x, int y,
240 int xCount, int yCount, boolean[][] occupied) {
241
242 cellInfo.maxVacantSpanX = Integer.MIN_VALUE;
243 cellInfo.maxVacantSpanXSpanY = Integer.MIN_VALUE;
244 cellInfo.maxVacantSpanY = Integer.MIN_VALUE;
245 cellInfo.maxVacantSpanYSpanX = Integer.MIN_VALUE;
246 cellInfo.clearVacantCells();
247
248 if (occupied[x][y]) {
249 return;
250 }
251
252 cellInfo.current.set(x, y, x, y);
253
254 findVacantCell(cellInfo.current, xCount, yCount, occupied, cellInfo);
255 }
256
257 private static void findVacantCell(Rect current, int xCount, int yCount, boolean[][] occupied,
258 CellInfo cellInfo) {
259
260 addVacantCell(current, cellInfo);
261
262 if (current.left > 0) {
263 if (isColumnEmpty(current.left - 1, current.top, current.bottom, occupied)) {
264 current.left--;
265 findVacantCell(current, xCount, yCount, occupied, cellInfo);
266 current.left++;
267 }
268 }
269
270 if (current.right < xCount - 1) {
271 if (isColumnEmpty(current.right + 1, current.top, current.bottom, occupied)) {
272 current.right++;
273 findVacantCell(current, xCount, yCount, occupied, cellInfo);
274 current.right--;
275 }
276 }
277
278 if (current.top > 0) {
279 if (isRowEmpty(current.top - 1, current.left, current.right, occupied)) {
280 current.top--;
281 findVacantCell(current, xCount, yCount, occupied, cellInfo);
282 current.top++;
283 }
284 }
285
286 if (current.bottom < yCount - 1) {
287 if (isRowEmpty(current.bottom + 1, current.left, current.right, occupied)) {
288 current.bottom++;
289 findVacantCell(current, xCount, yCount, occupied, cellInfo);
290 current.bottom--;
291 }
292 }
293 }
294
295 private static void addVacantCell(Rect current, CellInfo cellInfo) {
296 CellInfo.VacantCell cell = CellInfo.VacantCell.acquire();
297 cell.cellX = current.left;
298 cell.cellY = current.top;
299 cell.spanX = current.right - current.left + 1;
300 cell.spanY = current.bottom - current.top + 1;
301 if (cell.spanX > cellInfo.maxVacantSpanX) {
302 cellInfo.maxVacantSpanX = cell.spanX;
303 cellInfo.maxVacantSpanXSpanY = cell.spanY;
304 }
305 if (cell.spanY > cellInfo.maxVacantSpanY) {
306 cellInfo.maxVacantSpanY = cell.spanY;
307 cellInfo.maxVacantSpanYSpanX = cell.spanX;
308 }
309 cellInfo.vacantCells.add(cell);
310 }
311
312 private static boolean isColumnEmpty(int x, int top, int bottom, boolean[][] occupied) {
313 for (int y = top; y <= bottom; y++) {
314 if (occupied[x][y]) {
315 return false;
316 }
317 }
318 return true;
319 }
320
321 private static boolean isRowEmpty(int y, int left, int right, boolean[][] occupied) {
322 for (int x = left; x <= right; x++) {
323 if (occupied[x][y]) {
324 return false;
325 }
326 }
327 return true;
328 }
329
Jeff Sharkey70864282009-04-07 21:08:40 -0700330 CellInfo findAllVacantCells(boolean[] occupiedCells, View ignoreView) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 final boolean portrait = mPortrait;
332 final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
333 final int yCount = portrait ? mLongAxisCells : mShortAxisCells;
334
335 boolean[][] occupied = mOccupied;
336
337 if (occupiedCells != null) {
338 for (int y = 0; y < yCount; y++) {
339 for (int x = 0; x < xCount; x++) {
340 occupied[x][y] = occupiedCells[y * xCount + x];
341 }
342 }
343 } else {
Jeff Sharkey70864282009-04-07 21:08:40 -0700344 findOccupiedCells(xCount, yCount, occupied, ignoreView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 }
346
347 CellInfo cellInfo = new CellInfo();
348
349 cellInfo.cellX = -1;
350 cellInfo.cellY = -1;
351 cellInfo.spanY = 0;
352 cellInfo.spanX = 0;
353 cellInfo.maxVacantSpanX = Integer.MIN_VALUE;
354 cellInfo.maxVacantSpanXSpanY = Integer.MIN_VALUE;
355 cellInfo.maxVacantSpanY = Integer.MIN_VALUE;
356 cellInfo.maxVacantSpanYSpanX = Integer.MIN_VALUE;
357 cellInfo.screen = mCellInfo.screen;
358
359 Rect current = cellInfo.current;
360
361 for (int x = 0; x < xCount; x++) {
362 for (int y = 0; y < yCount; y++) {
363 if (!occupied[x][y]) {
364 current.set(x, y, x, y);
365 findVacantCell(current, xCount, yCount, occupied, cellInfo);
366 occupied[x][y] = true;
367 }
368 }
369 }
370
371 cellInfo.valid = cellInfo.vacantCells.size() > 0;
372
373 // Assume the caller will perform their own cell searching, otherwise we
374 // risk causing an unnecessary rebuild after findCellForSpan()
375
376 return cellInfo;
377 }
378
379 /**
380 * Given a point, return the cell that strictly encloses that point
381 * @param x X coordinate of the point
382 * @param y Y coordinate of the point
383 * @param result Array of 2 ints to hold the x and y coordinate of the cell
384 */
385 void pointToCellExact(int x, int y, int[] result) {
386 final boolean portrait = mPortrait;
387
388 final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
389 final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
390
391 result[0] = (x - hStartPadding) / (mCellWidth + mWidthGap);
392 result[1] = (y - vStartPadding) / (mCellHeight + mHeightGap);
393
394 final int xAxis = portrait ? mShortAxisCells : mLongAxisCells;
395 final int yAxis = portrait ? mLongAxisCells : mShortAxisCells;
396
397 if (result[0] < 0) result[0] = 0;
398 if (result[0] >= xAxis) result[0] = xAxis - 1;
399 if (result[1] < 0) result[1] = 0;
400 if (result[1] >= yAxis) result[1] = yAxis - 1;
401 }
402
403 /**
404 * Given a point, return the cell that most closely encloses that point
405 * @param x X coordinate of the point
406 * @param y Y coordinate of the point
407 * @param result Array of 2 ints to hold the x and y coordinate of the cell
408 */
409 void pointToCellRounded(int x, int y, int[] result) {
410 pointToCellExact(x + (mCellWidth / 2), y + (mCellHeight / 2), result);
411 }
412
413 /**
414 * Given a cell coordinate, return the point that represents the upper left corner of that cell
415 *
416 * @param cellX X coordinate of the cell
417 * @param cellY Y coordinate of the cell
418 *
419 * @param result Array of 2 ints to hold the x and y coordinate of the point
420 */
421 void cellToPoint(int cellX, int cellY, int[] result) {
422 final boolean portrait = mPortrait;
423
424 final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
425 final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
426
427
428 result[0] = hStartPadding + cellX * (mCellWidth + mWidthGap);
429 result[1] = vStartPadding + cellY * (mCellHeight + mHeightGap);
430 }
431
432 @Override
433 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
434 // TODO: currently ignoring padding
435
436 int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
437 int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
438
439 int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
440 int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
441
442 if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
443 throw new RuntimeException("CellLayout cannot have UNSPECIFIED dimensions");
444 }
445
446 final int shortAxisCells = mShortAxisCells;
447 final int longAxisCells = mLongAxisCells;
448 final int longAxisStartPadding = mLongAxisStartPadding;
449 final int longAxisEndPadding = mLongAxisEndPadding;
450 final int shortAxisStartPadding = mShortAxisStartPadding;
451 final int shortAxisEndPadding = mShortAxisEndPadding;
452 final int cellWidth = mCellWidth;
453 final int cellHeight = mCellHeight;
454
455 mPortrait = heightSpecSize > widthSpecSize;
456
457 int numShortGaps = shortAxisCells - 1;
458 int numLongGaps = longAxisCells - 1;
459
460 if (mPortrait) {
461 int vSpaceLeft = heightSpecSize - longAxisStartPadding - longAxisEndPadding
462 - (cellHeight * longAxisCells);
463 mHeightGap = vSpaceLeft / numLongGaps;
464
465 int hSpaceLeft = widthSpecSize - shortAxisStartPadding - shortAxisEndPadding
466 - (cellWidth * shortAxisCells);
467 if (numShortGaps > 0) {
468 mWidthGap = hSpaceLeft / numShortGaps;
469 } else {
470 mWidthGap = 0;
471 }
472 } else {
473 int hSpaceLeft = widthSpecSize - longAxisStartPadding - longAxisEndPadding
474 - (cellWidth * longAxisCells);
475 mWidthGap = hSpaceLeft / numLongGaps;
476
477 int vSpaceLeft = heightSpecSize - shortAxisStartPadding - shortAxisEndPadding
478 - (cellHeight * shortAxisCells);
479 if (numShortGaps > 0) {
480 mHeightGap = vSpaceLeft / numShortGaps;
481 } else {
482 mHeightGap = 0;
483 }
484 }
485
486 int count = getChildCount();
487
488 for (int i = 0; i < count; i++) {
489 View child = getChildAt(i);
490 LayoutParams lp = (LayoutParams) child.getLayoutParams();
491
492 if (mPortrait) {
493 lp.setup(cellWidth, cellHeight, mWidthGap, mHeightGap, shortAxisStartPadding,
494 longAxisStartPadding);
495 } else {
496 lp.setup(cellWidth, cellHeight, mWidthGap, mHeightGap, longAxisStartPadding,
497 shortAxisStartPadding);
498 }
499
500 int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.width, MeasureSpec.EXACTLY);
501 int childheightMeasureSpec =
502 MeasureSpec.makeMeasureSpec(lp.height, MeasureSpec.EXACTLY);
503 child.measure(childWidthMeasureSpec, childheightMeasureSpec);
504 }
505
506 setMeasuredDimension(widthSpecSize, heightSpecSize);
507 }
508
509 @Override
510 protected void onLayout(boolean changed, int l, int t, int r, int b) {
511 int count = getChildCount();
512
513 for (int i = 0; i < count; i++) {
514 View child = getChildAt(i);
515 if (child.getVisibility() != GONE) {
516
517 CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
518
519 int childLeft = lp.x;
520 int childTop = lp.y;
521 child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);
522 }
523 }
524 }
525
526 @Override
527 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
528 final int count = getChildCount();
529 for (int i = 0; i < count; i++) {
530 final View view = getChildAt(i);
531 view.setDrawingCacheEnabled(enabled);
532 // Update the drawing caches
Romain Guy806b0f32009-06-26 16:57:39 -0700533 view.buildDrawingCache(true);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800534 }
535 }
536
537 @Override
538 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
539 super.setChildrenDrawnWithCacheEnabled(enabled);
540 }
541
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800542 /**
Jeff Sharkey70864282009-04-07 21:08:40 -0700543 * Find a vacant area that will fit the given bounds nearest the requested
544 * cell location. Uses Euclidean distance to score multiple vacant areas.
545 *
Romain Guy51afc022009-05-04 18:03:43 -0700546 * @param pixelX The X location at which you want to search for a vacant area.
547 * @param pixelY The Y location at which you want to search for a vacant area.
Jeff Sharkey70864282009-04-07 21:08:40 -0700548 * @param spanX Horizontal span of the object.
549 * @param spanY Vertical span of the object.
550 * @param vacantCells Pre-computed set of vacant cells to search.
551 * @param recycle Previously returned value to possibly recycle.
552 * @return The X, Y cell of a vacant area that can contain this object,
553 * nearest the requested location.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800554 */
Jeff Sharkey70864282009-04-07 21:08:40 -0700555 int[] findNearestVacantArea(int pixelX, int pixelY, int spanX, int spanY,
556 CellInfo vacantCells, int[] recycle) {
557
558 // Keep track of best-scoring drop area
559 final int[] bestXY = recycle != null ? recycle : new int[2];
560 final int[] cellXY = mCellXY;
561 double bestDistance = Double.MAX_VALUE;
562
563 // Bail early if vacant cells aren't valid
564 if (!vacantCells.valid) {
565 return null;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800566 }
567
Jeff Sharkey70864282009-04-07 21:08:40 -0700568 // Look across all vacant cells for best fit
569 final int size = vacantCells.vacantCells.size();
570 for (int i = 0; i < size; i++) {
571 final CellInfo.VacantCell cell = vacantCells.vacantCells.get(i);
572
573 // Reject if vacant cell isn't our exact size
574 if (cell.spanX != spanX || cell.spanY != spanY) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800575 continue;
576 }
Jeff Sharkey70864282009-04-07 21:08:40 -0700577
578 // Score is center distance from requested pixel
579 cellToPoint(cell.cellX, cell.cellY, cellXY);
580
581 double distance = Math.sqrt(Math.pow(cellXY[0] - pixelX, 2) +
582 Math.pow(cellXY[1] - pixelY, 2));
583 if (distance <= bestDistance) {
584 bestDistance = distance;
585 bestXY[0] = cell.cellX;
586 bestXY[1] = cell.cellY;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800587 }
588 }
589
Jeff Sharkey70864282009-04-07 21:08:40 -0700590 // Return null if no suitable location found
591 if (bestDistance < Double.MAX_VALUE) {
592 return bestXY;
593 } else {
594 return null;
595 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 }
Jeff Sharkey70864282009-04-07 21:08:40 -0700597
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800598 /**
599 * Drop a child at the specified position
600 *
601 * @param child The child that is being dropped
Jeff Sharkey70864282009-04-07 21:08:40 -0700602 * @param targetXY Destination area to move to
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800603 */
Jeff Sharkey70864282009-04-07 21:08:40 -0700604 void onDropChild(View child, int[] targetXY) {
Romain Guyd94533d2009-08-17 10:01:15 -0700605 if (child != null) {
606 LayoutParams lp = (LayoutParams) child.getLayoutParams();
607 lp.cellX = targetXY[0];
608 lp.cellY = targetXY[1];
609 lp.isDragging = false;
610 mDragRect.setEmpty();
611 child.requestLayout();
612 invalidate();
613 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614 }
615
616 void onDropAborted(View child) {
617 if (child != null) {
618 ((LayoutParams) child.getLayoutParams()).isDragging = false;
619 invalidate();
620 }
621 mDragRect.setEmpty();
622 }
623
624 /**
625 * Start dragging the specified child
626 *
627 * @param child The child that is being dragged
628 */
629 void onDragChild(View child) {
630 LayoutParams lp = (LayoutParams) child.getLayoutParams();
631 lp.isDragging = true;
632 mDragRect.setEmpty();
633 }
634
635 /**
636 * Drag a child over the specified position
637 *
638 * @param child The child that is being dropped
639 * @param cellX The child's new x cell location
640 * @param cellY The child's new y cell location
641 */
642 void onDragOverChild(View child, int cellX, int cellY) {
643 int[] cellXY = mCellXY;
644 pointToCellRounded(cellX, cellY, cellXY);
645 LayoutParams lp = (LayoutParams) child.getLayoutParams();
646 cellToRect(cellXY[0], cellXY[1], lp.cellHSpan, lp.cellVSpan, mDragRect);
647 invalidate();
648 }
649
650 /**
651 * Computes a bounding rectangle for a range of cells
652 *
653 * @param cellX X coordinate of upper left corner expressed as a cell position
654 * @param cellY Y coordinate of upper left corner expressed as a cell position
655 * @param cellHSpan Width in cells
656 * @param cellVSpan Height in cells
657 * @param dragRect Rectnagle into which to put the results
658 */
659 public void cellToRect(int cellX, int cellY, int cellHSpan, int cellVSpan, RectF dragRect) {
660 final boolean portrait = mPortrait;
661 final int cellWidth = mCellWidth;
662 final int cellHeight = mCellHeight;
663 final int widthGap = mWidthGap;
664 final int heightGap = mHeightGap;
665
666 final int hStartPadding = portrait ? mShortAxisStartPadding : mLongAxisStartPadding;
667 final int vStartPadding = portrait ? mLongAxisStartPadding : mShortAxisStartPadding;
668
669 int width = cellHSpan * cellWidth + ((cellHSpan - 1) * widthGap);
670 int height = cellVSpan * cellHeight + ((cellVSpan - 1) * heightGap);
671
672 int x = hStartPadding + cellX * (cellWidth + widthGap);
673 int y = vStartPadding + cellY * (cellHeight + heightGap);
674
675 dragRect.set(x, y, x + width, y + height);
676 }
677
678 /**
679 * Computes the required horizontal and vertical cell spans to always
680 * fit the given rectangle.
681 *
682 * @param width Width in pixels
683 * @param height Height in pixels
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800684 */
685 public int[] rectToCell(int width, int height) {
686 // Always assume we're working with the smallest span to make sure we
687 // reserve enough space in both orientations.
688 int actualWidth = mCellWidth + mWidthGap;
689 int actualHeight = mCellHeight + mHeightGap;
690 int smallerSize = Math.min(actualWidth, actualHeight);
691
692 // Always round up to next largest cell
693 int spanX = (width + smallerSize) / smallerSize;
694 int spanY = (height + smallerSize) / smallerSize;
695 return new int[] { spanX, spanY };
696 }
697
698 /**
699 * Find the first vacant cell, if there is one.
700 *
701 * @param vacant Holds the x and y coordinate of the vacant cell
702 * @param spanX Horizontal cell span.
703 * @param spanY Vertical cell span.
704 *
705 * @return True if a vacant cell was found
706 */
707 public boolean getVacantCell(int[] vacant, int spanX, int spanY) {
708 final boolean portrait = mPortrait;
709 final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
710 final int yCount = portrait ? mLongAxisCells : mShortAxisCells;
711 final boolean[][] occupied = mOccupied;
712
Jeff Sharkey70864282009-04-07 21:08:40 -0700713 findOccupiedCells(xCount, yCount, occupied, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800714
715 return findVacantCell(vacant, spanX, spanY, xCount, yCount, occupied);
716 }
717
718 static boolean findVacantCell(int[] vacant, int spanX, int spanY,
719 int xCount, int yCount, boolean[][] occupied) {
720
721 for (int x = 0; x < xCount; x++) {
722 for (int y = 0; y < yCount; y++) {
723 boolean available = !occupied[x][y];
724out: for (int i = x; i < x + spanX - 1 && x < xCount; i++) {
725 for (int j = y; j < y + spanY - 1 && y < yCount; j++) {
726 available = available && !occupied[i][j];
727 if (!available) break out;
728 }
729 }
730
731 if (available) {
732 vacant[0] = x;
733 vacant[1] = y;
734 return true;
735 }
736 }
737 }
738
739 return false;
740 }
741
742 boolean[] getOccupiedCells() {
743 final boolean portrait = mPortrait;
744 final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
745 final int yCount = portrait ? mLongAxisCells : mShortAxisCells;
746 final boolean[][] occupied = mOccupied;
747
Jeff Sharkey70864282009-04-07 21:08:40 -0700748 findOccupiedCells(xCount, yCount, occupied, null);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800749
750 final boolean[] flat = new boolean[xCount * yCount];
751 for (int y = 0; y < yCount; y++) {
752 for (int x = 0; x < xCount; x++) {
753 flat[y * xCount + x] = occupied[x][y];
754 }
755 }
756
757 return flat;
758 }
759
Jeff Sharkey70864282009-04-07 21:08:40 -0700760 private void findOccupiedCells(int xCount, int yCount, boolean[][] occupied, View ignoreView) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800761 for (int x = 0; x < xCount; x++) {
762 for (int y = 0; y < yCount; y++) {
763 occupied[x][y] = false;
764 }
765 }
766
767 int count = getChildCount();
768 for (int i = 0; i < count; i++) {
769 View child = getChildAt(i);
Jeff Sharkey70864282009-04-07 21:08:40 -0700770 if (child instanceof Folder || child.equals(ignoreView)) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800771 continue;
772 }
773 LayoutParams lp = (LayoutParams) child.getLayoutParams();
774
775 for (int x = lp.cellX; x < lp.cellX + lp.cellHSpan && x < xCount; x++) {
776 for (int y = lp.cellY; y < lp.cellY + lp.cellVSpan && y < yCount; y++) {
777 occupied[x][y] = true;
778 }
779 }
780 }
781 }
782
783 @Override
784 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
785 return new CellLayout.LayoutParams(getContext(), attrs);
786 }
787
788 @Override
789 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
790 return p instanceof CellLayout.LayoutParams;
791 }
792
793 @Override
794 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
795 return new CellLayout.LayoutParams(p);
796 }
797
798 public static class LayoutParams extends ViewGroup.MarginLayoutParams {
799 /**
800 * Horizontal location of the item in the grid.
801 */
802 @ViewDebug.ExportedProperty
803 public int cellX;
804
805 /**
806 * Vertical location of the item in the grid.
807 */
808 @ViewDebug.ExportedProperty
809 public int cellY;
810
811 /**
812 * Number of cells spanned horizontally by the item.
813 */
814 @ViewDebug.ExportedProperty
815 public int cellHSpan;
816
817 /**
818 * Number of cells spanned vertically by the item.
819 */
820 @ViewDebug.ExportedProperty
821 public int cellVSpan;
822
823 /**
824 * Is this item currently being dragged
825 */
826 public boolean isDragging;
827
828 // X coordinate of the view in the layout.
829 @ViewDebug.ExportedProperty
830 int x;
831 // Y coordinate of the view in the layout.
832 @ViewDebug.ExportedProperty
833 int y;
834
835 public LayoutParams(Context c, AttributeSet attrs) {
836 super(c, attrs);
837 cellHSpan = 1;
838 cellVSpan = 1;
839 }
840
841 public LayoutParams(ViewGroup.LayoutParams source) {
842 super(source);
843 cellHSpan = 1;
844 cellVSpan = 1;
845 }
846
847 public LayoutParams(int cellX, int cellY, int cellHSpan, int cellVSpan) {
848 super(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
849 this.cellX = cellX;
850 this.cellY = cellY;
851 this.cellHSpan = cellHSpan;
852 this.cellVSpan = cellVSpan;
853 }
854
855 public void setup(int cellWidth, int cellHeight, int widthGap, int heightGap,
856 int hStartPadding, int vStartPadding) {
857
858 final int myCellHSpan = cellHSpan;
859 final int myCellVSpan = cellVSpan;
860 final int myCellX = cellX;
861 final int myCellY = cellY;
862
863 width = myCellHSpan * cellWidth + ((myCellHSpan - 1) * widthGap) -
864 leftMargin - rightMargin;
865 height = myCellVSpan * cellHeight + ((myCellVSpan - 1) * heightGap) -
866 topMargin - bottomMargin;
867
868 x = hStartPadding + myCellX * (cellWidth + widthGap) + leftMargin;
869 y = vStartPadding + myCellY * (cellHeight + heightGap) + topMargin;
870 }
871 }
872
873 static final class CellInfo implements ContextMenu.ContextMenuInfo {
874 /**
875 * See View.AttachInfo.InvalidateInfo for futher explanations about
876 * the recycling mechanism. In this case, we recycle the vacant cells
877 * instances because up to several hundreds can be instanciated when
878 * the user long presses an empty cell.
879 */
880 static final class VacantCell {
881 int cellX;
882 int cellY;
883 int spanX;
884 int spanY;
885
886 // We can create up to 523 vacant cells on a 4x4 grid, 100 seems
887 // like a reasonable compromise given the size of a VacantCell and
888 // the fact that the user is not likely to touch an empty 4x4 grid
889 // very often
890 private static final int POOL_LIMIT = 100;
891 private static final Object sLock = new Object();
892
893 private static int sAcquiredCount = 0;
894 private static VacantCell sRoot;
895
896 private VacantCell next;
897
898 static VacantCell acquire() {
899 synchronized (sLock) {
900 if (sRoot == null) {
901 return new VacantCell();
902 }
903
904 VacantCell info = sRoot;
905 sRoot = info.next;
906 sAcquiredCount--;
907
908 return info;
909 }
910 }
911
912 void release() {
913 synchronized (sLock) {
914 if (sAcquiredCount < POOL_LIMIT) {
915 sAcquiredCount++;
916 next = sRoot;
917 sRoot = this;
918 }
919 }
920 }
921
922 @Override
923 public String toString() {
924 return "VacantCell[x=" + cellX + ", y=" + cellY + ", spanX=" + spanX +
925 ", spanY=" + spanY + "]";
926 }
927 }
928
929 View cell;
930 int cellX;
931 int cellY;
932 int spanX;
933 int spanY;
934 int screen;
935 boolean valid;
936
937 final ArrayList<VacantCell> vacantCells = new ArrayList<VacantCell>(VacantCell.POOL_LIMIT);
938 int maxVacantSpanX;
939 int maxVacantSpanXSpanY;
940 int maxVacantSpanY;
941 int maxVacantSpanYSpanX;
942 final Rect current = new Rect();
943
Romain Guy4c58c482009-05-12 17:35:41 -0700944 void clearVacantCells() {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 final ArrayList<VacantCell> list = vacantCells;
946 final int count = list.size();
947
948 for (int i = 0; i < count; i++) list.get(i).release();
949
950 list.clear();
951 }
952
953 void findVacantCellsFromOccupied(boolean[] occupied, int xCount, int yCount) {
954 if (cellX < 0 || cellY < 0) {
955 maxVacantSpanX = maxVacantSpanXSpanY = Integer.MIN_VALUE;
956 maxVacantSpanY = maxVacantSpanYSpanX = Integer.MIN_VALUE;
957 clearVacantCells();
958 return;
959 }
960
961 final boolean[][] unflattened = new boolean[xCount][yCount];
962 for (int y = 0; y < yCount; y++) {
963 for (int x = 0; x < xCount; x++) {
964 unflattened[x][y] = occupied[y * xCount + x];
965 }
966 }
967 CellLayout.findIntersectingVacantCells(this, cellX, cellY, xCount, yCount, unflattened);
968 }
969
970 /**
971 * This method can be called only once! Calling #findVacantCellsFromOccupied will
972 * restore the ability to call this method.
973 *
974 * Finds the upper-left coordinate of the first rectangle in the grid that can
975 * hold a cell of the specified dimensions.
976 *
977 * @param cellXY The array that will contain the position of a vacant cell if such a cell
978 * can be found.
979 * @param spanX The horizontal span of the cell we want to find.
980 * @param spanY The vertical span of the cell we want to find.
981 *
982 * @return True if a vacant cell of the specified dimension was found, false otherwise.
983 */
984 boolean findCellForSpan(int[] cellXY, int spanX, int spanY) {
Romain Guy4c58c482009-05-12 17:35:41 -0700985 return findCellForSpan(cellXY, spanX, spanY, true);
986 }
987
988 boolean findCellForSpan(int[] cellXY, int spanX, int spanY, boolean clear) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800989 final ArrayList<VacantCell> list = vacantCells;
990 final int count = list.size();
991
992 boolean found = false;
993
994 if (this.spanX >= spanX && this.spanY >= spanY) {
995 cellXY[0] = cellX;
996 cellXY[1] = cellY;
997 found = true;
998 }
999
1000 // Look for an exact match first
1001 for (int i = 0; i < count; i++) {
1002 VacantCell cell = list.get(i);
1003 if (cell.spanX == spanX && cell.spanY == spanY) {
1004 cellXY[0] = cell.cellX;
1005 cellXY[1] = cell.cellY;
1006 found = true;
1007 break;
1008 }
1009 }
1010
1011 // Look for the first cell large enough
1012 for (int i = 0; i < count; i++) {
1013 VacantCell cell = list.get(i);
1014 if (cell.spanX >= spanX && cell.spanY >= spanY) {
1015 cellXY[0] = cell.cellX;
1016 cellXY[1] = cell.cellY;
1017 found = true;
1018 break;
1019 }
1020 }
1021
Romain Guy4c58c482009-05-12 17:35:41 -07001022 if (clear) clearVacantCells();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001023
1024 return found;
1025 }
1026
1027 @Override
1028 public String toString() {
1029 return "Cell[view=" + (cell == null ? "null" : cell.getClass()) + ", x=" + cellX +
1030 ", y=" + cellY + "]";
1031 }
1032 }
1033}
1034
1035