1 /*
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 
17 package com.android.launcher2;
18 
19 import android.animation.Animator;
20 import android.animation.AnimatorListenerAdapter;
21 import android.animation.ObjectAnimator;
22 import android.animation.PropertyValuesHolder;
23 import android.content.Context;
24 import android.content.res.Resources;
25 import android.graphics.PointF;
26 import android.graphics.Rect;
27 import android.graphics.drawable.Drawable;
28 import android.text.InputType;
29 import android.text.Selection;
30 import android.text.Spannable;
31 import android.util.AttributeSet;
32 import android.util.Log;
33 import android.view.ActionMode;
34 import android.view.KeyEvent;
35 import android.view.LayoutInflater;
36 import android.view.Menu;
37 import android.view.MenuItem;
38 import android.view.MotionEvent;
39 import android.view.View;
40 import android.view.accessibility.AccessibilityEvent;
41 import android.view.accessibility.AccessibilityManager;
42 import android.view.inputmethod.EditorInfo;
43 import android.view.inputmethod.InputMethodManager;
44 import android.widget.LinearLayout;
45 import android.widget.TextView;
46 
47 import com.android.launcher.R;
48 import com.android.launcher2.FolderInfo.FolderListener;
49 
50 import java.util.ArrayList;
51 import java.util.Collections;
52 import java.util.Comparator;
53 
54 /**
55  * Represents a set of icons chosen by the user or generated by the system.
56  */
57 public class Folder extends LinearLayout implements DragSource, View.OnClickListener,
58         View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
59         View.OnFocusChangeListener {
60     private static final String TAG = "Launcher.Folder";
61 
62     protected DragController mDragController;
63     protected Launcher mLauncher;
64     protected FolderInfo mInfo;
65 
66     static final int STATE_NONE = -1;
67     static final int STATE_SMALL = 0;
68     static final int STATE_ANIMATING = 1;
69     static final int STATE_OPEN = 2;
70 
71     private int mExpandDuration;
72     protected CellLayout mContent;
73     private final LayoutInflater mInflater;
74     private final IconCache mIconCache;
75     private int mState = STATE_NONE;
76     private static final int REORDER_ANIMATION_DURATION = 230;
77     private static final int ON_EXIT_CLOSE_DELAY = 800;
78     private boolean mRearrangeOnClose = false;
79     private FolderIcon mFolderIcon;
80     private int mMaxCountX;
81     private int mMaxCountY;
82     private int mMaxNumItems;
83     private ArrayList<View> mItemsInReadingOrder = new ArrayList<View>();
84     private Drawable mIconDrawable;
85     boolean mItemsInvalidated = false;
86     private ShortcutInfo mCurrentDragInfo;
87     private View mCurrentDragView;
88     boolean mSuppressOnAdd = false;
89     private int[] mTargetCell = new int[2];
90     private int[] mPreviousTargetCell = new int[2];
91     private int[] mEmptyCell = new int[2];
92     private Alarm mReorderAlarm = new Alarm();
93     private Alarm mOnExitAlarm = new Alarm();
94     private int mFolderNameHeight;
95     private Rect mTempRect = new Rect();
96     private boolean mDragInProgress = false;
97     private boolean mDeleteFolderOnDropCompleted = false;
98     private boolean mSuppressFolderDeletion = false;
99     private boolean mItemAddedBackToSelfViaIcon = false;
100     FolderEditText mFolderName;
101     private float mFolderIconPivotX;
102     private float mFolderIconPivotY;
103 
104     private boolean mIsEditingName = false;
105     private InputMethodManager mInputMethodManager;
106 
107     private static String sDefaultFolderName;
108     private static String sHintText;
109 
110     private boolean mDestroyed;
111 
112     /**
113      * Used to inflate the Workspace from XML.
114      *
115      * @param context The application's context.
116      * @param attrs The attribtues set containing the Workspace's customization values.
117      */
Folder(Context context, AttributeSet attrs)118     public Folder(Context context, AttributeSet attrs) {
119         super(context, attrs);
120         setAlwaysDrawnWithCacheEnabled(false);
121         mInflater = LayoutInflater.from(context);
122         mIconCache = ((LauncherApplication)context.getApplicationContext()).getIconCache();
123 
124         Resources res = getResources();
125         mMaxCountX = res.getInteger(R.integer.folder_max_count_x);
126         mMaxCountY = res.getInteger(R.integer.folder_max_count_y);
127         mMaxNumItems = res.getInteger(R.integer.folder_max_num_items);
128         if (mMaxCountX < 0 || mMaxCountY < 0 || mMaxNumItems < 0) {
129             mMaxCountX = LauncherModel.getCellCountX();
130             mMaxCountY = LauncherModel.getCellCountY();
131             mMaxNumItems = mMaxCountX * mMaxCountY;
132         }
133 
134         mInputMethodManager = (InputMethodManager)
135                 getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
136 
137         mExpandDuration = res.getInteger(R.integer.config_folderAnimDuration);
138 
139         if (sDefaultFolderName == null) {
140             sDefaultFolderName = res.getString(R.string.folder_name);
141         }
142         if (sHintText == null) {
143             sHintText = res.getString(R.string.folder_hint_text);
144         }
145         mLauncher = (Launcher) context;
146         // We need this view to be focusable in touch mode so that when text editing of the folder
147         // name is complete, we have something to focus on, thus hiding the cursor and giving
148         // reliable behvior when clicking the text field (since it will always gain focus on click).
149         setFocusableInTouchMode(true);
150     }
151 
152     @Override
onFinishInflate()153     protected void onFinishInflate() {
154         super.onFinishInflate();
155         mContent = (CellLayout) findViewById(R.id.folder_content);
156         mContent.setGridSize(0, 0);
157         mContent.getShortcutsAndWidgets().setMotionEventSplittingEnabled(false);
158         mContent.setInvertIfRtl(true);
159         mFolderName = (FolderEditText) findViewById(R.id.folder_name);
160         mFolderName.setFolder(this);
161         mFolderName.setOnFocusChangeListener(this);
162 
163         // We find out how tall the text view wants to be (it is set to wrap_content), so that
164         // we can allocate the appropriate amount of space for it.
165         int measureSpec = MeasureSpec.UNSPECIFIED;
166         mFolderName.measure(measureSpec, measureSpec);
167         mFolderNameHeight = mFolderName.getMeasuredHeight();
168 
169         // We disable action mode for now since it messes up the view on phones
170         mFolderName.setCustomSelectionActionModeCallback(mActionModeCallback);
171         mFolderName.setOnEditorActionListener(this);
172         mFolderName.setSelectAllOnFocus(true);
173         mFolderName.setInputType(mFolderName.getInputType() |
174                 InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
175     }
176 
177     private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
178         public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
179             return false;
180         }
181 
182         public boolean onCreateActionMode(ActionMode mode, Menu menu) {
183             return false;
184         }
185 
186         public void onDestroyActionMode(ActionMode mode) {
187         }
188 
189         public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
190             return false;
191         }
192     };
193 
onClick(View v)194     public void onClick(View v) {
195         Object tag = v.getTag();
196         if (tag instanceof ShortcutInfo) {
197             // refactor this code from Folder
198             ShortcutInfo item = (ShortcutInfo) tag;
199             int[] pos = new int[2];
200             v.getLocationOnScreen(pos);
201             item.intent.setSourceBounds(new Rect(pos[0], pos[1],
202                     pos[0] + v.getWidth(), pos[1] + v.getHeight()));
203 
204             mLauncher.startActivitySafely(v, item.intent, item);
205         }
206     }
207 
onLongClick(View v)208     public boolean onLongClick(View v) {
209         // Return if global dragging is not enabled
210         if (!mLauncher.isDraggingEnabled()) return true;
211 
212         Object tag = v.getTag();
213         if (tag instanceof ShortcutInfo) {
214             ShortcutInfo item = (ShortcutInfo) tag;
215             if (!v.isInTouchMode()) {
216                 return false;
217             }
218 
219             mLauncher.dismissFolderCling(null);
220 
221             mLauncher.getWorkspace().onDragStartedWithItem(v);
222             mLauncher.getWorkspace().beginDragShared(v, this);
223             mIconDrawable = ((TextView) v).getCompoundDrawables()[1];
224 
225             mCurrentDragInfo = item;
226             mEmptyCell[0] = item.cellX;
227             mEmptyCell[1] = item.cellY;
228             mCurrentDragView = v;
229 
230             mContent.removeView(mCurrentDragView);
231             mInfo.remove(mCurrentDragInfo);
232             mDragInProgress = true;
233             mItemAddedBackToSelfViaIcon = false;
234         }
235         return true;
236     }
237 
isEditingName()238     public boolean isEditingName() {
239         return mIsEditingName;
240     }
241 
startEditingFolderName()242     public void startEditingFolderName() {
243         mFolderName.setHint("");
244         mIsEditingName = true;
245     }
246 
dismissEditingName()247     public void dismissEditingName() {
248         mInputMethodManager.hideSoftInputFromWindow(getWindowToken(), 0);
249         doneEditingFolderName(true);
250     }
251 
doneEditingFolderName(boolean commit)252     public void doneEditingFolderName(boolean commit) {
253         mFolderName.setHint(sHintText);
254         // Convert to a string here to ensure that no other state associated with the text field
255         // gets saved.
256         String newTitle = mFolderName.getText().toString();
257         mInfo.setTitle(newTitle);
258         LauncherModel.updateItemInDatabase(mLauncher, mInfo);
259 
260         if (commit) {
261             sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
262                     String.format(getContext().getString(R.string.folder_renamed), newTitle));
263         }
264         // In order to clear the focus from the text field, we set the focus on ourself. This
265         // ensures that every time the field is clicked, focus is gained, giving reliable behavior.
266         requestFocus();
267 
268         Selection.setSelection((Spannable) mFolderName.getText(), 0, 0);
269         mIsEditingName = false;
270     }
271 
onEditorAction(TextView v, int actionId, KeyEvent event)272     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
273         if (actionId == EditorInfo.IME_ACTION_DONE) {
274             dismissEditingName();
275             return true;
276         }
277         return false;
278     }
279 
getEditTextRegion()280     public View getEditTextRegion() {
281         return mFolderName;
282     }
283 
getDragDrawable()284     public Drawable getDragDrawable() {
285         return mIconDrawable;
286     }
287 
288     /**
289      * We need to handle touch events to prevent them from falling through to the workspace below.
290      */
291     @Override
onTouchEvent(MotionEvent ev)292     public boolean onTouchEvent(MotionEvent ev) {
293         return true;
294     }
295 
setDragController(DragController dragController)296     public void setDragController(DragController dragController) {
297         mDragController = dragController;
298     }
299 
setFolderIcon(FolderIcon icon)300     void setFolderIcon(FolderIcon icon) {
301         mFolderIcon = icon;
302     }
303 
304     @Override
dispatchPopulateAccessibilityEvent(AccessibilityEvent event)305     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
306         // When the folder gets focus, we don't want to announce the list of items.
307         return true;
308     }
309 
310     /**
311      * @return the FolderInfo object associated with this folder
312      */
getInfo()313     FolderInfo getInfo() {
314         return mInfo;
315     }
316 
317     private class GridComparator implements Comparator<ShortcutInfo> {
318         int mNumCols;
GridComparator(int numCols)319         public GridComparator(int numCols) {
320             mNumCols = numCols;
321         }
322 
323         @Override
compare(ShortcutInfo lhs, ShortcutInfo rhs)324         public int compare(ShortcutInfo lhs, ShortcutInfo rhs) {
325             int lhIndex = lhs.cellY * mNumCols + lhs.cellX;
326             int rhIndex = rhs.cellY * mNumCols + rhs.cellX;
327             return (lhIndex - rhIndex);
328         }
329     }
330 
placeInReadingOrder(ArrayList<ShortcutInfo> items)331     private void placeInReadingOrder(ArrayList<ShortcutInfo> items) {
332         int maxX = 0;
333         int count = items.size();
334         for (int i = 0; i < count; i++) {
335             ShortcutInfo item = items.get(i);
336             if (item.cellX > maxX) {
337                 maxX = item.cellX;
338             }
339         }
340 
341         GridComparator gridComparator = new GridComparator(maxX + 1);
342         Collections.sort(items, gridComparator);
343         final int countX = mContent.getCountX();
344         for (int i = 0; i < count; i++) {
345             int x = i % countX;
346             int y = i / countX;
347             ShortcutInfo item = items.get(i);
348             item.cellX = x;
349             item.cellY = y;
350         }
351     }
352 
bind(FolderInfo info)353     void bind(FolderInfo info) {
354         mInfo = info;
355         ArrayList<ShortcutInfo> children = info.contents;
356         ArrayList<ShortcutInfo> overflow = new ArrayList<ShortcutInfo>();
357         setupContentForNumItems(children.size());
358         placeInReadingOrder(children);
359         int count = 0;
360         for (int i = 0; i < children.size(); i++) {
361             ShortcutInfo child = (ShortcutInfo) children.get(i);
362             if (!createAndAddShortcut(child)) {
363                 overflow.add(child);
364             } else {
365                 count++;
366             }
367         }
368 
369         // We rearrange the items in case there are any empty gaps
370         setupContentForNumItems(count);
371 
372         // If our folder has too many items we prune them from the list. This is an issue
373         // when upgrading from the old Folders implementation which could contain an unlimited
374         // number of items.
375         for (ShortcutInfo item: overflow) {
376             mInfo.remove(item);
377             LauncherModel.deleteItemFromDatabase(mLauncher, item);
378         }
379 
380         mItemsInvalidated = true;
381         updateTextViewFocus();
382         mInfo.addListener(this);
383 
384         if (!sDefaultFolderName.contentEquals(mInfo.title)) {
385             mFolderName.setText(mInfo.title);
386         } else {
387             mFolderName.setText("");
388         }
389         updateItemLocationsInDatabase();
390     }
391 
392     /**
393      * Creates a new UserFolder, inflated from R.layout.user_folder.
394      *
395      * @param context The application's context.
396      *
397      * @return A new UserFolder.
398      */
fromXml(Context context)399     static Folder fromXml(Context context) {
400         return (Folder) LayoutInflater.from(context).inflate(R.layout.user_folder, null);
401     }
402 
403     /**
404      * This method is intended to make the UserFolder to be visually identical in size and position
405      * to its associated FolderIcon. This allows for a seamless transition into the expanded state.
406      */
positionAndSizeAsIcon()407     private void positionAndSizeAsIcon() {
408         if (!(getParent() instanceof DragLayer)) return;
409         setScaleX(0.8f);
410         setScaleY(0.8f);
411         setAlpha(0f);
412         mState = STATE_SMALL;
413     }
414 
animateOpen()415     public void animateOpen() {
416         positionAndSizeAsIcon();
417 
418         if (!(getParent() instanceof DragLayer)) return;
419         centerAboutIcon();
420         PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1);
421         PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
422         PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
423         final ObjectAnimator oa =
424             LauncherAnimUtils.ofPropertyValuesHolder(this, alpha, scaleX, scaleY);
425 
426         oa.addListener(new AnimatorListenerAdapter() {
427             @Override
428             public void onAnimationStart(Animator animation) {
429                 sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
430                         String.format(getContext().getString(R.string.folder_opened),
431                         mContent.getCountX(), mContent.getCountY()));
432                 mState = STATE_ANIMATING;
433             }
434             @Override
435             public void onAnimationEnd(Animator animation) {
436                 mState = STATE_OPEN;
437                 setLayerType(LAYER_TYPE_NONE, null);
438                 Cling cling = mLauncher.showFirstRunFoldersCling();
439                 if (cling != null) {
440                     cling.bringToFront();
441                 }
442                 setFocusOnFirstChild();
443             }
444         });
445         oa.setDuration(mExpandDuration);
446         setLayerType(LAYER_TYPE_HARDWARE, null);
447         oa.start();
448     }
449 
sendCustomAccessibilityEvent(int type, String text)450     private void sendCustomAccessibilityEvent(int type, String text) {
451         AccessibilityManager accessibilityManager = (AccessibilityManager)
452                 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
453         if (accessibilityManager.isEnabled()) {
454             AccessibilityEvent event = AccessibilityEvent.obtain(type);
455             onInitializeAccessibilityEvent(event);
456             event.getText().add(text);
457             accessibilityManager.sendAccessibilityEvent(event);
458         }
459     }
460 
setFocusOnFirstChild()461     private void setFocusOnFirstChild() {
462         View firstChild = mContent.getChildAt(0, 0);
463         if (firstChild != null) {
464             firstChild.requestFocus();
465         }
466     }
467 
animateClosed()468     public void animateClosed() {
469         if (!(getParent() instanceof DragLayer)) return;
470         PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
471         PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.9f);
472         PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.9f);
473         final ObjectAnimator oa =
474                 LauncherAnimUtils.ofPropertyValuesHolder(this, alpha, scaleX, scaleY);
475 
476         oa.addListener(new AnimatorListenerAdapter() {
477             @Override
478             public void onAnimationEnd(Animator animation) {
479                 onCloseComplete();
480                 setLayerType(LAYER_TYPE_NONE, null);
481                 mState = STATE_SMALL;
482             }
483             @Override
484             public void onAnimationStart(Animator animation) {
485                 sendCustomAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
486                         getContext().getString(R.string.folder_closed));
487                 mState = STATE_ANIMATING;
488             }
489         });
490         oa.setDuration(mExpandDuration);
491         setLayerType(LAYER_TYPE_HARDWARE, null);
492         oa.start();
493     }
494 
notifyDataSetChanged()495     void notifyDataSetChanged() {
496         // recreate all the children if the data set changes under us. We may want to do this more
497         // intelligently (ie just removing the views that should no longer exist)
498         mContent.removeAllViewsInLayout();
499         bind(mInfo);
500     }
501 
acceptDrop(DragObject d)502     public boolean acceptDrop(DragObject d) {
503         final ItemInfo item = (ItemInfo) d.dragInfo;
504         final int itemType = item.itemType;
505         return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
506                     itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) &&
507                     !isFull());
508     }
509 
findAndSetEmptyCells(ShortcutInfo item)510     protected boolean findAndSetEmptyCells(ShortcutInfo item) {
511         int[] emptyCell = new int[2];
512         if (mContent.findCellForSpan(emptyCell, item.spanX, item.spanY)) {
513             item.cellX = emptyCell[0];
514             item.cellY = emptyCell[1];
515             return true;
516         } else {
517             return false;
518         }
519     }
520 
createAndAddShortcut(ShortcutInfo item)521     protected boolean createAndAddShortcut(ShortcutInfo item) {
522         final TextView textView =
523             (TextView) mInflater.inflate(R.layout.application, this, false);
524         textView.setCompoundDrawablesWithIntrinsicBounds(null,
525                 new FastBitmapDrawable(item.getIcon(mIconCache)), null, null);
526         textView.setText(item.title);
527         if (item.contentDescription != null) {
528             textView.setContentDescription(item.contentDescription);
529         }
530         textView.setTag(item);
531 
532         textView.setOnClickListener(this);
533         textView.setOnLongClickListener(this);
534 
535         // We need to check here to verify that the given item's location isn't already occupied
536         // by another item.
537         if (mContent.getChildAt(item.cellX, item.cellY) != null || item.cellX < 0 || item.cellY < 0
538                 || item.cellX >= mContent.getCountX() || item.cellY >= mContent.getCountY()) {
539             // This shouldn't happen, log it.
540             Log.e(TAG, "Folder order not properly persisted during bind");
541             if (!findAndSetEmptyCells(item)) {
542                 return false;
543             }
544         }
545 
546         CellLayout.LayoutParams lp =
547             new CellLayout.LayoutParams(item.cellX, item.cellY, item.spanX, item.spanY);
548         boolean insert = false;
549         textView.setOnKeyListener(new FolderKeyEventListener());
550         mContent.addViewToCellLayout(textView, insert ? 0 : -1, (int)item.id, lp, true);
551         return true;
552     }
553 
onDragEnter(DragObject d)554     public void onDragEnter(DragObject d) {
555         mPreviousTargetCell[0] = -1;
556         mPreviousTargetCell[1] = -1;
557         mOnExitAlarm.cancelAlarm();
558     }
559 
560     OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
561         public void onAlarm(Alarm alarm) {
562             realTimeReorder(mEmptyCell, mTargetCell);
563         }
564     };
565 
readingOrderGreaterThan(int[] v1, int[] v2)566     boolean readingOrderGreaterThan(int[] v1, int[] v2) {
567         if (v1[1] > v2[1] || (v1[1] == v2[1] && v1[0] > v2[0])) {
568             return true;
569         } else {
570             return false;
571         }
572     }
573 
realTimeReorder(int[] empty, int[] target)574     private void realTimeReorder(int[] empty, int[] target) {
575         boolean wrap;
576         int startX;
577         int endX;
578         int startY;
579         int delay = 0;
580         float delayAmount = 30;
581         if (readingOrderGreaterThan(target, empty)) {
582             wrap = empty[0] >= mContent.getCountX() - 1;
583             startY = wrap ? empty[1] + 1 : empty[1];
584             for (int y = startY; y <= target[1]; y++) {
585                 startX = y == empty[1] ? empty[0] + 1 : 0;
586                 endX = y < target[1] ? mContent.getCountX() - 1 : target[0];
587                 for (int x = startX; x <= endX; x++) {
588                     View v = mContent.getChildAt(x,y);
589                     if (mContent.animateChildToPosition(v, empty[0], empty[1],
590                             REORDER_ANIMATION_DURATION, delay, true, true)) {
591                         empty[0] = x;
592                         empty[1] = y;
593                         delay += delayAmount;
594                         delayAmount *= 0.9;
595                     }
596                 }
597             }
598         } else {
599             wrap = empty[0] == 0;
600             startY = wrap ? empty[1] - 1 : empty[1];
601             for (int y = startY; y >= target[1]; y--) {
602                 startX = y == empty[1] ? empty[0] - 1 : mContent.getCountX() - 1;
603                 endX = y > target[1] ? 0 : target[0];
604                 for (int x = startX; x >= endX; x--) {
605                     View v = mContent.getChildAt(x,y);
606                     if (mContent.animateChildToPosition(v, empty[0], empty[1],
607                             REORDER_ANIMATION_DURATION, delay, true, true)) {
608                         empty[0] = x;
609                         empty[1] = y;
610                         delay += delayAmount;
611                         delayAmount *= 0.9;
612                     }
613                 }
614             }
615         }
616     }
617 
isLayoutRtl()618     public boolean isLayoutRtl() {
619         return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
620     }
621 
onDragOver(DragObject d)622     public void onDragOver(DragObject d) {
623         float[] r = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, d.dragView, null);
624         mTargetCell = mContent.findNearestArea((int) r[0], (int) r[1], 1, 1, mTargetCell);
625 
626         if (isLayoutRtl()) {
627             mTargetCell[0] = mContent.getCountX() - mTargetCell[0] - 1;
628         }
629 
630         if (mTargetCell[0] != mPreviousTargetCell[0] || mTargetCell[1] != mPreviousTargetCell[1]) {
631             mReorderAlarm.cancelAlarm();
632             mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
633             mReorderAlarm.setAlarm(150);
634             mPreviousTargetCell[0] = mTargetCell[0];
635             mPreviousTargetCell[1] = mTargetCell[1];
636         }
637     }
638 
639     // This is used to compute the visual center of the dragView. The idea is that
640     // the visual center represents the user's interpretation of where the item is, and hence
641     // is the appropriate point to use when determining drop location.
getDragViewVisualCenter(int x, int y, int xOffset, int yOffset, DragView dragView, float[] recycle)642     private float[] getDragViewVisualCenter(int x, int y, int xOffset, int yOffset,
643             DragView dragView, float[] recycle) {
644         float res[];
645         if (recycle == null) {
646             res = new float[2];
647         } else {
648             res = recycle;
649         }
650 
651         // These represent the visual top and left of drag view if a dragRect was provided.
652         // If a dragRect was not provided, then they correspond to the actual view left and
653         // top, as the dragRect is in that case taken to be the entire dragView.
654         // R.dimen.dragViewOffsetY.
655         int left = x - xOffset;
656         int top = y - yOffset;
657 
658         // In order to find the visual center, we shift by half the dragRect
659         res[0] = left + dragView.getDragRegion().width() / 2;
660         res[1] = top + dragView.getDragRegion().height() / 2;
661 
662         return res;
663     }
664 
665     OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
666         public void onAlarm(Alarm alarm) {
667             completeDragExit();
668         }
669     };
670 
completeDragExit()671     public void completeDragExit() {
672         mLauncher.closeFolder();
673         mCurrentDragInfo = null;
674         mCurrentDragView = null;
675         mSuppressOnAdd = false;
676         mRearrangeOnClose = true;
677     }
678 
onDragExit(DragObject d)679     public void onDragExit(DragObject d) {
680         // We only close the folder if this is a true drag exit, ie. not because a drop
681         // has occurred above the folder.
682         if (!d.dragComplete) {
683             mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener);
684             mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
685         }
686         mReorderAlarm.cancelAlarm();
687     }
688 
onDropCompleted(View target, DragObject d, boolean isFlingToDelete, boolean success)689     public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
690             boolean success) {
691         if (success) {
692             if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon) {
693                 replaceFolderWithFinalItem();
694             }
695         } else {
696             setupContentForNumItems(getItemCount());
697             // The drag failed, we need to return the item to the folder
698             mFolderIcon.onDrop(d);
699         }
700 
701         if (target != this) {
702             if (mOnExitAlarm.alarmPending()) {
703                 mOnExitAlarm.cancelAlarm();
704                 if (!success) {
705                     mSuppressFolderDeletion = true;
706                 }
707                 completeDragExit();
708             }
709         }
710 
711         mDeleteFolderOnDropCompleted = false;
712         mDragInProgress = false;
713         mItemAddedBackToSelfViaIcon = false;
714         mCurrentDragInfo = null;
715         mCurrentDragView = null;
716         mSuppressOnAdd = false;
717 
718         // Reordering may have occured, and we need to save the new item locations. We do this once
719         // at the end to prevent unnecessary database operations.
720         updateItemLocationsInDatabase();
721     }
722 
723     @Override
supportsFlingToDelete()724     public boolean supportsFlingToDelete() {
725         return true;
726     }
727 
onFlingToDelete(DragObject d, int x, int y, PointF vec)728     public void onFlingToDelete(DragObject d, int x, int y, PointF vec) {
729         // Do nothing
730     }
731 
732     @Override
onFlingToDeleteCompleted()733     public void onFlingToDeleteCompleted() {
734         // Do nothing
735     }
736 
updateItemLocationsInDatabase()737     private void updateItemLocationsInDatabase() {
738         ArrayList<View> list = getItemsInReadingOrder();
739         for (int i = 0; i < list.size(); i++) {
740             View v = list.get(i);
741             ItemInfo info = (ItemInfo) v.getTag();
742             LauncherModel.moveItemInDatabase(mLauncher, info, mInfo.id, 0,
743                         info.cellX, info.cellY);
744         }
745     }
746 
notifyDrop()747     public void notifyDrop() {
748         if (mDragInProgress) {
749             mItemAddedBackToSelfViaIcon = true;
750         }
751     }
752 
isDropEnabled()753     public boolean isDropEnabled() {
754         return true;
755     }
756 
getDropTargetDelegate(DragObject d)757     public DropTarget getDropTargetDelegate(DragObject d) {
758         return null;
759     }
760 
setupContentDimensions(int count)761     private void setupContentDimensions(int count) {
762         ArrayList<View> list = getItemsInReadingOrder();
763 
764         int countX = mContent.getCountX();
765         int countY = mContent.getCountY();
766         boolean done = false;
767 
768         while (!done) {
769             int oldCountX = countX;
770             int oldCountY = countY;
771             if (countX * countY < count) {
772                 // Current grid is too small, expand it
773                 if ((countX <= countY || countY == mMaxCountY) && countX < mMaxCountX) {
774                     countX++;
775                 } else if (countY < mMaxCountY) {
776                     countY++;
777                 }
778                 if (countY == 0) countY++;
779             } else if ((countY - 1) * countX >= count && countY >= countX) {
780                 countY = Math.max(0, countY - 1);
781             } else if ((countX - 1) * countY >= count) {
782                 countX = Math.max(0, countX - 1);
783             }
784             done = countX == oldCountX && countY == oldCountY;
785         }
786         mContent.setGridSize(countX, countY);
787         arrangeChildren(list);
788     }
789 
isFull()790     public boolean isFull() {
791         return getItemCount() >= mMaxNumItems;
792     }
793 
centerAboutIcon()794     private void centerAboutIcon() {
795         DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
796 
797         int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
798         int height = getPaddingTop() + getPaddingBottom() + mContent.getDesiredHeight()
799                 + mFolderNameHeight;
800         DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
801 
802         float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, mTempRect);
803 
804         int centerX = (int) (mTempRect.left + mTempRect.width() * scale / 2);
805         int centerY = (int) (mTempRect.top + mTempRect.height() * scale / 2);
806         int centeredLeft = centerX - width / 2;
807         int centeredTop = centerY - height / 2;
808 
809         int currentPage = mLauncher.getWorkspace().getCurrentPage();
810         // In case the workspace is scrolling, we need to use the final scroll to compute
811         // the folders bounds.
812         mLauncher.getWorkspace().setFinalScrollForPageChange(currentPage);
813         // We first fetch the currently visible CellLayoutChildren
814         CellLayout currentLayout = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPage);
815         ShortcutAndWidgetContainer boundingLayout = currentLayout.getShortcutsAndWidgets();
816         Rect bounds = new Rect();
817         parent.getDescendantRectRelativeToSelf(boundingLayout, bounds);
818         // We reset the workspaces scroll
819         mLauncher.getWorkspace().resetFinalScrollForPageChange(currentPage);
820 
821         // We need to bound the folder to the currently visible CellLayoutChildren
822         int left = Math.min(Math.max(bounds.left, centeredLeft),
823                 bounds.left + bounds.width() - width);
824         int top = Math.min(Math.max(bounds.top, centeredTop),
825                 bounds.top + bounds.height() - height);
826         // If the folder doesn't fit within the bounds, center it about the desired bounds
827         if (width >= bounds.width()) {
828             left = bounds.left + (bounds.width() - width) / 2;
829         }
830         if (height >= bounds.height()) {
831             top = bounds.top + (bounds.height() - height) / 2;
832         }
833 
834         int folderPivotX = width / 2 + (centeredLeft - left);
835         int folderPivotY = height / 2 + (centeredTop - top);
836         setPivotX(folderPivotX);
837         setPivotY(folderPivotY);
838         mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() *
839                 (1.0f * folderPivotX / width));
840         mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() *
841                 (1.0f * folderPivotY / height));
842 
843         lp.width = width;
844         lp.height = height;
845         lp.x = left;
846         lp.y = top;
847     }
848 
getPivotXForIconAnimation()849     float getPivotXForIconAnimation() {
850         return mFolderIconPivotX;
851     }
getPivotYForIconAnimation()852     float getPivotYForIconAnimation() {
853         return mFolderIconPivotY;
854     }
855 
setupContentForNumItems(int count)856     private void setupContentForNumItems(int count) {
857         setupContentDimensions(count);
858 
859         DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
860         if (lp == null) {
861             lp = new DragLayer.LayoutParams(0, 0);
862             lp.customPosition = true;
863             setLayoutParams(lp);
864         }
865         centerAboutIcon();
866     }
867 
onMeasure(int widthMeasureSpec, int heightMeasureSpec)868     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
869         int width = getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
870         int height = getPaddingTop() + getPaddingBottom() + mContent.getDesiredHeight()
871                 + mFolderNameHeight;
872 
873         int contentWidthSpec = MeasureSpec.makeMeasureSpec(mContent.getDesiredWidth(),
874                 MeasureSpec.EXACTLY);
875         int contentHeightSpec = MeasureSpec.makeMeasureSpec(mContent.getDesiredHeight(),
876                 MeasureSpec.EXACTLY);
877         mContent.measure(contentWidthSpec, contentHeightSpec);
878 
879         mFolderName.measure(contentWidthSpec,
880                 MeasureSpec.makeMeasureSpec(mFolderNameHeight, MeasureSpec.EXACTLY));
881         setMeasuredDimension(width, height);
882     }
883 
arrangeChildren(ArrayList<View> list)884     private void arrangeChildren(ArrayList<View> list) {
885         int[] vacant = new int[2];
886         if (list == null) {
887             list = getItemsInReadingOrder();
888         }
889         mContent.removeAllViews();
890 
891         for (int i = 0; i < list.size(); i++) {
892             View v = list.get(i);
893             mContent.getVacantCell(vacant, 1, 1);
894             CellLayout.LayoutParams lp = (CellLayout.LayoutParams) v.getLayoutParams();
895             lp.cellX = vacant[0];
896             lp.cellY = vacant[1];
897             ItemInfo info = (ItemInfo) v.getTag();
898             if (info.cellX != vacant[0] || info.cellY != vacant[1]) {
899                 info.cellX = vacant[0];
900                 info.cellY = vacant[1];
901                 LauncherModel.addOrMoveItemInDatabase(mLauncher, info, mInfo.id, 0,
902                         info.cellX, info.cellY);
903             }
904             boolean insert = false;
905             mContent.addViewToCellLayout(v, insert ? 0 : -1, (int)info.id, lp, true);
906         }
907         mItemsInvalidated = true;
908     }
909 
getItemCount()910     public int getItemCount() {
911         return mContent.getShortcutsAndWidgets().getChildCount();
912     }
913 
getItemAt(int index)914     public View getItemAt(int index) {
915         return mContent.getShortcutsAndWidgets().getChildAt(index);
916     }
917 
onCloseComplete()918     private void onCloseComplete() {
919         DragLayer parent = (DragLayer) getParent();
920         if (parent != null) {
921             parent.removeView(this);
922         }
923         mDragController.removeDropTarget((DropTarget) this);
924         clearFocus();
925         mFolderIcon.requestFocus();
926 
927         if (mRearrangeOnClose) {
928             setupContentForNumItems(getItemCount());
929             mRearrangeOnClose = false;
930         }
931         if (getItemCount() <= 1) {
932             if (!mDragInProgress && !mSuppressFolderDeletion) {
933                 replaceFolderWithFinalItem();
934             } else if (mDragInProgress) {
935                 mDeleteFolderOnDropCompleted = true;
936             }
937         }
938         mSuppressFolderDeletion = false;
939     }
940 
replaceFolderWithFinalItem()941     private void replaceFolderWithFinalItem() {
942         // Add the last remaining child to the workspace in place of the folder
943         Runnable onCompleteRunnable = new Runnable() {
944             @Override
945             public void run() {
946                 CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container, mInfo.screen);
947 
948                View child = null;
949                 // Move the item from the folder to the workspace, in the position of the folder
950                 if (getItemCount() == 1) {
951                     ShortcutInfo finalItem = mInfo.contents.get(0);
952                     child = mLauncher.createShortcut(R.layout.application, cellLayout,
953                             finalItem);
954                     LauncherModel.addOrMoveItemInDatabase(mLauncher, finalItem, mInfo.container,
955                             mInfo.screen, mInfo.cellX, mInfo.cellY);
956                 }
957                 if (getItemCount() <= 1) {
958                     // Remove the folder
959                     LauncherModel.deleteItemFromDatabase(mLauncher, mInfo);
960                     cellLayout.removeView(mFolderIcon);
961                     if (mFolderIcon instanceof DropTarget) {
962                         mDragController.removeDropTarget((DropTarget) mFolderIcon);
963                     }
964                     mLauncher.removeFolder(mInfo);
965                 }
966                 // We add the child after removing the folder to prevent both from existing at
967                 // the same time in the CellLayout.
968                 if (child != null) {
969                     mLauncher.getWorkspace().addInScreen(child, mInfo.container, mInfo.screen,
970                             mInfo.cellX, mInfo.cellY, mInfo.spanX, mInfo.spanY);
971                 }
972             }
973         };
974         View finalChild = getItemAt(0);
975         if (finalChild != null) {
976             mFolderIcon.performDestroyAnimation(finalChild, onCompleteRunnable);
977         }
978         mDestroyed = true;
979     }
980 
isDestroyed()981     boolean isDestroyed() {
982         return mDestroyed;
983     }
984 
985     // This method keeps track of the last item in the folder for the purposes
986     // of keyboard focus
updateTextViewFocus()987     private void updateTextViewFocus() {
988         View lastChild = getItemAt(getItemCount() - 1);
989         getItemAt(getItemCount() - 1);
990         if (lastChild != null) {
991             mFolderName.setNextFocusDownId(lastChild.getId());
992             mFolderName.setNextFocusRightId(lastChild.getId());
993             mFolderName.setNextFocusLeftId(lastChild.getId());
994             mFolderName.setNextFocusUpId(lastChild.getId());
995         }
996     }
997 
onDrop(DragObject d)998     public void onDrop(DragObject d) {
999         ShortcutInfo item;
1000         if (d.dragInfo instanceof ApplicationInfo) {
1001             // Came from all apps -- make a copy
1002             item = ((ApplicationInfo) d.dragInfo).makeShortcut();
1003             item.spanX = 1;
1004             item.spanY = 1;
1005         } else {
1006             item = (ShortcutInfo) d.dragInfo;
1007         }
1008         // Dragged from self onto self, currently this is the only path possible, however
1009         // we keep this as a distinct code path.
1010         if (item == mCurrentDragInfo) {
1011             ShortcutInfo si = (ShortcutInfo) mCurrentDragView.getTag();
1012             CellLayout.LayoutParams lp = (CellLayout.LayoutParams) mCurrentDragView.getLayoutParams();
1013             si.cellX = lp.cellX = mEmptyCell[0];
1014             si.cellX = lp.cellY = mEmptyCell[1];
1015             mContent.addViewToCellLayout(mCurrentDragView, -1, (int)item.id, lp, true);
1016             if (d.dragView.hasDrawn()) {
1017                 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, mCurrentDragView);
1018             } else {
1019                 d.deferDragViewCleanupPostAnimation = false;
1020                 mCurrentDragView.setVisibility(VISIBLE);
1021             }
1022             mItemsInvalidated = true;
1023             setupContentDimensions(getItemCount());
1024             mSuppressOnAdd = true;
1025         }
1026         mInfo.add(item);
1027     }
1028 
1029     // This is used so the item doesn't immediately appear in the folder when added. In one case
1030     // we need to create the illusion that the item isn't added back to the folder yet, to
1031     // to correspond to the animation of the icon back into the folder. This is
hideItem(ShortcutInfo info)1032     public void hideItem(ShortcutInfo info) {
1033         View v = getViewForInfo(info);
1034         v.setVisibility(INVISIBLE);
1035     }
showItem(ShortcutInfo info)1036     public void showItem(ShortcutInfo info) {
1037         View v = getViewForInfo(info);
1038         v.setVisibility(VISIBLE);
1039     }
1040 
onAdd(ShortcutInfo item)1041     public void onAdd(ShortcutInfo item) {
1042         mItemsInvalidated = true;
1043         // If the item was dropped onto this open folder, we have done the work associated
1044         // with adding the item to the folder, as indicated by mSuppressOnAdd being set
1045         if (mSuppressOnAdd) return;
1046         if (!findAndSetEmptyCells(item)) {
1047             // The current layout is full, can we expand it?
1048             setupContentForNumItems(getItemCount() + 1);
1049             findAndSetEmptyCells(item);
1050         }
1051         createAndAddShortcut(item);
1052         LauncherModel.addOrMoveItemInDatabase(
1053                 mLauncher, item, mInfo.id, 0, item.cellX, item.cellY);
1054     }
1055 
onRemove(ShortcutInfo item)1056     public void onRemove(ShortcutInfo item) {
1057         mItemsInvalidated = true;
1058         // If this item is being dragged from this open folder, we have already handled
1059         // the work associated with removing the item, so we don't have to do anything here.
1060         if (item == mCurrentDragInfo) return;
1061         View v = getViewForInfo(item);
1062         mContent.removeView(v);
1063         if (mState == STATE_ANIMATING) {
1064             mRearrangeOnClose = true;
1065         } else {
1066             setupContentForNumItems(getItemCount());
1067         }
1068         if (getItemCount() <= 1) {
1069             replaceFolderWithFinalItem();
1070         }
1071     }
1072 
getViewForInfo(ShortcutInfo item)1073     private View getViewForInfo(ShortcutInfo item) {
1074         for (int j = 0; j < mContent.getCountY(); j++) {
1075             for (int i = 0; i < mContent.getCountX(); i++) {
1076                 View v = mContent.getChildAt(i, j);
1077                 if (v.getTag() == item) {
1078                     return v;
1079                 }
1080             }
1081         }
1082         return null;
1083     }
1084 
onItemsChanged()1085     public void onItemsChanged() {
1086         updateTextViewFocus();
1087     }
1088 
onTitleChanged(CharSequence title)1089     public void onTitleChanged(CharSequence title) {
1090     }
1091 
getItemsInReadingOrder()1092     public ArrayList<View> getItemsInReadingOrder() {
1093         if (mItemsInvalidated) {
1094             mItemsInReadingOrder.clear();
1095             for (int j = 0; j < mContent.getCountY(); j++) {
1096                 for (int i = 0; i < mContent.getCountX(); i++) {
1097                     View v = mContent.getChildAt(i, j);
1098                     if (v != null) {
1099                         mItemsInReadingOrder.add(v);
1100                     }
1101                 }
1102             }
1103             mItemsInvalidated = false;
1104         }
1105         return mItemsInReadingOrder;
1106     }
1107 
getLocationInDragLayer(int[] loc)1108     public void getLocationInDragLayer(int[] loc) {
1109         mLauncher.getDragLayer().getLocationInDragLayer(this, loc);
1110     }
1111 
onFocusChange(View v, boolean hasFocus)1112     public void onFocusChange(View v, boolean hasFocus) {
1113         if (v == mFolderName && hasFocus) {
1114             startEditingFolderName();
1115         }
1116     }
1117 }
1118