Home | History | Annotate | Download | only in folder
      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.launcher3.folder;
     18 
     19 import android.animation.Animator;
     20 import android.animation.AnimatorListenerAdapter;
     21 import android.animation.AnimatorSet;
     22 import android.animation.ObjectAnimator;
     23 import android.animation.PropertyValuesHolder;
     24 import android.annotation.SuppressLint;
     25 import android.content.Context;
     26 import android.content.res.Resources;
     27 import android.graphics.Rect;
     28 import android.text.InputType;
     29 import android.text.Selection;
     30 import android.util.AttributeSet;
     31 import android.util.Log;
     32 import android.view.ActionMode;
     33 import android.view.FocusFinder;
     34 import android.view.KeyEvent;
     35 import android.view.Menu;
     36 import android.view.MenuItem;
     37 import android.view.View;
     38 import android.view.ViewDebug;
     39 import android.view.accessibility.AccessibilityEvent;
     40 import android.view.animation.AccelerateInterpolator;
     41 import android.view.animation.AnimationUtils;
     42 import android.view.inputmethod.EditorInfo;
     43 import android.widget.TextView;
     44 
     45 import com.android.launcher3.AbstractFloatingView;
     46 import com.android.launcher3.Alarm;
     47 import com.android.launcher3.AppInfo;
     48 import com.android.launcher3.BubbleTextView;
     49 import com.android.launcher3.CellLayout;
     50 import com.android.launcher3.DeviceProfile;
     51 import com.android.launcher3.DragSource;
     52 import com.android.launcher3.DropTarget;
     53 import com.android.launcher3.ExtendedEditText;
     54 import com.android.launcher3.FolderInfo;
     55 import com.android.launcher3.FolderInfo.FolderListener;
     56 import com.android.launcher3.ItemInfo;
     57 import com.android.launcher3.Launcher;
     58 import com.android.launcher3.LauncherAnimUtils;
     59 import com.android.launcher3.LauncherSettings;
     60 import com.android.launcher3.LogDecelerateInterpolator;
     61 import com.android.launcher3.OnAlarmListener;
     62 import com.android.launcher3.PagedView;
     63 import com.android.launcher3.R;
     64 import com.android.launcher3.ShortcutInfo;
     65 import com.android.launcher3.UninstallDropTarget.DropTargetSource;
     66 import com.android.launcher3.Utilities;
     67 import com.android.launcher3.Workspace.ItemOperator;
     68 import com.android.launcher3.accessibility.AccessibleDragListenerAdapter;
     69 import com.android.launcher3.anim.AnimationLayerSet;
     70 import com.android.launcher3.anim.CircleRevealOutlineProvider;
     71 import com.android.launcher3.config.FeatureFlags;
     72 import com.android.launcher3.dragndrop.DragController;
     73 import com.android.launcher3.dragndrop.DragController.DragListener;
     74 import com.android.launcher3.dragndrop.DragLayer;
     75 import com.android.launcher3.dragndrop.DragOptions;
     76 import com.android.launcher3.pageindicators.PageIndicatorDots;
     77 import com.android.launcher3.userevent.nano.LauncherLogProto.ContainerType;
     78 import com.android.launcher3.userevent.nano.LauncherLogProto.Target;
     79 import com.android.launcher3.util.Thunk;
     80 import com.android.launcher3.widget.PendingAddShortcutInfo;
     81 
     82 import java.util.ArrayList;
     83 import java.util.Collections;
     84 import java.util.Comparator;
     85 import java.util.List;
     86 
     87 /**
     88  * Represents a set of icons chosen by the user or generated by the system.
     89  */
     90 public class Folder extends AbstractFloatingView implements DragSource, View.OnClickListener,
     91         View.OnLongClickListener, DropTarget, FolderListener, TextView.OnEditorActionListener,
     92         View.OnFocusChangeListener, DragListener, DropTargetSource,
     93         ExtendedEditText.OnBackKeyListener {
     94     private static final String TAG = "Launcher.Folder";
     95 
     96     /**
     97      * We avoid measuring {@link #mContent} with a 0 width or height, as this
     98      * results in CellLayout being measured as UNSPECIFIED, which it does not support.
     99      */
    100     private static final int MIN_CONTENT_DIMEN = 5;
    101 
    102     static final int STATE_NONE = -1;
    103     static final int STATE_SMALL = 0;
    104     static final int STATE_ANIMATING = 1;
    105     static final int STATE_OPEN = 2;
    106 
    107     /**
    108      * Time for which the scroll hint is shown before automatically changing page.
    109      */
    110     public static final int SCROLL_HINT_DURATION = 500;
    111     public static final int RESCROLL_DELAY = PagedView.PAGE_SNAP_ANIMATION_DURATION + 150;
    112 
    113     public static final int SCROLL_NONE = -1;
    114     public static final int SCROLL_LEFT = 0;
    115     public static final int SCROLL_RIGHT = 1;
    116 
    117     /**
    118      * Fraction of icon width which behave as scroll region.
    119      */
    120     private static final float ICON_OVERSCROLL_WIDTH_FACTOR = 0.45f;
    121 
    122     private static final int FOLDER_NAME_ANIMATION_DURATION = 633;
    123 
    124     private static final int REORDER_DELAY = 250;
    125     private static final int ON_EXIT_CLOSE_DELAY = 400;
    126     private static final Rect sTempRect = new Rect();
    127 
    128     private static String sDefaultFolderName;
    129     private static String sHintText;
    130 
    131     private final Alarm mReorderAlarm = new Alarm();
    132     private final Alarm mOnExitAlarm = new Alarm();
    133     private final Alarm mOnScrollHintAlarm = new Alarm();
    134     @Thunk final Alarm mScrollPauseAlarm = new Alarm();
    135 
    136     @Thunk final ArrayList<View> mItemsInReadingOrder = new ArrayList<View>();
    137 
    138     private AnimatorSet mCurrentAnimator;
    139 
    140     private final int mExpandDuration;
    141     public final int mMaterialExpandDuration;
    142     private final int mMaterialExpandStagger;
    143 
    144     protected final Launcher mLauncher;
    145     protected DragController mDragController;
    146     public FolderInfo mInfo;
    147 
    148     @Thunk FolderIcon mFolderIcon;
    149 
    150     @Thunk FolderPagedView mContent;
    151     public ExtendedEditText mFolderName;
    152     private PageIndicatorDots mPageIndicator;
    153 
    154     private View mFooter;
    155     private int mFooterHeight;
    156 
    157     // Cell ranks used for drag and drop
    158     @Thunk int mTargetRank, mPrevTargetRank, mEmptyCellRank;
    159 
    160     @ViewDebug.ExportedProperty(category = "launcher",
    161             mapping = {
    162                     @ViewDebug.IntToString(from = STATE_NONE, to = "STATE_NONE"),
    163                     @ViewDebug.IntToString(from = STATE_SMALL, to = "STATE_SMALL"),
    164                     @ViewDebug.IntToString(from = STATE_ANIMATING, to = "STATE_ANIMATING"),
    165                     @ViewDebug.IntToString(from = STATE_OPEN, to = "STATE_OPEN"),
    166             })
    167     @Thunk int mState = STATE_NONE;
    168     @ViewDebug.ExportedProperty(category = "launcher")
    169     private boolean mRearrangeOnClose = false;
    170     boolean mItemsInvalidated = false;
    171     private View mCurrentDragView;
    172     private boolean mIsExternalDrag;
    173     private boolean mDragInProgress = false;
    174     private boolean mDeleteFolderOnDropCompleted = false;
    175     private boolean mSuppressFolderDeletion = false;
    176     private boolean mItemAddedBackToSelfViaIcon = false;
    177     @Thunk float mFolderIconPivotX;
    178     @Thunk float mFolderIconPivotY;
    179     private boolean mIsEditingName = false;
    180 
    181     @ViewDebug.ExportedProperty(category = "launcher")
    182     private boolean mDestroyed;
    183 
    184     @Thunk Runnable mDeferredAction;
    185     private boolean mDeferDropAfterUninstall;
    186     private boolean mUninstallSuccessful;
    187 
    188     // Folder scrolling
    189     private int mScrollAreaOffset;
    190 
    191     @Thunk int mScrollHintDir = SCROLL_NONE;
    192     @Thunk int mCurrentScrollDir = SCROLL_NONE;
    193 
    194     /**
    195      * Used to inflate the Workspace from XML.
    196      *
    197      * @param context The application's context.
    198      * @param attrs The attributes set containing the Workspace's customization values.
    199      */
    200     public Folder(Context context, AttributeSet attrs) {
    201         super(context, attrs);
    202         setAlwaysDrawnWithCacheEnabled(false);
    203         Resources res = getResources();
    204         mExpandDuration = res.getInteger(R.integer.config_folderExpandDuration);
    205         mMaterialExpandDuration = res.getInteger(R.integer.config_materialFolderExpandDuration);
    206         mMaterialExpandStagger = res.getInteger(R.integer.config_materialFolderExpandStagger);
    207 
    208         if (sDefaultFolderName == null) {
    209             sDefaultFolderName = res.getString(R.string.folder_name);
    210         }
    211         if (sHintText == null) {
    212             sHintText = res.getString(R.string.folder_hint_text);
    213         }
    214         mLauncher = Launcher.getLauncher(context);
    215         // We need this view to be focusable in touch mode so that when text editing of the folder
    216         // name is complete, we have something to focus on, thus hiding the cursor and giving
    217         // reliable behavior when clicking the text field (since it will always gain focus on click).
    218         setFocusableInTouchMode(true);
    219     }
    220 
    221     @Override
    222     protected void onFinishInflate() {
    223         super.onFinishInflate();
    224         mContent = (FolderPagedView) findViewById(R.id.folder_content);
    225         mContent.setFolder(this);
    226 
    227         mPageIndicator = (PageIndicatorDots) findViewById(R.id.folder_page_indicator);
    228         mFolderName = (ExtendedEditText) findViewById(R.id.folder_name);
    229         mFolderName.setOnBackKeyListener(this);
    230         mFolderName.setOnFocusChangeListener(this);
    231 
    232         if (!Utilities.ATLEAST_MARSHMALLOW) {
    233             // We disable action mode in older OSes where floating selection menu is not yet
    234             // available.
    235             mFolderName.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
    236                 public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
    237                     return false;
    238                 }
    239 
    240                 public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    241                     return false;
    242                 }
    243 
    244                 public void onDestroyActionMode(ActionMode mode) {
    245                 }
    246 
    247                 public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    248                     return false;
    249                 }
    250             });
    251         }
    252         mFolderName.setOnEditorActionListener(this);
    253         mFolderName.setSelectAllOnFocus(true);
    254         mFolderName.setInputType(mFolderName.getInputType()
    255                 & ~InputType.TYPE_TEXT_FLAG_AUTO_CORRECT
    256                 & ~InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
    257                 | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
    258         mFolderName.forceDisableSuggestions(true);
    259 
    260         mFooter = findViewById(R.id.folder_footer);
    261 
    262         // We find out how tall footer wants to be (it is set to wrap_content), so that
    263         // we can allocate the appropriate amount of space for it.
    264         int measureSpec = MeasureSpec.UNSPECIFIED;
    265         mFooter.measure(measureSpec, measureSpec);
    266         mFooterHeight = mFooter.getMeasuredHeight();
    267     }
    268 
    269     public void onClick(View v) {
    270         Object tag = v.getTag();
    271         if (tag instanceof ShortcutInfo) {
    272             mLauncher.onClick(v);
    273         }
    274     }
    275 
    276     public boolean onLongClick(View v) {
    277         // Return if global dragging is not enabled
    278         if (!mLauncher.isDraggingEnabled()) return true;
    279         return startDrag(v, new DragOptions());
    280     }
    281 
    282     public boolean startDrag(View v, DragOptions options) {
    283         Object tag = v.getTag();
    284         if (tag instanceof ShortcutInfo) {
    285             ShortcutInfo item = (ShortcutInfo) tag;
    286 
    287             mEmptyCellRank = item.rank;
    288             mCurrentDragView = v;
    289 
    290             mDragController.addDragListener(this);
    291             if (options.isAccessibleDrag) {
    292                 mDragController.addDragListener(new AccessibleDragListenerAdapter(
    293                         mContent, CellLayout.FOLDER_ACCESSIBILITY_DRAG) {
    294 
    295                     @Override
    296                     protected void enableAccessibleDrag(boolean enable) {
    297                         super.enableAccessibleDrag(enable);
    298                         mFooter.setImportantForAccessibility(enable
    299                                 ? IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
    300                                 : IMPORTANT_FOR_ACCESSIBILITY_AUTO);
    301                     }
    302                 });
    303             }
    304 
    305             mLauncher.getWorkspace().beginDragShared(v, this, options);
    306         }
    307         return true;
    308     }
    309 
    310     @Override
    311     public void onDragStart(DropTarget.DragObject dragObject, DragOptions options) {
    312         if (dragObject.dragSource != this) {
    313             return;
    314         }
    315 
    316         mContent.removeItem(mCurrentDragView);
    317         if (dragObject.dragInfo instanceof ShortcutInfo) {
    318             mItemsInvalidated = true;
    319 
    320             // We do not want to get events for the item being removed, as they will get handled
    321             // when the drop completes
    322             try (SuppressInfoChanges s = new SuppressInfoChanges()) {
    323                 mInfo.remove((ShortcutInfo) dragObject.dragInfo, true);
    324             }
    325         }
    326         mDragInProgress = true;
    327         mItemAddedBackToSelfViaIcon = false;
    328     }
    329 
    330     @Override
    331     public void onDragEnd() {
    332         if (mIsExternalDrag && mDragInProgress) {
    333             completeDragExit();
    334         }
    335         mDragInProgress = false;
    336         mDragController.removeDragListener(this);
    337     }
    338 
    339     public boolean isEditingName() {
    340         return mIsEditingName;
    341     }
    342 
    343     public void startEditingFolderName() {
    344         post(new Runnable() {
    345             @Override
    346             public void run() {
    347                 mFolderName.setHint("");
    348                 mIsEditingName = true;
    349             }
    350         });
    351     }
    352 
    353 
    354     @Override
    355     public boolean onBackKey() {
    356         // Convert to a string here to ensure that no other state associated with the text field
    357         // gets saved.
    358         String newTitle = mFolderName.getText().toString();
    359         mInfo.setTitle(newTitle);
    360         mLauncher.getModelWriter().updateItemInDatabase(mInfo);
    361 
    362         mFolderName.setHint(sDefaultFolderName.contentEquals(newTitle) ? sHintText : null);
    363 
    364         Utilities.sendCustomAccessibilityEvent(
    365                 this, AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
    366                 getContext().getString(R.string.folder_renamed, newTitle));
    367 
    368         // This ensures that focus is gained every time the field is clicked, which selects all
    369         // the text and brings up the soft keyboard if necessary.
    370         mFolderName.clearFocus();
    371 
    372         Selection.setSelection(mFolderName.getText(), 0, 0);
    373         mIsEditingName = false;
    374         return true;
    375     }
    376 
    377     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    378         if (actionId == EditorInfo.IME_ACTION_DONE) {
    379             mFolderName.dispatchBackKey();
    380             return true;
    381         }
    382         return false;
    383     }
    384 
    385     @Override
    386     public ExtendedEditText getActiveTextView() {
    387         return isEditingName() ? mFolderName : null;
    388     }
    389 
    390     public FolderIcon getFolderIcon() {
    391         return mFolderIcon;
    392     }
    393 
    394     public void setDragController(DragController dragController) {
    395         mDragController = dragController;
    396     }
    397 
    398     public void setFolderIcon(FolderIcon icon) {
    399         mFolderIcon = icon;
    400     }
    401 
    402     @Override
    403     protected void onAttachedToWindow() {
    404         // requestFocus() causes the focus onto the folder itself, which doesn't cause visual
    405         // effect but the next arrow key can start the keyboard focus inside of the folder, not
    406         // the folder itself.
    407         requestFocus();
    408         super.onAttachedToWindow();
    409     }
    410 
    411     @Override
    412     public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
    413         // When the folder gets focus, we don't want to announce the list of items.
    414         return true;
    415     }
    416 
    417     @Override
    418     public View focusSearch(int direction) {
    419         // When the folder is focused, further focus search should be within the folder contents.
    420         return FocusFinder.getInstance().findNextFocus(this, null, direction);
    421     }
    422 
    423     /**
    424      * @return the FolderInfo object associated with this folder
    425      */
    426     public FolderInfo getInfo() {
    427         return mInfo;
    428     }
    429 
    430     void bind(FolderInfo info) {
    431         mInfo = info;
    432         ArrayList<ShortcutInfo> children = info.contents;
    433         Collections.sort(children, ITEM_POS_COMPARATOR);
    434 
    435         ArrayList<ShortcutInfo> overflow = mContent.bindItems(children);
    436 
    437         // If our folder has too many items we prune them from the list. This is an issue
    438         // when upgrading from the old Folders implementation which could contain an unlimited
    439         // number of items.
    440         // TODO: Remove this, as with multi-page folders, there will never be any overflow
    441         for (ShortcutInfo item: overflow) {
    442             mInfo.remove(item, false);
    443             mLauncher.getModelWriter().deleteItemFromDatabase(item);
    444         }
    445 
    446         DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
    447         if (lp == null) {
    448             lp = new DragLayer.LayoutParams(0, 0);
    449             lp.customPosition = true;
    450             setLayoutParams(lp);
    451         }
    452         centerAboutIcon();
    453 
    454         mItemsInvalidated = true;
    455         updateTextViewFocus();
    456         mInfo.addListener(this);
    457 
    458         if (!sDefaultFolderName.contentEquals(mInfo.title)) {
    459             mFolderName.setText(mInfo.title);
    460             mFolderName.setHint(null);
    461         } else {
    462             mFolderName.setText("");
    463             mFolderName.setHint(sHintText);
    464         }
    465 
    466         // In case any children didn't come across during loading, clean up the folder accordingly
    467         mFolderIcon.post(new Runnable() {
    468             public void run() {
    469                 if (getItemCount() <= 1) {
    470                     replaceFolderWithFinalItem();
    471                 }
    472             }
    473         });
    474     }
    475 
    476     /**
    477      * Creates a new UserFolder, inflated from R.layout.user_folder.
    478      *
    479      * @param launcher The main activity.
    480      *
    481      * @return A new UserFolder.
    482      */
    483     @SuppressLint("InflateParams")
    484     static Folder fromXml(Launcher launcher) {
    485         return (Folder) launcher.getLayoutInflater().inflate(
    486                 FeatureFlags.LAUNCHER3_DISABLE_ICON_NORMALIZATION
    487                         ? R.layout.user_folder : R.layout.user_folder_icon_normalized, null);
    488     }
    489 
    490     /**
    491      * This method is intended to make the UserFolder to be visually identical in size and position
    492      * to its associated FolderIcon. This allows for a seamless transition into the expanded state.
    493      */
    494     private void positionAndSizeAsIcon() {
    495         if (!(getParent() instanceof DragLayer)) return;
    496         setScaleX(0.8f);
    497         setScaleY(0.8f);
    498         setAlpha(0f);
    499         mState = STATE_SMALL;
    500     }
    501 
    502     private void prepareReveal() {
    503         setScaleX(1f);
    504         setScaleY(1f);
    505         setAlpha(1f);
    506         mState = STATE_SMALL;
    507     }
    508 
    509     private void startAnimation(final AnimatorSet a) {
    510         if (mCurrentAnimator != null && mCurrentAnimator.isRunning()) {
    511             mCurrentAnimator.cancel();
    512         }
    513         a.addListener(new AnimatorListenerAdapter() {
    514             @Override
    515             public void onAnimationStart(Animator animation) {
    516                 mState = STATE_ANIMATING;
    517                 mCurrentAnimator = a;
    518             }
    519 
    520             @Override
    521             public void onAnimationEnd(Animator animation) {
    522                 mCurrentAnimator = null;
    523             }
    524         });
    525         a.start();
    526     }
    527 
    528     private AnimatorSet getOpeningAnimator() {
    529         prepareReveal();
    530         mFolderIcon.growAndFadeOut();
    531 
    532         AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
    533 
    534         int width = getFolderWidth();
    535         int height = getFolderHeight();
    536 
    537         float transX = - 0.075f * (width / 2 - getPivotX());
    538         float transY = - 0.075f * (height / 2 - getPivotY());
    539         setTranslationX(transX);
    540         setTranslationY(transY);
    541         PropertyValuesHolder tx = PropertyValuesHolder.ofFloat(TRANSLATION_X, transX, 0);
    542         PropertyValuesHolder ty = PropertyValuesHolder.ofFloat(TRANSLATION_Y, transY, 0);
    543 
    544         Animator drift = ObjectAnimator.ofPropertyValuesHolder(this, tx, ty);
    545         drift.setDuration(mMaterialExpandDuration);
    546         drift.setStartDelay(mMaterialExpandStagger);
    547         drift.setInterpolator(new LogDecelerateInterpolator(100, 0));
    548 
    549         int rx = (int) Math.max(Math.max(width - getPivotX(), 0), getPivotX());
    550         int ry = (int) Math.max(Math.max(height - getPivotY(), 0), getPivotY());
    551         float radius = (float) Math.hypot(rx, ry);
    552 
    553         Animator reveal = new CircleRevealOutlineProvider((int) getPivotX(),
    554                 (int) getPivotY(), 0, radius).createRevealAnimator(this);
    555         reveal.setDuration(mMaterialExpandDuration);
    556         reveal.setInterpolator(new LogDecelerateInterpolator(100, 0));
    557 
    558         mContent.setAlpha(0f);
    559         Animator iconsAlpha = ObjectAnimator.ofFloat(mContent, "alpha", 0f, 1f);
    560         iconsAlpha.setDuration(mMaterialExpandDuration);
    561         iconsAlpha.setStartDelay(mMaterialExpandStagger);
    562         iconsAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
    563 
    564         mFooter.setAlpha(0f);
    565         Animator textAlpha = ObjectAnimator.ofFloat(mFooter, "alpha", 0f, 1f);
    566         textAlpha.setDuration(mMaterialExpandDuration);
    567         textAlpha.setStartDelay(mMaterialExpandStagger);
    568         textAlpha.setInterpolator(new AccelerateInterpolator(1.5f));
    569 
    570         anim.play(drift);
    571         anim.play(iconsAlpha);
    572         anim.play(textAlpha);
    573         anim.play(reveal);
    574 
    575         AnimationLayerSet layerSet = new AnimationLayerSet();
    576         layerSet.addView(mContent);
    577         layerSet.addView(mFooter);
    578         anim.addListener(layerSet);
    579 
    580         return anim;
    581     }
    582 
    583     /**
    584      * Opens the user folder described by the specified tag. The opening of the folder
    585      * is animated relative to the specified View. If the View is null, no animation
    586      * is played.
    587      */
    588     public void animateOpen() {
    589         Folder openFolder = getOpen(mLauncher);
    590         if (openFolder != null && openFolder != this) {
    591             // Close any open folder before opening a folder.
    592             openFolder.close(true);
    593         }
    594 
    595         DragLayer dragLayer = mLauncher.getDragLayer();
    596         // Just verify that the folder hasn't already been added to the DragLayer.
    597         // There was a one-off crash where the folder had a parent already.
    598         if (getParent() == null) {
    599             dragLayer.addView(this);
    600             mDragController.addDropTarget(this);
    601         } else {
    602             if (FeatureFlags.IS_DOGFOOD_BUILD) {
    603                 Log.e(TAG, "Opening folder (" + this + ") which already has a parent:"
    604                         + getParent());
    605             }
    606         }
    607 
    608         mIsOpen = true;
    609 
    610         mContent.completePendingPageChanges();
    611         if (!mDragInProgress) {
    612             // Open on the first page.
    613             mContent.snapToPageImmediately(0);
    614         }
    615 
    616         // This is set to true in close(), but isn't reset to false until onDropCompleted(). This
    617         // leads to an inconsistent state if you drag out of the folder and drag back in without
    618         // dropping. One resulting issue is that replaceFolderWithFinalItem() can be called twice.
    619         mDeleteFolderOnDropCompleted = false;
    620 
    621         final Runnable onCompleteRunnable;
    622         centerAboutIcon();
    623 
    624         AnimatorSet anim = FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION
    625                 ? new FolderAnimationManager(this, true /* isOpening */).getAnimator()
    626                 : getOpeningAnimator();
    627         onCompleteRunnable = new Runnable() {
    628             @Override
    629             public void run() {
    630                 mLauncher.getUserEventDispatcher().resetElapsedContainerMillis();
    631             }
    632         };
    633         anim.addListener(new AnimatorListenerAdapter() {
    634             @Override
    635             public void onAnimationStart(Animator animation) {
    636                 if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
    637                     mFolderIcon.setBackgroundVisible(false);
    638                     mFolderIcon.drawLeaveBehindIfExists();
    639                 } else {
    640                     mFolderIcon.setVisibility(INVISIBLE);
    641                 }
    642 
    643                 Utilities.sendCustomAccessibilityEvent(
    644                         Folder.this,
    645                         AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
    646                         mContent.getAccessibilityDescription());
    647             }
    648             @Override
    649             public void onAnimationEnd(Animator animation) {
    650                 mState = STATE_OPEN;
    651 
    652                 onCompleteRunnable.run();
    653                 mContent.setFocusOnFirstChild();
    654             }
    655         });
    656 
    657         // Footer animation
    658         if (mContent.getPageCount() > 1 && !mInfo.hasOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION)) {
    659             int footerWidth = mContent.getDesiredWidth()
    660                     - mFooter.getPaddingLeft() - mFooter.getPaddingRight();
    661 
    662             float textWidth =  mFolderName.getPaint().measureText(mFolderName.getText().toString());
    663             float translation = (footerWidth - textWidth) / 2;
    664             mFolderName.setTranslationX(mContent.mIsRtl ? -translation : translation);
    665             mPageIndicator.prepareEntryAnimation();
    666 
    667             // Do not update the flag if we are in drag mode. The flag will be updated, when we
    668             // actually drop the icon.
    669             final boolean updateAnimationFlag = !mDragInProgress;
    670             anim.addListener(new AnimatorListenerAdapter() {
    671 
    672                 @SuppressLint("InlinedApi")
    673                 @Override
    674                 public void onAnimationEnd(Animator animation) {
    675                     mFolderName.animate().setDuration(FOLDER_NAME_ANIMATION_DURATION)
    676                         .translationX(0)
    677                         .setInterpolator(AnimationUtils.loadInterpolator(
    678                                 mLauncher, android.R.interpolator.fast_out_slow_in));
    679                     mPageIndicator.playEntryAnimation();
    680 
    681                     if (updateAnimationFlag) {
    682                         mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true,
    683                                 mLauncher.getModelWriter());
    684                     }
    685                 }
    686             });
    687         } else {
    688             mFolderName.setTranslationX(0);
    689         }
    690 
    691         mPageIndicator.stopAllAnimations();
    692         startAnimation(anim);
    693 
    694         // Make sure the folder picks up the last drag move even if the finger doesn't move.
    695         if (mDragController.isDragging()) {
    696             mDragController.forceTouchMove();
    697         }
    698 
    699         mContent.verifyVisibleHighResIcons(mContent.getNextPage());
    700 
    701         // Notify the accessibility manager that this folder "window" has appeared and occluded
    702         // the workspace items
    703         sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
    704         dragLayer.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
    705     }
    706 
    707     public void beginExternalDrag() {
    708         mEmptyCellRank = mContent.allocateRankForNewItem();
    709         mIsExternalDrag = true;
    710         mDragInProgress = true;
    711 
    712         // Since this folder opened by another controller, it might not get onDrop or
    713         // onDropComplete. Perform cleanup once drag-n-drop ends.
    714         mDragController.addDragListener(this);
    715     }
    716 
    717     @Override
    718     protected boolean isOfType(int type) {
    719         return (type & TYPE_FOLDER) != 0;
    720     }
    721 
    722     @Override
    723     protected void handleClose(boolean animate) {
    724         mIsOpen = false;
    725 
    726         if (isEditingName()) {
    727             mFolderName.dispatchBackKey();
    728         }
    729 
    730         if (mFolderIcon != null) {
    731             if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
    732                 mFolderIcon.clearLeaveBehindIfExists();
    733             } else {
    734                 mFolderIcon.shrinkAndFadeIn(animate);
    735             }
    736         }
    737 
    738         if (!(getParent() instanceof DragLayer)) return;
    739         DragLayer parent = (DragLayer) getParent();
    740 
    741         if (animate) {
    742             animateClosed();
    743         } else {
    744             closeComplete(false);
    745         }
    746 
    747         // Notify the accessibility manager that this folder "window" has disappeared and no
    748         // longer occludes the workspace items
    749         parent.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
    750     }
    751 
    752     private AnimatorSet getClosingAnimator() {
    753         AnimatorSet animatorSet = LauncherAnimUtils.createAnimatorSet();
    754         animatorSet.play(LauncherAnimUtils.ofViewAlphaAndScale(this, 0, 0.9f, 0.9f));
    755 
    756         AnimationLayerSet layerSet = new AnimationLayerSet();
    757         layerSet.addView(this);
    758         animatorSet.addListener(layerSet);
    759         animatorSet.setDuration(mExpandDuration);
    760         return animatorSet;
    761     }
    762 
    763     private void animateClosed() {
    764         AnimatorSet a = FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION
    765                 ? new FolderAnimationManager(this, false /* isOpening */).getAnimator()
    766                 : getClosingAnimator();
    767         a.addListener(new AnimatorListenerAdapter() {
    768             @Override
    769             public void onAnimationEnd(Animator animation) {
    770                 closeComplete(true);
    771             }
    772             @Override
    773             public void onAnimationStart(Animator animation) {
    774                 Utilities.sendCustomAccessibilityEvent(
    775                         Folder.this,
    776                         AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
    777                         getContext().getString(R.string.folder_closed));
    778             }
    779         });
    780         startAnimation(a);
    781     }
    782 
    783     private void closeComplete(boolean wasAnimated) {
    784         // TODO: Clear all active animations.
    785         DragLayer parent = (DragLayer) getParent();
    786         if (parent != null) {
    787             parent.removeView(this);
    788         }
    789         mDragController.removeDropTarget(this);
    790         clearFocus();
    791         if (mFolderIcon != null) {
    792             mFolderIcon.setVisibility(View.VISIBLE);
    793             if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
    794                 mFolderIcon.setBackgroundVisible(true);
    795                 mFolderIcon.mFolderName.setTextVisibility(true);
    796             }
    797             if (wasAnimated) {
    798                 if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
    799                     mFolderIcon.mBackground.fadeInBackgroundShadow();
    800                     mFolderIcon.mBackground.animateBackgroundStroke();
    801                     mFolderIcon.onFolderClose(mContent.getCurrentPage());
    802                 }
    803                 if (mFolderIcon.hasBadge()) {
    804                     mFolderIcon.createBadgeScaleAnimator(0f, 1f).start();
    805                 }
    806                 mFolderIcon.requestFocus();
    807             }
    808         }
    809 
    810         if (mRearrangeOnClose) {
    811             rearrangeChildren();
    812             mRearrangeOnClose = false;
    813         }
    814         if (getItemCount() <= 1) {
    815             if (!mDragInProgress && !mSuppressFolderDeletion) {
    816                 replaceFolderWithFinalItem();
    817             } else if (mDragInProgress) {
    818                 mDeleteFolderOnDropCompleted = true;
    819             }
    820         }
    821         mSuppressFolderDeletion = false;
    822         clearDragInfo();
    823         mState = STATE_SMALL;
    824         mContent.setCurrentPage(0);
    825     }
    826 
    827     public boolean acceptDrop(DragObject d) {
    828         final ItemInfo item = d.dragInfo;
    829         final int itemType = item.itemType;
    830         return ((itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION ||
    831                 itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT ||
    832                 itemType == LauncherSettings.Favorites.ITEM_TYPE_DEEP_SHORTCUT) &&
    833                     !isFull());
    834     }
    835 
    836     public void onDragEnter(DragObject d) {
    837         mPrevTargetRank = -1;
    838         mOnExitAlarm.cancelAlarm();
    839         // Get the area offset such that the folder only closes if half the drag icon width
    840         // is outside the folder area
    841         mScrollAreaOffset = d.dragView.getDragRegionWidth() / 2 - d.xOffset;
    842     }
    843 
    844     OnAlarmListener mReorderAlarmListener = new OnAlarmListener() {
    845         public void onAlarm(Alarm alarm) {
    846             mContent.realTimeReorder(mEmptyCellRank, mTargetRank);
    847             mEmptyCellRank = mTargetRank;
    848         }
    849     };
    850 
    851     public boolean isLayoutRtl() {
    852         return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
    853     }
    854 
    855     @Override
    856     public void onDragOver(DragObject d) {
    857         onDragOver(d, REORDER_DELAY);
    858     }
    859 
    860     private int getTargetRank(DragObject d, float[] recycle) {
    861         recycle = d.getVisualCenter(recycle);
    862         return mContent.findNearestArea(
    863                 (int) recycle[0] - getPaddingLeft(), (int) recycle[1] - getPaddingTop());
    864     }
    865 
    866     @Thunk void onDragOver(DragObject d, int reorderDelay) {
    867         if (mScrollPauseAlarm.alarmPending()) {
    868             return;
    869         }
    870         final float[] r = new float[2];
    871         mTargetRank = getTargetRank(d, r);
    872 
    873         if (mTargetRank != mPrevTargetRank) {
    874             mReorderAlarm.cancelAlarm();
    875             mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
    876             mReorderAlarm.setAlarm(REORDER_DELAY);
    877             mPrevTargetRank = mTargetRank;
    878 
    879             if (d.stateAnnouncer != null) {
    880                 d.stateAnnouncer.announce(getContext().getString(R.string.move_to_position,
    881                         mTargetRank + 1));
    882             }
    883         }
    884 
    885         float x = r[0];
    886         int currentPage = mContent.getNextPage();
    887 
    888         float cellOverlap = mContent.getCurrentCellLayout().getCellWidth()
    889                 * ICON_OVERSCROLL_WIDTH_FACTOR;
    890         boolean isOutsideLeftEdge = x < cellOverlap;
    891         boolean isOutsideRightEdge = x > (getWidth() - cellOverlap);
    892 
    893         if (currentPage > 0 && (mContent.mIsRtl ? isOutsideRightEdge : isOutsideLeftEdge)) {
    894             showScrollHint(SCROLL_LEFT, d);
    895         } else if (currentPage < (mContent.getPageCount() - 1)
    896                 && (mContent.mIsRtl ? isOutsideLeftEdge : isOutsideRightEdge)) {
    897             showScrollHint(SCROLL_RIGHT, d);
    898         } else {
    899             mOnScrollHintAlarm.cancelAlarm();
    900             if (mScrollHintDir != SCROLL_NONE) {
    901                 mContent.clearScrollHint();
    902                 mScrollHintDir = SCROLL_NONE;
    903             }
    904         }
    905     }
    906 
    907     private void showScrollHint(int direction, DragObject d) {
    908         // Show scroll hint on the right
    909         if (mScrollHintDir != direction) {
    910             mContent.showScrollHint(direction);
    911             mScrollHintDir = direction;
    912         }
    913 
    914         // Set alarm for when the hint is complete
    915         if (!mOnScrollHintAlarm.alarmPending() || mCurrentScrollDir != direction) {
    916             mCurrentScrollDir = direction;
    917             mOnScrollHintAlarm.cancelAlarm();
    918             mOnScrollHintAlarm.setOnAlarmListener(new OnScrollHintListener(d));
    919             mOnScrollHintAlarm.setAlarm(SCROLL_HINT_DURATION);
    920 
    921             mReorderAlarm.cancelAlarm();
    922             mTargetRank = mEmptyCellRank;
    923         }
    924     }
    925 
    926     OnAlarmListener mOnExitAlarmListener = new OnAlarmListener() {
    927         public void onAlarm(Alarm alarm) {
    928             completeDragExit();
    929         }
    930     };
    931 
    932     public void completeDragExit() {
    933         if (mIsOpen) {
    934             close(true);
    935             mRearrangeOnClose = true;
    936         } else if (mState == STATE_ANIMATING) {
    937             mRearrangeOnClose = true;
    938         } else {
    939             rearrangeChildren();
    940             clearDragInfo();
    941         }
    942     }
    943 
    944     private void clearDragInfo() {
    945         mCurrentDragView = null;
    946         mIsExternalDrag = false;
    947     }
    948 
    949     public void onDragExit(DragObject d) {
    950         // We only close the folder if this is a true drag exit, ie. not because
    951         // a drop has occurred above the folder.
    952         if (!d.dragComplete) {
    953             mOnExitAlarm.setOnAlarmListener(mOnExitAlarmListener);
    954             mOnExitAlarm.setAlarm(ON_EXIT_CLOSE_DELAY);
    955         }
    956         mReorderAlarm.cancelAlarm();
    957 
    958         mOnScrollHintAlarm.cancelAlarm();
    959         mScrollPauseAlarm.cancelAlarm();
    960         if (mScrollHintDir != SCROLL_NONE) {
    961             mContent.clearScrollHint();
    962             mScrollHintDir = SCROLL_NONE;
    963         }
    964     }
    965 
    966     /**
    967      * When performing an accessibility drop, onDrop is sent immediately after onDragEnter. So we
    968      * need to complete all transient states based on timers.
    969      */
    970     @Override
    971     public void prepareAccessibilityDrop() {
    972         if (mReorderAlarm.alarmPending()) {
    973             mReorderAlarm.cancelAlarm();
    974             mReorderAlarmListener.onAlarm(mReorderAlarm);
    975         }
    976     }
    977 
    978     public void onDropCompleted(final View target, final DragObject d,
    979             final boolean isFlingToDelete, final boolean success) {
    980         if (mDeferDropAfterUninstall) {
    981             Log.d(TAG, "Deferred handling drop because waiting for uninstall.");
    982             mDeferredAction = new Runnable() {
    983                     public void run() {
    984                         onDropCompleted(target, d, isFlingToDelete, success);
    985                         mDeferredAction = null;
    986                     }
    987                 };
    988             return;
    989         }
    990 
    991         boolean beingCalledAfterUninstall = mDeferredAction != null;
    992         boolean successfulDrop =
    993                 success && (!beingCalledAfterUninstall || mUninstallSuccessful);
    994 
    995         if (successfulDrop) {
    996             if (mDeleteFolderOnDropCompleted && !mItemAddedBackToSelfViaIcon && target != this) {
    997                 replaceFolderWithFinalItem();
    998             }
    999         } else {
   1000             // The drag failed, we need to return the item to the folder
   1001             ShortcutInfo info = (ShortcutInfo) d.dragInfo;
   1002             View icon = (mCurrentDragView != null && mCurrentDragView.getTag() == info)
   1003                     ? mCurrentDragView : mContent.createNewView(info);
   1004             ArrayList<View> views = getItemsInReadingOrder();
   1005             views.add(info.rank, icon);
   1006             mContent.arrangeChildren(views, views.size());
   1007             mItemsInvalidated = true;
   1008 
   1009             try (SuppressInfoChanges s = new SuppressInfoChanges()) {
   1010                 mFolderIcon.onDrop(d);
   1011             }
   1012         }
   1013 
   1014         if (target != this) {
   1015             if (mOnExitAlarm.alarmPending()) {
   1016                 mOnExitAlarm.cancelAlarm();
   1017                 if (!successfulDrop) {
   1018                     mSuppressFolderDeletion = true;
   1019                 }
   1020                 mScrollPauseAlarm.cancelAlarm();
   1021                 completeDragExit();
   1022             }
   1023         }
   1024 
   1025         mDeleteFolderOnDropCompleted = false;
   1026         mDragInProgress = false;
   1027         mItemAddedBackToSelfViaIcon = false;
   1028         mCurrentDragView = null;
   1029 
   1030         // Reordering may have occured, and we need to save the new item locations. We do this once
   1031         // at the end to prevent unnecessary database operations.
   1032         updateItemLocationsInDatabaseBatch();
   1033 
   1034         // Use the item count to check for multi-page as the folder UI may not have
   1035         // been refreshed yet.
   1036         if (getItemCount() <= mContent.itemsPerPage()) {
   1037             // Show the animation, next time something is added to the folder.
   1038             mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, false,
   1039                     mLauncher.getModelWriter());
   1040         }
   1041 
   1042         if (!isFlingToDelete) {
   1043             // Fling to delete already exits spring loaded mode after the animation finishes.
   1044             mLauncher.exitSpringLoadedDragModeDelayed(successfulDrop,
   1045                     Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null);
   1046         }
   1047     }
   1048 
   1049     @Override
   1050     public void deferCompleteDropAfterUninstallActivity() {
   1051         mDeferDropAfterUninstall = true;
   1052     }
   1053 
   1054     @Override
   1055     public void onDragObjectRemoved(boolean success) {
   1056         mDeferDropAfterUninstall = false;
   1057         mUninstallSuccessful = success;
   1058         if (mDeferredAction != null) {
   1059             mDeferredAction.run();
   1060         }
   1061     }
   1062 
   1063     @Override
   1064     public float getIntrinsicIconScaleFactor() {
   1065         return 1f;
   1066     }
   1067 
   1068     @Override
   1069     public boolean supportsAppInfoDropTarget() {
   1070         return true;
   1071     }
   1072 
   1073     @Override
   1074     public boolean supportsDeleteDropTarget() {
   1075         return true;
   1076     }
   1077 
   1078     private void updateItemLocationsInDatabaseBatch() {
   1079         ArrayList<View> list = getItemsInReadingOrder();
   1080         ArrayList<ItemInfo> items = new ArrayList<ItemInfo>();
   1081         for (int i = 0; i < list.size(); i++) {
   1082             View v = list.get(i);
   1083             ItemInfo info = (ItemInfo) v.getTag();
   1084             info.rank = i;
   1085             items.add(info);
   1086         }
   1087 
   1088         mLauncher.getModelWriter().moveItemsInDatabase(items, mInfo.id, 0);
   1089     }
   1090 
   1091     public void notifyDrop() {
   1092         if (mDragInProgress) {
   1093             mItemAddedBackToSelfViaIcon = true;
   1094         }
   1095     }
   1096 
   1097     public boolean isDropEnabled() {
   1098         if (FeatureFlags.LAUNCHER3_NEW_FOLDER_ANIMATION) {
   1099             return mState != STATE_ANIMATING;
   1100         }
   1101         return true;
   1102     }
   1103 
   1104     public boolean isFull() {
   1105         return mContent.isFull();
   1106     }
   1107 
   1108     private void centerAboutIcon() {
   1109         DeviceProfile grid = mLauncher.getDeviceProfile();
   1110 
   1111         DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();
   1112         DragLayer parent = (DragLayer) mLauncher.findViewById(R.id.drag_layer);
   1113         int width = getFolderWidth();
   1114         int height = getFolderHeight();
   1115 
   1116         float scale = parent.getDescendantRectRelativeToSelf(mFolderIcon, sTempRect);
   1117         int centerX = sTempRect.centerX();
   1118         int centerY = sTempRect.centerY();
   1119         int centeredLeft = centerX - width / 2;
   1120         int centeredTop = centerY - height / 2;
   1121 
   1122         // We need to bound the folder to the currently visible workspace area
   1123         mLauncher.getWorkspace().getPageAreaRelativeToDragLayer(sTempRect);
   1124         int left = Math.min(Math.max(sTempRect.left, centeredLeft),
   1125                 sTempRect.right- width);
   1126         int top = Math.min(Math.max(sTempRect.top, centeredTop),
   1127                 sTempRect.bottom - height);
   1128 
   1129         int distFromEdgeOfScreen = mLauncher.getWorkspace().getPaddingLeft() + getPaddingLeft();
   1130 
   1131         if (grid.isPhone && (grid.availableWidthPx - width) < 4 * distFromEdgeOfScreen) {
   1132             // Center the folder if it is very close to being centered anyway, by virtue of
   1133             // filling the majority of the viewport. ie. remove it from the uncanny valley
   1134             // of centeredness.
   1135             left = (grid.availableWidthPx - width) / 2;
   1136         } else if (width >= sTempRect.width()) {
   1137             // If the folder doesn't fit within the bounds, center it about the desired bounds
   1138             left = sTempRect.left + (sTempRect.width() - width) / 2;
   1139         }
   1140         if (height >= sTempRect.height()) {
   1141             // Folder height is greater than page height, center on page
   1142             top = sTempRect.top + (sTempRect.height() - height) / 2;
   1143         } else {
   1144             // Folder height is less than page height, so bound it to the absolute open folder
   1145             // bounds if necessary
   1146             Rect folderBounds = grid.getAbsoluteOpenFolderBounds();
   1147             left = Math.max(folderBounds.left, Math.min(left, folderBounds.right - width));
   1148             top = Math.max(folderBounds.top, Math.min(top, folderBounds.bottom - height));
   1149         }
   1150 
   1151         int folderPivotX = width / 2 + (centeredLeft - left);
   1152         int folderPivotY = height / 2 + (centeredTop - top);
   1153         setPivotX(folderPivotX);
   1154         setPivotY(folderPivotY);
   1155 
   1156         mFolderIconPivotX = (int) (mFolderIcon.getMeasuredWidth() *
   1157                 (1.0f * folderPivotX / width));
   1158         mFolderIconPivotY = (int) (mFolderIcon.getMeasuredHeight() *
   1159                 (1.0f * folderPivotY / height));
   1160 
   1161         lp.width = width;
   1162         lp.height = height;
   1163         lp.x = left;
   1164         lp.y = top;
   1165     }
   1166 
   1167     public float getPivotXForIconAnimation() {
   1168         return mFolderIconPivotX;
   1169     }
   1170     public float getPivotYForIconAnimation() {
   1171         return mFolderIconPivotY;
   1172     }
   1173 
   1174     private int getContentAreaHeight() {
   1175         DeviceProfile grid = mLauncher.getDeviceProfile();
   1176         int maxContentAreaHeight = grid.availableHeightPx
   1177                 - grid.getTotalWorkspacePadding().y - mFooterHeight;
   1178         int height = Math.min(maxContentAreaHeight,
   1179                 mContent.getDesiredHeight());
   1180         return Math.max(height, MIN_CONTENT_DIMEN);
   1181     }
   1182 
   1183     private int getContentAreaWidth() {
   1184         return Math.max(mContent.getDesiredWidth(), MIN_CONTENT_DIMEN);
   1185     }
   1186 
   1187     private int getFolderWidth() {
   1188         return getPaddingLeft() + getPaddingRight() + mContent.getDesiredWidth();
   1189     }
   1190 
   1191     private int getFolderHeight() {
   1192         return getFolderHeight(getContentAreaHeight());
   1193     }
   1194 
   1195     private int getFolderHeight(int contentAreaHeight) {
   1196         return getPaddingTop() + getPaddingBottom() + contentAreaHeight + mFooterHeight;
   1197     }
   1198 
   1199     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   1200         int contentWidth = getContentAreaWidth();
   1201         int contentHeight = getContentAreaHeight();
   1202 
   1203         int contentAreaWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY);
   1204         int contentAreaHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY);
   1205 
   1206         mContent.setFixedSize(contentWidth, contentHeight);
   1207         mContent.measure(contentAreaWidthSpec, contentAreaHeightSpec);
   1208 
   1209         if (mContent.getChildCount() > 0) {
   1210             int cellIconGap = (mContent.getPageAt(0).getCellWidth()
   1211                     - mLauncher.getDeviceProfile().iconSizePx) / 2;
   1212             mFooter.setPadding(mContent.getPaddingLeft() + cellIconGap,
   1213                     mFooter.getPaddingTop(),
   1214                     mContent.getPaddingRight() + cellIconGap,
   1215                     mFooter.getPaddingBottom());
   1216         }
   1217         mFooter.measure(contentAreaWidthSpec,
   1218                 MeasureSpec.makeMeasureSpec(mFooterHeight, MeasureSpec.EXACTLY));
   1219 
   1220         int folderWidth = getPaddingLeft() + getPaddingRight() + contentWidth;
   1221         int folderHeight = getFolderHeight(contentHeight);
   1222         setMeasuredDimension(folderWidth, folderHeight);
   1223     }
   1224 
   1225     /**
   1226      * Rearranges the children based on their rank.
   1227      */
   1228     public void rearrangeChildren() {
   1229         rearrangeChildren(-1);
   1230     }
   1231 
   1232     /**
   1233      * Rearranges the children based on their rank.
   1234      * @param itemCount if greater than the total children count, empty spaces are left at the end,
   1235      * otherwise it is ignored.
   1236      */
   1237     public void rearrangeChildren(int itemCount) {
   1238         ArrayList<View> views = getItemsInReadingOrder();
   1239         mContent.arrangeChildren(views, Math.max(itemCount, views.size()));
   1240         mItemsInvalidated = true;
   1241     }
   1242 
   1243     public int getItemCount() {
   1244         return mContent.getItemCount();
   1245     }
   1246 
   1247     @Thunk void replaceFolderWithFinalItem() {
   1248         // Add the last remaining child to the workspace in place of the folder
   1249         Runnable onCompleteRunnable = new Runnable() {
   1250             @Override
   1251             public void run() {
   1252                 int itemCount = mInfo.contents.size();
   1253                 if (itemCount <= 1) {
   1254                     View newIcon = null;
   1255 
   1256                     if (itemCount == 1) {
   1257                         // Move the item from the folder to the workspace, in the position of the
   1258                         // folder
   1259                         CellLayout cellLayout = mLauncher.getCellLayout(mInfo.container,
   1260                                 mInfo.screenId);
   1261                         ShortcutInfo finalItem = mInfo.contents.remove(0);
   1262                         newIcon = mLauncher.createShortcut(cellLayout, finalItem);
   1263                         mLauncher.getModelWriter().addOrMoveItemInDatabase(finalItem,
   1264                                 mInfo.container, mInfo.screenId, mInfo.cellX, mInfo.cellY);
   1265                     }
   1266 
   1267                     // Remove the folder
   1268                     mLauncher.removeItem(mFolderIcon, mInfo, true /* deleteFromDb */);
   1269                     if (mFolderIcon instanceof DropTarget) {
   1270                         mDragController.removeDropTarget((DropTarget) mFolderIcon);
   1271                     }
   1272 
   1273                     if (newIcon != null) {
   1274                         // We add the child after removing the folder to prevent both from existing
   1275                         // at the same time in the CellLayout.  We need to add the new item with
   1276                         // addInScreenFromBind() to ensure that hotseat items are placed correctly.
   1277                         mLauncher.getWorkspace().addInScreenFromBind(newIcon, mInfo);
   1278 
   1279                         // Focus the newly created child
   1280                         newIcon.requestFocus();
   1281                     }
   1282                 }
   1283             }
   1284         };
   1285         View finalChild = mContent.getLastItem();
   1286         if (finalChild != null) {
   1287             mFolderIcon.performDestroyAnimation(onCompleteRunnable);
   1288         } else {
   1289             onCompleteRunnable.run();
   1290         }
   1291         mDestroyed = true;
   1292     }
   1293 
   1294     public boolean isDestroyed() {
   1295         return mDestroyed;
   1296     }
   1297 
   1298     // This method keeps track of the first and last item in the folder for the purposes
   1299     // of keyboard focus
   1300     public void updateTextViewFocus() {
   1301         final View firstChild = mContent.getFirstItem();
   1302         final View lastChild = mContent.getLastItem();
   1303         if (firstChild != null && lastChild != null) {
   1304             mFolderName.setNextFocusDownId(lastChild.getId());
   1305             mFolderName.setNextFocusRightId(lastChild.getId());
   1306             mFolderName.setNextFocusLeftId(lastChild.getId());
   1307             mFolderName.setNextFocusUpId(lastChild.getId());
   1308             // Hitting TAB from the folder name wraps around to the first item on the current
   1309             // folder page, and hitting SHIFT+TAB from that item wraps back to the folder name.
   1310             mFolderName.setNextFocusForwardId(firstChild.getId());
   1311             // When clicking off the folder when editing the name, this Folder gains focus. When
   1312             // pressing an arrow key from that state, give the focus to the first item.
   1313             this.setNextFocusDownId(firstChild.getId());
   1314             this.setNextFocusRightId(firstChild.getId());
   1315             this.setNextFocusLeftId(firstChild.getId());
   1316             this.setNextFocusUpId(firstChild.getId());
   1317             // When pressing shift+tab in the above state, give the focus to the last item.
   1318             setOnKeyListener(new OnKeyListener() {
   1319                 @Override
   1320                 public boolean onKey(View v, int keyCode, KeyEvent event) {
   1321                     boolean isShiftPlusTab = keyCode == KeyEvent.KEYCODE_TAB &&
   1322                             event.hasModifiers(KeyEvent.META_SHIFT_ON);
   1323                     if (isShiftPlusTab && Folder.this.isFocused()) {
   1324                         return lastChild.requestFocus();
   1325                     }
   1326                     return false;
   1327                 }
   1328             });
   1329         }
   1330     }
   1331 
   1332     public void onDrop(DragObject d) {
   1333         Runnable cleanUpRunnable = null;
   1334 
   1335         // If we are coming from All Apps space, we defer removing the extra empty screen
   1336         // until the folder closes
   1337         if (d.dragSource != mLauncher.getWorkspace() && !(d.dragSource instanceof Folder)) {
   1338             cleanUpRunnable = new Runnable() {
   1339                 @Override
   1340                 public void run() {
   1341                     mLauncher.exitSpringLoadedDragModeDelayed(true,
   1342                             Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT,
   1343                             null);
   1344                 }
   1345             };
   1346         }
   1347 
   1348         // If the icon was dropped while the page was being scrolled, we need to compute
   1349         // the target location again such that the icon is placed of the final page.
   1350         if (!mContent.rankOnCurrentPage(mEmptyCellRank)) {
   1351             // Reorder again.
   1352             mTargetRank = getTargetRank(d, null);
   1353 
   1354             // Rearrange items immediately.
   1355             mReorderAlarmListener.onAlarm(mReorderAlarm);
   1356 
   1357             mOnScrollHintAlarm.cancelAlarm();
   1358             mScrollPauseAlarm.cancelAlarm();
   1359         }
   1360         mContent.completePendingPageChanges();
   1361 
   1362         PendingAddShortcutInfo pasi = d.dragInfo instanceof PendingAddShortcutInfo
   1363                 ? (PendingAddShortcutInfo) d.dragInfo : null;
   1364         ShortcutInfo pasiSi = pasi != null ? pasi.activityInfo.createShortcutInfo() : null;
   1365         if (pasi != null && pasiSi == null) {
   1366             // There is no ShortcutInfo, so we have to go through a configuration activity.
   1367             pasi.container = mInfo.id;
   1368             pasi.rank = mEmptyCellRank;
   1369 
   1370             mLauncher.addPendingItem(pasi, pasi.container, pasi.screenId, null, pasi.spanX,
   1371                     pasi.spanY);
   1372             d.deferDragViewCleanupPostAnimation = false;
   1373             mRearrangeOnClose = true;
   1374         } else {
   1375             final ShortcutInfo si;
   1376             if (pasiSi != null) {
   1377                 si = pasiSi;
   1378             } else if (d.dragInfo instanceof AppInfo) {
   1379                 // Came from all apps -- make a copy.
   1380                 si = ((AppInfo) d.dragInfo).makeShortcut();
   1381             } else {
   1382                 // ShortcutInfo
   1383                 si = (ShortcutInfo) d.dragInfo;
   1384             }
   1385 
   1386             View currentDragView;
   1387             if (mIsExternalDrag) {
   1388                 currentDragView = mContent.createAndAddViewForRank(si, mEmptyCellRank);
   1389 
   1390                 // Actually move the item in the database if it was an external drag. Call this
   1391                 // before creating the view, so that ShortcutInfo is updated appropriately.
   1392                 mLauncher.getModelWriter().addOrMoveItemInDatabase(
   1393                         si, mInfo.id, 0, si.cellX, si.cellY);
   1394 
   1395                 // We only need to update the locations if it doesn't get handled in
   1396                 // #onDropCompleted.
   1397                 if (d.dragSource != this) {
   1398                     updateItemLocationsInDatabaseBatch();
   1399                 }
   1400                 mIsExternalDrag = false;
   1401             } else {
   1402                 currentDragView = mCurrentDragView;
   1403                 mContent.addViewForRank(currentDragView, si, mEmptyCellRank);
   1404             }
   1405 
   1406             if (d.dragView.hasDrawn()) {
   1407                 // Temporarily reset the scale such that the animation target gets calculated
   1408                 // correctly.
   1409                 float scaleX = getScaleX();
   1410                 float scaleY = getScaleY();
   1411                 setScaleX(1.0f);
   1412                 setScaleY(1.0f);
   1413                 mLauncher.getDragLayer().animateViewIntoPosition(d.dragView, currentDragView,
   1414                         cleanUpRunnable, null);
   1415                 setScaleX(scaleX);
   1416                 setScaleY(scaleY);
   1417             } else {
   1418                 d.deferDragViewCleanupPostAnimation = false;
   1419                 currentDragView.setVisibility(VISIBLE);
   1420             }
   1421 
   1422             mItemsInvalidated = true;
   1423             rearrangeChildren();
   1424 
   1425             // Temporarily suppress the listener, as we did all the work already here.
   1426             try (SuppressInfoChanges s = new SuppressInfoChanges()) {
   1427                 mInfo.add(si, false);
   1428             }
   1429         }
   1430 
   1431         // Clear the drag info, as it is no longer being dragged.
   1432         mDragInProgress = false;
   1433 
   1434         if (mContent.getPageCount() > 1) {
   1435             // The animation has already been shown while opening the folder.
   1436             mInfo.setOption(FolderInfo.FLAG_MULTI_PAGE_ANIMATION, true, mLauncher.getModelWriter());
   1437         }
   1438 
   1439         if (d.stateAnnouncer != null) {
   1440             d.stateAnnouncer.completeAction(R.string.item_moved);
   1441         }
   1442     }
   1443 
   1444     // This is used so the item doesn't immediately appear in the folder when added. In one case
   1445     // we need to create the illusion that the item isn't added back to the folder yet, to
   1446     // to correspond to the animation of the icon back into the folder. This is
   1447     public void hideItem(ShortcutInfo info) {
   1448         View v = getViewForInfo(info);
   1449         v.setVisibility(INVISIBLE);
   1450     }
   1451     public void showItem(ShortcutInfo info) {
   1452         View v = getViewForInfo(info);
   1453         v.setVisibility(VISIBLE);
   1454     }
   1455 
   1456     @Override
   1457     public void onAdd(ShortcutInfo item, int rank) {
   1458         View view = mContent.createAndAddViewForRank(item, rank);
   1459         mLauncher.getModelWriter().addOrMoveItemInDatabase(item, mInfo.id, 0, item.cellX,
   1460                 item.cellY);
   1461 
   1462         ArrayList<View> items = new ArrayList<>(getItemsInReadingOrder());
   1463         items.add(rank, view);
   1464         mContent.arrangeChildren(items, items.size());
   1465         mItemsInvalidated = true;
   1466     }
   1467 
   1468     public void onRemove(ShortcutInfo item) {
   1469         mItemsInvalidated = true;
   1470         View v = getViewForInfo(item);
   1471         mContent.removeItem(v);
   1472         if (mState == STATE_ANIMATING) {
   1473             mRearrangeOnClose = true;
   1474         } else {
   1475             rearrangeChildren();
   1476         }
   1477         if (getItemCount() <= 1) {
   1478             if (mIsOpen) {
   1479                 close(true);
   1480             } else {
   1481                 replaceFolderWithFinalItem();
   1482             }
   1483         }
   1484     }
   1485 
   1486     private View getViewForInfo(final ShortcutInfo item) {
   1487         return mContent.iterateOverItems(new ItemOperator() {
   1488 
   1489             @Override
   1490             public boolean evaluate(ItemInfo info, View view) {
   1491                 return info == item;
   1492             }
   1493         });
   1494     }
   1495 
   1496     @Override
   1497     public void onItemsChanged(boolean animate) {
   1498         updateTextViewFocus();
   1499     }
   1500 
   1501     @Override
   1502     public void prepareAutoUpdate() {
   1503         close(false);
   1504     }
   1505 
   1506     public void onTitleChanged(CharSequence title) {
   1507     }
   1508 
   1509     public ArrayList<View> getItemsInReadingOrder() {
   1510         if (mItemsInvalidated) {
   1511             mItemsInReadingOrder.clear();
   1512             mContent.iterateOverItems(new ItemOperator() {
   1513 
   1514                 @Override
   1515                 public boolean evaluate(ItemInfo info, View view) {
   1516                     mItemsInReadingOrder.add(view);
   1517                     return false;
   1518                 }
   1519             });
   1520             mItemsInvalidated = false;
   1521         }
   1522         return mItemsInReadingOrder;
   1523     }
   1524 
   1525     public List<BubbleTextView> getItemsOnPage(int page) {
   1526         ArrayList<View> allItems = getItemsInReadingOrder();
   1527         int lastPage = mContent.getPageCount() - 1;
   1528         int totalItemsInFolder = allItems.size();
   1529         int itemsPerPage = mContent.itemsPerPage();
   1530         int numItemsOnCurrentPage = page == lastPage
   1531                 ? totalItemsInFolder - (itemsPerPage * page)
   1532                 : itemsPerPage;
   1533 
   1534         int startIndex = page * itemsPerPage;
   1535         int endIndex = Math.min(startIndex + numItemsOnCurrentPage, allItems.size());
   1536 
   1537         List<BubbleTextView> itemsOnCurrentPage = new ArrayList<>(numItemsOnCurrentPage);
   1538         for (int i = startIndex; i < endIndex; ++i) {
   1539             itemsOnCurrentPage.add((BubbleTextView) allItems.get(i));
   1540         }
   1541         return itemsOnCurrentPage;
   1542     }
   1543 
   1544     public void onFocusChange(View v, boolean hasFocus) {
   1545         if (v == mFolderName) {
   1546             if (hasFocus) {
   1547                 startEditingFolderName();
   1548             } else {
   1549                 mFolderName.dispatchBackKey();
   1550             }
   1551         }
   1552     }
   1553 
   1554     @Override
   1555     public void getHitRectRelativeToDragLayer(Rect outRect) {
   1556         getHitRect(outRect);
   1557         outRect.left -= mScrollAreaOffset;
   1558         outRect.right += mScrollAreaOffset;
   1559     }
   1560 
   1561     @Override
   1562     public void fillInLogContainerData(View v, ItemInfo info, Target target, Target targetParent) {
   1563         target.gridX = info.cellX;
   1564         target.gridY = info.cellY;
   1565         target.pageIndex = mContent.getCurrentPage();
   1566         targetParent.containerType = ContainerType.FOLDER;
   1567     }
   1568 
   1569     private class OnScrollHintListener implements OnAlarmListener {
   1570 
   1571         private final DragObject mDragObject;
   1572 
   1573         OnScrollHintListener(DragObject object) {
   1574             mDragObject = object;
   1575         }
   1576 
   1577         /**
   1578          * Scroll hint has been shown long enough. Now scroll to appropriate page.
   1579          */
   1580         @Override
   1581         public void onAlarm(Alarm alarm) {
   1582             if (mCurrentScrollDir == SCROLL_LEFT) {
   1583                 mContent.scrollLeft();
   1584                 mScrollHintDir = SCROLL_NONE;
   1585             } else if (mCurrentScrollDir == SCROLL_RIGHT) {
   1586                 mContent.scrollRight();
   1587                 mScrollHintDir = SCROLL_NONE;
   1588             } else {
   1589                 // This should not happen
   1590                 return;
   1591             }
   1592             mCurrentScrollDir = SCROLL_NONE;
   1593 
   1594             // Pause drag event until the scrolling is finished
   1595             mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject));
   1596             mScrollPauseAlarm.setAlarm(RESCROLL_DELAY);
   1597         }
   1598     }
   1599 
   1600     private class OnScrollFinishedListener implements OnAlarmListener {
   1601 
   1602         private final DragObject mDragObject;
   1603 
   1604         OnScrollFinishedListener(DragObject object) {
   1605             mDragObject = object;
   1606         }
   1607 
   1608         /**
   1609          * Page scroll is complete.
   1610          */
   1611         @Override
   1612         public void onAlarm(Alarm alarm) {
   1613             // Reorder immediately on page change.
   1614             onDragOver(mDragObject, 1);
   1615         }
   1616     }
   1617 
   1618     // Compares item position based on rank and position giving priority to the rank.
   1619     public static final Comparator<ItemInfo> ITEM_POS_COMPARATOR = new Comparator<ItemInfo>() {
   1620 
   1621         @Override
   1622         public int compare(ItemInfo lhs, ItemInfo rhs) {
   1623             if (lhs.rank != rhs.rank) {
   1624                 return lhs.rank - rhs.rank;
   1625             } else if (lhs.cellY != rhs.cellY) {
   1626                 return lhs.cellY - rhs.cellY;
   1627             } else {
   1628                 return lhs.cellX - rhs.cellX;
   1629             }
   1630         }
   1631     };
   1632 
   1633     /**
   1634      * Temporary resource held while we don't want to handle info changes
   1635      */
   1636     private class SuppressInfoChanges implements AutoCloseable {
   1637 
   1638         SuppressInfoChanges() {
   1639             mInfo.removeListener(Folder.this);
   1640         }
   1641 
   1642         @Override
   1643         public void close() {
   1644             mInfo.addListener(Folder.this);
   1645             updateTextViewFocus();
   1646         }
   1647     }
   1648 
   1649     /**
   1650      * Returns a folder which is already open or null
   1651      */
   1652     public static Folder getOpen(Launcher launcher) {
   1653         return getOpenView(launcher, TYPE_FOLDER);
   1654     }
   1655 
   1656     @Override
   1657     public int getLogContainerType() {
   1658         return ContainerType.FOLDER;
   1659     }
   1660 }
   1661