DeleteDropTarget.java revision c05d313e5adf67f29a4fa2a08f44ff9f53b3d6e4
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.util.AttributeSet; 33import android.view.View; 34import android.view.ViewConfiguration; 35import android.view.ViewGroup; 36import android.view.animation.AnimationUtils; 37import android.view.animation.DecelerateInterpolator; 38import android.view.animation.LinearInterpolator; 39 40import java.util.List; 41import java.util.Set; 42 43public class DeleteDropTarget extends ButtonDropTarget { 44 private static int DELETE_ANIMATION_DURATION = 285; 45 private static int FLING_DELETE_ANIMATION_DURATION = 350; 46 private static float FLING_TO_DELETE_FRICTION = 0.035f; 47 private static int MODE_FLING_DELETE_TO_TRASH = 0; 48 private static int MODE_FLING_DELETE_ALONG_VECTOR = 1; 49 50 private final int mFlingDeleteMode = MODE_FLING_DELETE_ALONG_VECTOR; 51 52 private ColorStateList mOriginalTextColor; 53 private TransitionDrawable mUninstallDrawable; 54 private TransitionDrawable mRemoveDrawable; 55 private TransitionDrawable mCurrentDrawable; 56 57 private boolean mWaitingForUninstall = false; 58 59 public DeleteDropTarget(Context context, AttributeSet attrs) { 60 this(context, attrs, 0); 61 } 62 63 public DeleteDropTarget(Context context, AttributeSet attrs, int defStyle) { 64 super(context, attrs, defStyle); 65 } 66 67 @Override 68 protected void onFinishInflate() { 69 super.onFinishInflate(); 70 71 // Get the drawable 72 mOriginalTextColor = getTextColors(); 73 74 // Get the hover color 75 Resources r = getResources(); 76 mHoverColor = r.getColor(R.color.delete_target_hover_tint); 77 mUninstallDrawable = (TransitionDrawable) 78 r.getDrawable(R.drawable.uninstall_target_selector); 79 mRemoveDrawable = (TransitionDrawable) r.getDrawable(R.drawable.remove_target_selector); 80 81 mRemoveDrawable.setCrossFadeEnabled(true); 82 mUninstallDrawable.setCrossFadeEnabled(true); 83 84 // The current drawable is set to either the remove drawable or the uninstall drawable 85 // and is initially set to the remove drawable, as set in the layout xml. 86 mCurrentDrawable = (TransitionDrawable) getCurrentDrawable(); 87 88 // Remove the text in the Phone UI in landscape 89 int orientation = getResources().getConfiguration().orientation; 90 if (orientation == Configuration.ORIENTATION_LANDSCAPE) { 91 if (!LauncherAppState.getInstance().isScreenLarge()) { 92 setText(""); 93 } 94 } 95 } 96 97 private boolean isAllAppsApplication(DragSource source, Object info) { 98 return (source instanceof AppsCustomizePagedView) && (info instanceof AppInfo); 99 } 100 private boolean isAllAppsWidget(DragSource source, Object info) { 101 if (source instanceof AppsCustomizePagedView) { 102 if (info instanceof PendingAddItemInfo) { 103 PendingAddItemInfo addInfo = (PendingAddItemInfo) info; 104 switch (addInfo.itemType) { 105 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 106 case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: 107 return true; 108 } 109 } 110 } 111 return false; 112 } 113 private boolean isDragSourceWorkspaceOrFolder(DragObject d) { 114 return (d.dragSource instanceof Workspace) || (d.dragSource instanceof Folder); 115 } 116 private boolean isWorkspaceOrFolderApplication(DragObject d) { 117 return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof ShortcutInfo); 118 } 119 private boolean isWorkspaceOrFolderWidget(DragObject d) { 120 return isDragSourceWorkspaceOrFolder(d) && (d.dragInfo instanceof LauncherAppWidgetInfo); 121 } 122 private boolean isWorkspaceFolder(DragObject d) { 123 return (d.dragSource instanceof Workspace) && (d.dragInfo instanceof FolderInfo); 124 } 125 126 private void setHoverColor() { 127 mCurrentDrawable.startTransition(mTransitionDuration); 128 setTextColor(mHoverColor); 129 } 130 private void resetHoverColor() { 131 mCurrentDrawable.resetTransition(); 132 setTextColor(mOriginalTextColor); 133 } 134 135 @Override 136 public boolean acceptDrop(DragObject d) { 137 return willAcceptDrop(d.dragInfo); 138 } 139 140 public static boolean willAcceptDrop(Object info) { 141 if (info instanceof ItemInfo) { 142 ItemInfo item = (ItemInfo) info; 143 if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET || 144 item.itemType == LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT) { 145 return true; 146 } 147 148 if (!AppsCustomizePagedView.DISABLE_ALL_APPS && 149 item.itemType == LauncherSettings.Favorites.ITEM_TYPE_FOLDER) { 150 return true; 151 } 152 153 if (!AppsCustomizePagedView.DISABLE_ALL_APPS && 154 item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 155 item instanceof AppInfo) { 156 AppInfo appInfo = (AppInfo) info; 157 return (appInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0; 158 } 159 160 if (item.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && 161 item instanceof ShortcutInfo) { 162 if (AppsCustomizePagedView.DISABLE_ALL_APPS) { 163 ShortcutInfo shortcutInfo = (ShortcutInfo) info; 164 return (shortcutInfo.flags & AppInfo.DOWNLOADED_FLAG) != 0; 165 } else { 166 return true; 167 } 168 } 169 } 170 return false; 171 } 172 173 @Override 174 public void onDragStart(DragSource source, Object info, int dragAction) { 175 boolean isVisible = true; 176 boolean isUninstall = false; 177 178 // If we are dragging a widget from AppsCustomize, hide the delete target 179 if (isAllAppsWidget(source, info)) { 180 isVisible = false; 181 } 182 183 // If we are dragging an application from AppsCustomize, only show the control if we can 184 // delete the app (it was downloaded), and rename the string to "uninstall" in such a case 185 if (willAcceptDrop(info)) { 186 isVisible = true; 187 } else { 188 isVisible = false; 189 } 190 191 if (isUninstall) { 192 setCompoundDrawablesRelativeWithIntrinsicBounds(mUninstallDrawable, null, null, null); 193 } else { 194 setCompoundDrawablesRelativeWithIntrinsicBounds(mRemoveDrawable, null, null, null); 195 } 196 mCurrentDrawable = (TransitionDrawable) getCurrentDrawable(); 197 198 mActive = isVisible; 199 resetHoverColor(); 200 ((ViewGroup) getParent()).setVisibility(isVisible ? View.VISIBLE : View.GONE); 201 if (getText().length() > 0) { 202 setText(isUninstall ? R.string.delete_target_uninstall_label 203 : R.string.delete_target_label); 204 } 205 } 206 207 @Override 208 public void onDragEnd() { 209 super.onDragEnd(); 210 mActive = false; 211 } 212 213 public void onDragEnter(DragObject d) { 214 super.onDragEnter(d); 215 216 setHoverColor(); 217 } 218 219 public void onDragExit(DragObject d) { 220 super.onDragExit(d); 221 222 if (!d.dragComplete) { 223 resetHoverColor(); 224 } else { 225 // Restore the hover color if we are deleting 226 d.dragView.setColor(mHoverColor); 227 } 228 } 229 230 private void animateToTrashAndCompleteDrop(final DragObject d) { 231 final DragLayer dragLayer = mLauncher.getDragLayer(); 232 final Rect from = new Rect(); 233 dragLayer.getViewRectRelativeToSelf(d.dragView, from); 234 final Rect to = getIconRect(d.dragView.getMeasuredWidth(), d.dragView.getMeasuredHeight(), 235 mCurrentDrawable.getIntrinsicWidth(), mCurrentDrawable.getIntrinsicHeight()); 236 final float scale = (float) to.width() / from.width(); 237 238 mSearchDropTargetBar.deferOnDragEnd(); 239 deferCompleteDropIfUninstalling(d); 240 241 Runnable onAnimationEndRunnable = new Runnable() { 242 @Override 243 public void run() { 244 completeDrop(d); 245 mSearchDropTargetBar.onDragEnd(); 246 mLauncher.exitSpringLoadedDragMode(); 247 } 248 }; 249 dragLayer.animateView(d.dragView, from, to, scale, 1f, 1f, 0.1f, 0.1f, 250 DELETE_ANIMATION_DURATION, new DecelerateInterpolator(2), 251 new LinearInterpolator(), onAnimationEndRunnable, 252 DragLayer.ANIMATION_END_DISAPPEAR, null); 253 } 254 255 private void deferCompleteDropIfUninstalling(DragObject d) { 256 mWaitingForUninstall = false; 257 if (isUninstallFromWorkspace(d)) { 258 if (d.dragSource instanceof Folder) { 259 ((Folder) d.dragSource).deferCompleteDropAfterUninstallActivity(); 260 } else if (d.dragSource instanceof Workspace) { 261 ((Workspace) d.dragSource).deferCompleteDropAfterUninstallActivity(); 262 } 263 mWaitingForUninstall = true; 264 } 265 } 266 267 private boolean isUninstallFromWorkspace(DragObject d) { 268 if (AppsCustomizePagedView.DISABLE_ALL_APPS && isWorkspaceOrFolderApplication(d)) { 269 ShortcutInfo shortcut = (ShortcutInfo) d.dragInfo; 270 if (shortcut.intent != null && shortcut.intent.getComponent() != null) { 271 Set<String> categories = shortcut.intent.getCategories(); 272 boolean includesLauncherCategory = false; 273 if (categories != null) { 274 for (String category : categories) { 275 if (category.equals(Intent.CATEGORY_LAUNCHER)) { 276 includesLauncherCategory = true; 277 break; 278 } 279 } 280 } 281 return includesLauncherCategory; 282 } 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 } else if (isUninstallFromWorkspace(d)) { 296 ShortcutInfo shortcut = (ShortcutInfo) item; 297 if (shortcut.intent != null && shortcut.intent.getComponent() != null) { 298 final ComponentName componentName = shortcut.intent.getComponent(); 299 final DragSource dragSource = d.dragSource; 300 int flags = AppInfo.initFlags( 301 ShortcutInfo.getPackageInfo(getContext(), componentName.getPackageName())); 302 mWaitingForUninstall = 303 mLauncher.startApplicationUninstallActivity(componentName, flags); 304 if (mWaitingForUninstall) { 305 final Runnable checkIfUninstallWasSuccess = new Runnable() { 306 @Override 307 public void run() { 308 mWaitingForUninstall = false; 309 String packageName = componentName.getPackageName(); 310 List<ResolveInfo> activities = 311 AllAppsList.findActivitiesForPackage(getContext(), packageName); 312 boolean uninstallSuccessful = activities.size() == 0; 313 if (dragSource instanceof Folder) { 314 ((Folder) dragSource). 315 onUninstallActivityReturned(uninstallSuccessful); 316 } else if (dragSource instanceof Workspace) { 317 ((Workspace) dragSource). 318 onUninstallActivityReturned(uninstallSuccessful); 319 } 320 } 321 }; 322 mLauncher.addOnResumeCallback(checkIfUninstallWasSuccess); 323 } 324 } 325 } else if (isWorkspaceOrFolderApplication(d)) { 326 LauncherModel.deleteItemFromDatabase(mLauncher, item); 327 } else if (isWorkspaceFolder(d)) { 328 // Remove the folder from the workspace and delete the contents from launcher model 329 FolderInfo folderInfo = (FolderInfo) item; 330 mLauncher.removeFolder(folderInfo); 331 LauncherModel.deleteFolderContentsFromDatabase(mLauncher, folderInfo); 332 } else if (isWorkspaceOrFolderWidget(d)) { 333 // Remove the widget from the workspace 334 mLauncher.removeAppWidget((LauncherAppWidgetInfo) item); 335 LauncherModel.deleteItemFromDatabase(mLauncher, item); 336 337 final LauncherAppWidgetInfo launcherAppWidgetInfo = (LauncherAppWidgetInfo) item; 338 final LauncherAppWidgetHost appWidgetHost = mLauncher.getAppWidgetHost(); 339 if (appWidgetHost != null) { 340 // Deleting an app widget ID is a void call but writes to disk before returning 341 // to the caller... 342 new Thread("deleteAppWidgetId") { 343 public void run() { 344 appWidgetHost.deleteAppWidgetId(launcherAppWidgetInfo.appWidgetId); 345 } 346 }.start(); 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