DeleteDropTarget.java revision 950a467b180c78d3ce3bbe7b4a227a13d28b2536
1/*
2 * Copyright (C) 2011 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
17package com.android.launcher3;
18
19import android.animation.TimeInterpolator;
20import android.animation.ValueAnimator;
21import android.animation.ValueAnimator.AnimatorUpdateListener;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.content.pm.ResolveInfo;
26import android.content.res.ColorStateList;
27import android.content.res.Configuration;
28import android.content.res.Resources;
29import android.graphics.PointF;
30import android.graphics.Rect;
31import android.graphics.drawable.TransitionDrawable;
32import android.os.AsyncTask;
33import android.os.UserManager;
34import android.util.AttributeSet;
35import android.view.View;
36import android.view.ViewConfiguration;
37import android.view.ViewGroup;
38import android.view.animation.AnimationUtils;
39import android.view.animation.DecelerateInterpolator;
40import android.view.animation.LinearInterpolator;
41
42import com.android.launcher3.compat.LauncherAppsCompat;
43import com.android.launcher3.compat.UserHandleCompat;
44
45import java.util.List;
46import java.util.Set;
47
48public class DeleteDropTarget extends ButtonDropTarget {
49    private static int DELETE_ANIMATION_DURATION = 285;
50    private static int FLING_DELETE_ANIMATION_DURATION = 350;
51    private static float FLING_TO_DELETE_FRICTION = 0.035f;
52    private static int MODE_FLING_DELETE_TO_TRASH = 0;
53    private static int MODE_FLING_DELETE_ALONG_VECTOR = 1;
54
55    private final int mFlingDeleteMode = MODE_FLING_DELETE_ALONG_VECTOR;
56
57    private ColorStateList mOriginalTextColor;
58    private TransitionDrawable mUninstallDrawable;
59    private TransitionDrawable mRemoveDrawable;
60    private TransitionDrawable mCurrentDrawable;
61
62    private boolean mWaitingForUninstall = false;
63
64    public DeleteDropTarget(Context context, AttributeSet attrs) {
65        this(context, attrs, 0);
66    }
67
68    public DeleteDropTarget(Context context, AttributeSet attrs, int defStyle) {
69        super(context, attrs, defStyle);
70    }
71
72    @Override
73    protected void onFinishInflate() {
74        super.onFinishInflate();
75
76        // Get the drawable
77        mOriginalTextColor = getTextColors();
78
79        // Get the hover color
80        Resources r = getResources();
81        mHoverColor = r.getColor(R.color.delete_target_hover_tint);
82        mUninstallDrawable = (TransitionDrawable)
83                r.getDrawable(R.drawable.uninstall_target_selector);
84        mRemoveDrawable = (TransitionDrawable) r.getDrawable(R.drawable.remove_target_selector);
85
86        mRemoveDrawable.setCrossFadeEnabled(true);
87        mUninstallDrawable.setCrossFadeEnabled(true);
88
89        // The current drawable is set to either the remove drawable or the uninstall drawable
90        // and is initially set to the remove drawable, as set in the layout xml.
91        mCurrentDrawable = (TransitionDrawable) getCurrentDrawable();
92
93        // Remove the text in the Phone UI in landscape
94        int orientation = getResources().getConfiguration().orientation;
95        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
96            if (!LauncherAppState.getInstance().isScreenLarge()) {
97                setText("");
98            }
99        }
100    }
101
102    private boolean isAllAppsApplication(DragSource source, Object info) {
103        return source.supportsAppInfoDropTarget() && (info instanceof AppInfo);
104    }
105    private boolean isAllAppsWidget(DragSource source, Object info) {
106        if (source instanceof AppsCustomizePagedView) {
107            if (info instanceof PendingAddItemInfo) {
108                PendingAddItemInfo addInfo = (PendingAddItemInfo) info;
109                switch (addInfo.itemType) {
110                    case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
111                    case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
112                        return true;
113                }
114            }
115        }
116        return false;
117    }
118    private boolean isDragSourceWorkspaceOrFolder(DragObject d) {
119        return (d.dragSource instanceof Workspace) || (d.dragSource instanceof Folder);
120    }
121    private boolean isWorkspaceOrFolderApplication(DragObject d) {
122        return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof ShortcutInfo);
123    }
124    private boolean isWorkspaceOrFolderWidget(DragObject d) {
125        return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof LauncherAppWidgetInfo);
126    }
127    private boolean isWorkspaceFolder(DragObject d) {
128        return (d.dragSource instanceof Workspace) && (d.dragInfo instanceof FolderInfo);
129    }
130
131    private void setHoverColor() {
132        mCurrentDrawable.startTransition(mTransitionDuration);
133        setTextColor(mHoverColor);
134    }
135    private void resetHoverColor() {
136        mCurrentDrawable.resetTransition();
137        setTextColor(mOriginalTextColor);
138    }
139
140    @Override
141    public boolean acceptDrop(DragObject d) {
142        return willAcceptDrop(d.dragInfo);
143    }
144
145    public static boolean willAcceptDrop(Object info) {
146        if (info instanceof ItemInfo) {
147            ItemInfo item = (ItemInfo) info;
148            if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET ||
149                    item.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) {
150                return true;
151            }
152
153            if (!LauncherAppState.isDisableAllApps() &&
154                    item.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) {
155                return true;
156            }
157
158            if (!LauncherAppState.isDisableAllApps() &&
159                    item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
160                    item instanceof AppInfo) {
161                AppInfo appInfo = (AppInfo) info;
162                return (appInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0;
163            }
164
165            if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION &&
166                item instanceof ShortcutInfo) {
167                if (LauncherAppState.isDisableAllApps()) {
168                    ShortcutInfo shortcutInfo = (ShortcutInfo) info;
169                    return (shortcutInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0;
170                } else {
171                    return true;
172                }
173            }
174        }
175        return false;
176    }
177
178    @Override
179    public void onDragStart(DragSource source, Object info, int dragAction) {
180        boolean isVisible = true;
181        boolean useUninstallLabel = !LauncherAppState.isDisableAllApps() &&
182                isAllAppsApplication(source, info);
183        boolean useDeleteLabel = !useUninstallLabel && source.supportsDeleteDropTarget();
184
185        // If we are dragging an application from AppsCustomize, only show the control if we can
186        // delete the app (it was downloaded), and rename the string to "uninstall" in such a case.
187        // Hide the delete target if it is a widget from AppsCustomize.
188        if (!willAcceptDrop(info) || isAllAppsWidget(source, info)) {
189            isVisible = false;
190        }
191        if (useUninstallLabel) {
192            UserManager userManager = (UserManager)
193                getContext().getSystemService(Context.USER_SERVICE);
194            if (userManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)
195                    || userManager.hasUserRestriction(UserManager.DISALLOW_UNINSTALL_APPS)) {
196                isVisible = false;
197            }
198        }
199
200        if (useUninstallLabel) {
201            setCompoundDrawablesRelativeWithIntrinsicBounds(mUninstallDrawable, null, null, null);
202        } else if (useDeleteLabel) {
203            setCompoundDrawablesRelativeWithIntrinsicBounds(mRemoveDrawable, null, null, null);
204        } else {
205            isVisible = false;
206        }
207        mCurrentDrawable = (TransitionDrawable) getCurrentDrawable();
208
209        mActive = isVisible;
210        resetHoverColor();
211        ((ViewGroup) getParent()).setVisibility(isVisible ? View.VISIBLE : View.GONE);
212        if (isVisible && getText().length() > 0) {
213            setText(useUninstallLabel ? R.string.delete_target_uninstall_label
214                : R.string.delete_target_label);
215        }
216    }
217
218    @Override
219    public void onDragEnd() {
220        super.onDragEnd();
221        mActive = false;
222    }
223
224    public void onDragEnter(DragObject d) {
225        super.onDragEnter(d);
226
227        setHoverColor();
228    }
229
230    public void onDragExit(DragObject d) {
231        super.onDragExit(d);
232
233        if (!d.dragComplete) {
234            resetHoverColor();
235        } else {
236            // Restore the hover color if we are deleting
237            d.dragView.setColor(mHoverColor);
238        }
239    }
240
241    private void animateToTrashAndCompleteDrop(final DragObject d) {
242        final DragLayer dragLayer = mLauncher.getDragLayer();
243        final Rect from = new Rect();
244        dragLayer.getViewRectRelativeToSelf(d.dragView, from);
245        final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
246                mCurrentDrawable.getIntrinsicWidth(), mCurrentDrawable.getIntrinsicHeight());
247        final float scale = (float) to.width() / from.width();
248
249        mSearchDropTargetBar.deferOnDragEnd();
250        deferCompleteDropIfUninstalling(d);
251
252        Runnable onAnimationEndRunnable = new Runnable() {
253            @Override
254            public void run() {
255                completeDrop(d);
256                mSearchDropTargetBar.onDragEnd();
257                mLauncher.exitSpringLoadedDragMode();
258            }
259        };
260        dragLayer.animateView(d.dragView, from, to, scale, 1f, 1f, 0.1f, 0.1f,
261                DELETE_ANIMATION_DURATION, new DecelerateInterpolator(2),
262                new LinearInterpolator(), onAnimationEndRunnable,
263                DragLayer.ANIMATION_END_DISAPPEAR, null);
264    }
265
266    private void deferCompleteDropIfUninstalling(DragObject d) {
267        mWaitingForUninstall = false;
268        if (isUninstallFromWorkspace(d)) {
269            if (d.dragSource instanceof Folder) {
270                ((Folder) d.dragSource).deferCompleteDropAfterUninstallActivity();
271            } else if (d.dragSource instanceof Workspace) {
272                ((Workspace) d.dragSource).deferCompleteDropAfterUninstallActivity();
273            }
274            mWaitingForUninstall = true;
275        }
276    }
277
278    private boolean isUninstallFromWorkspace(DragObject d) {
279        if (LauncherAppState.isDisableAllApps() && isWorkspaceOrFolderApplication(d)) {
280            ShortcutInfo shortcut = (ShortcutInfo) d.dragInfo;
281            // Only allow manifest shortcuts to initiate an un-install.
282            return !InstallShortcutReceiver.isValidShortcutLaunchIntent(shortcut.intent);
283        }
284        return false;
285    }
286
287    private void completeDrop(DragObject d) {
288        ItemInfo item = (ItemInfo) d.dragInfo;
289        boolean wasWaitingForUninstall = mWaitingForUninstall;
290        mWaitingForUninstall = false;
291        if (isAllAppsApplication(d.dragSource, item)) {
292            // Uninstall the application if it is being dragged from AppsCustomize
293            AppInfo appInfo = (AppInfo) item;
294            mLauncher.startApplicationUninstallActivity(appInfo.componentName, appInfo.flags,
295                    appInfo.user);
296        } else if (isUninstallFromWorkspace(d)) {
297            ShortcutInfo shortcut = (ShortcutInfo) item;
298            if (shortcut.intent != null && shortcut.intent.getComponent() != null) {
299                final ComponentName componentName = shortcut.intent.getComponent();
300                final DragSource dragSource = d.dragSource;
301                final UserHandleCompat user = shortcut.user;
302                mWaitingForUninstall = mLauncher.startApplicationUninstallActivity(
303                        componentName, shortcut.flags, user);
304                if (mWaitingForUninstall) {
305                    final Runnable checkIfUninstallWasSuccess = new Runnable() {
306                        @Override
307                        public void run() {
308                            mWaitingForUninstall = false;
309                            String packageName = componentName.getPackageName();
310                            boolean uninstallSuccessful = !AllAppsList.packageHasActivities(
311                                    getContext(), packageName, user);
312                            if (dragSource instanceof Folder) {
313                                ((Folder) dragSource).
314                                    onUninstallActivityReturned(uninstallSuccessful);
315                            } else if (dragSource instanceof Workspace) {
316                                ((Workspace) dragSource).
317                                    onUninstallActivityReturned(uninstallSuccessful);
318                            }
319                        }
320                    };
321                    mLauncher.addOnResumeCallback(checkIfUninstallWasSuccess);
322                }
323            }
324        } else if (isWorkspaceOrFolderApplication(d)) {
325            LauncherModel.deleteItemFromDatabase(mLauncher, item);
326        } else if (isWorkspaceFolder(d)) {
327            // Remove the folder from the workspace and delete the contents from launcher model
328            FolderInfo folderInfo = (FolderInfo) item;
329            mLauncher.removeFolder(folderInfo);
330            LauncherModel.deleteFolderContentsFromDatabase(mLauncher, folderInfo);
331        } else if (isWorkspaceOrFolderWidget(d)) {
332            // Remove the widget from the workspace
333            mLauncher.removeAppWidget((LauncherAppWidgetInfo) item);
334            LauncherModel.deleteItemFromDatabase(mLauncher, item);
335
336            final LauncherAppWidgetInfo launcherAppWidgetInfo = (LauncherAppWidgetInfo) item;
337            final LauncherAppWidgetHost appWidgetHost = mLauncher.getAppWidgetHost();
338            if ((appWidgetHost != null) && launcherAppWidgetInfo.isWidgetIdValid()) {
339                // Deleting an app widget ID is a void call but writes to disk before returning
340                // to the caller...
341                new AsyncTask<Void, Void, Void>() {
342                    public Void doInBackground(Void ... args) {
343                        appWidgetHost.deleteAppWidgetId(launcherAppWidgetInfo.appWidgetId);
344                        return null;
345                    }
346                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
347            }
348        }
349        if (wasWaitingForUninstall && !mWaitingForUninstall) {
350            if (d.dragSource instanceof Folder) {
351                ((Folder) d.dragSource).onUninstallActivityReturned(false);
352            } else if (d.dragSource instanceof Workspace) {
353                ((Workspace) d.dragSource).onUninstallActivityReturned(false);
354            }
355        }
356    }
357
358    public void onDrop(DragObject d) {
359        animateToTrashAndCompleteDrop(d);
360    }
361
362    /**
363     * Creates an animation from the current drag view to the delete trash icon.
364     */
365    private AnimatorUpdateListener createFlingToTrashAnimatorListener(final DragLayer dragLayer,
366            DragObject d, PointF vel, ViewConfiguration config) {
367        final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(),
368                mCurrentDrawable.getIntrinsicWidth(), mCurrentDrawable.getIntrinsicHeight());
369        final Rect from = new Rect();
370        dragLayer.getViewRectRelativeToSelf(d.dragView, from);
371
372        // Calculate how far along the velocity vector we should put the intermediate point on
373        // the bezier curve
374        float velocity = Math.abs(vel.length());
375        float vp = Math.min(1f, velocity / (config.getScaledMaximumFlingVelocity() / 2f));
376        int offsetY = (int) (-from.top * vp);
377        int offsetX = (int) (offsetY / (vel.y / vel.x));
378        final float y2 = from.top + offsetY;                        // intermediate t/l
379        final float x2 = from.left + offsetX;
380        final float x1 = from.left;                                 // drag view t/l
381        final float y1 = from.top;
382        final float x3 = to.left;                                   // delete target t/l
383        final float y3 = to.top;
384
385        final TimeInterpolator scaleAlphaInterpolator = new TimeInterpolator() {
386            @Override
387            public float getInterpolation(float t) {
388                return t * t * t * t * t * t * t * t;
389            }
390        };
391        return new AnimatorUpdateListener() {
392            @Override
393            public void onAnimationUpdate(ValueAnimator animation) {
394                final DragView dragView = (DragView) dragLayer.getAnimatedView();
395                float t = ((Float) animation.getAnimatedValue()).floatValue();
396                float tp = scaleAlphaInterpolator.getInterpolation(t);
397                float initialScale = dragView.getInitialScale();
398                float finalAlpha = 0.5f;
399                float scale = dragView.getScaleX();
400                float x1o = ((1f - scale) * dragView.getMeasuredWidth()) / 2f;
401                float y1o = ((1f - scale) * dragView.getMeasuredHeight()) / 2f;
402                float x = (1f - t) * (1f - t) * (x1 - x1o) + 2 * (1f - t) * t * (x2 - x1o) +
403                        (t * t) * x3;
404                float y = (1f - t) * (1f - t) * (y1 - y1o) + 2 * (1f - t) * t * (y2 - x1o) +
405                        (t * t) * y3;
406
407                dragView.setTranslationX(x);
408                dragView.setTranslationY(y);
409                dragView.setScaleX(initialScale * (1f - tp));
410                dragView.setScaleY(initialScale * (1f - tp));
411                dragView.setAlpha(finalAlpha + (1f - finalAlpha) * (1f - tp));
412            }
413        };
414    }
415
416    /**
417     * Creates an animation from the current drag view along its current velocity vector.
418     * For this animation, the alpha runs for a fixed duration and we update the position
419     * progressively.
420     */
421    private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
422        private DragLayer mDragLayer;
423        private PointF mVelocity;
424        private Rect mFrom;
425        private long mPrevTime;
426        private boolean mHasOffsetForScale;
427        private float mFriction;
428
429        private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
430
431        public FlingAlongVectorAnimatorUpdateListener(DragLayer dragLayer, PointF vel, Rect from,
432                long startTime, float friction) {
433            mDragLayer = dragLayer;
434            mVelocity = vel;
435            mFrom = from;
436            mPrevTime = startTime;
437            mFriction = 1f - (dragLayer.getResources().getDisplayMetrics().density * friction);
438        }
439
440        @Override
441        public void onAnimationUpdate(ValueAnimator animation) {
442            final DragView dragView = (DragView) mDragLayer.getAnimatedView();
443            float t = ((Float) animation.getAnimatedValue()).floatValue();
444            long curTime = AnimationUtils.currentAnimationTimeMillis();
445
446            if (!mHasOffsetForScale) {
447                mHasOffsetForScale = true;
448                float scale = dragView.getScaleX();
449                float xOffset = ((scale - 1f) * dragView.getMeasuredWidth()) / 2f;
450                float yOffset = ((scale - 1f) * dragView.getMeasuredHeight()) / 2f;
451
452                mFrom.left += xOffset;
453                mFrom.top += yOffset;
454            }
455
456            mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
457            mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
458
459            dragView.setTranslationX(mFrom.left);
460            dragView.setTranslationY(mFrom.top);
461            dragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
462
463            mVelocity.x *= mFriction;
464            mVelocity.y *= mFriction;
465            mPrevTime = curTime;
466        }
467    };
468    private AnimatorUpdateListener createFlingAlongVectorAnimatorListener(final DragLayer dragLayer,
469            DragObject d, PointF vel, final long startTime, final int duration,
470            ViewConfiguration config) {
471        final Rect from = new Rect();
472        dragLayer.getViewRectRelativeToSelf(d.dragView, from);
473
474        return new FlingAlongVectorAnimatorUpdateListener(dragLayer, vel, from, startTime,
475                FLING_TO_DELETE_FRICTION);
476    }
477
478    public void onFlingToDelete(final DragObject d, int x, int y, PointF vel) {
479        final boolean isAllApps = d.dragSource instanceof AppsCustomizePagedView;
480
481        // Don't highlight the icon as it's animating
482        d.dragView.setColor(0);
483        d.dragView.updateInitialScaleToCurrentScale();
484        // Don't highlight the target if we are flinging from AllApps
485        if (isAllApps) {
486            resetHoverColor();
487        }
488
489        if (mFlingDeleteMode == MODE_FLING_DELETE_TO_TRASH) {
490            // Defer animating out the drop target if we are animating to it
491            mSearchDropTargetBar.deferOnDragEnd();
492            mSearchDropTargetBar.finishAnimations();
493        }
494
495        final ViewConfiguration config = ViewConfiguration.get(mLauncher);
496        final DragLayer dragLayer = mLauncher.getDragLayer();
497        final int duration = FLING_DELETE_ANIMATION_DURATION;
498        final long startTime = AnimationUtils.currentAnimationTimeMillis();
499
500        // NOTE: Because it takes time for the first frame of animation to actually be
501        // called and we expect the animation to be a continuation of the fling, we have
502        // to account for the time that has elapsed since the fling finished.  And since
503        // we don't have a startDelay, we will always get call to update when we call
504        // start() (which we want to ignore).
505        final TimeInterpolator tInterpolator = new TimeInterpolator() {
506            private int mCount = -1;
507            private float mOffset = 0f;
508
509            @Override
510            public float getInterpolation(float t) {
511                if (mCount < 0) {
512                    mCount++;
513                } else if (mCount == 0) {
514                    mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
515                            startTime) / duration);
516                    mCount++;
517                }
518                return Math.min(1f, mOffset + t);
519            }
520        };
521        AnimatorUpdateListener updateCb = null;
522        if (mFlingDeleteMode == MODE_FLING_DELETE_TO_TRASH) {
523            updateCb = createFlingToTrashAnimatorListener(dragLayer, d, vel, config);
524        } else if (mFlingDeleteMode == MODE_FLING_DELETE_ALONG_VECTOR) {
525            updateCb = createFlingAlongVectorAnimatorListener(dragLayer, d, vel, startTime,
526                    duration, config);
527        }
528        deferCompleteDropIfUninstalling(d);
529
530        Runnable onAnimationEndRunnable = new Runnable() {
531            @Override
532            public void run() {
533                // If we are dragging from AllApps, then we allow AppsCustomizePagedView to clean up
534                // itself, otherwise, complete the drop to initiate the deletion process
535                if (!isAllApps) {
536                    mLauncher.exitSpringLoadedDragMode();
537                    completeDrop(d);
538                }
539                mLauncher.getDragController().onDeferredEndFling(d);
540            }
541        };
542        dragLayer.animateView(d.dragView, updateCb, duration, tInterpolator, onAnimationEndRunnable,
543                DragLayer.ANIMATION_END_DISAPPEAR, null);
544    }
545}
546