AppsCustomizePagedView.java revision 7c7c66d3f3c299ee05c10a632644bc74f2c5bfdb
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.launcher2; 18 19import android.animation.AnimatorSet; 20import android.animation.ValueAnimator; 21import android.appwidget.AppWidgetHostView; 22import android.appwidget.AppWidgetManager; 23import android.appwidget.AppWidgetProviderInfo; 24import android.content.ComponentName; 25import android.content.Context; 26import android.content.Intent; 27import android.content.pm.PackageManager; 28import android.content.pm.ResolveInfo; 29import android.content.res.Configuration; 30import android.content.res.Resources; 31import android.content.res.TypedArray; 32import android.graphics.Bitmap; 33import android.graphics.Bitmap.Config; 34import android.graphics.Canvas; 35import android.graphics.ColorMatrix; 36import android.graphics.ColorMatrixColorFilter; 37import android.graphics.Matrix; 38import android.graphics.Paint; 39import android.graphics.PorterDuff; 40import android.graphics.Rect; 41import android.graphics.RectF; 42import android.graphics.Shader; 43import android.graphics.drawable.BitmapDrawable; 44import android.graphics.drawable.Drawable; 45import android.os.AsyncTask; 46import android.os.Process; 47import android.util.AttributeSet; 48import android.util.Log; 49import android.view.Gravity; 50import android.view.KeyEvent; 51import android.view.LayoutInflater; 52import android.view.MotionEvent; 53import android.view.View; 54import android.view.ViewGroup; 55import android.view.animation.AccelerateInterpolator; 56import android.view.animation.DecelerateInterpolator; 57import android.widget.GridLayout; 58import android.widget.ImageView; 59import android.widget.Toast; 60 61import com.android.launcher.R; 62import com.android.launcher2.DropTarget.DragObject; 63 64import java.lang.ref.WeakReference; 65import java.util.ArrayList; 66import java.util.Collections; 67import java.util.Iterator; 68import java.util.List; 69 70/** 71 * A simple callback interface which also provides the results of the task. 72 */ 73interface AsyncTaskCallback { 74 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); 75} 76 77/** 78 * The data needed to perform either of the custom AsyncTasks. 79 */ 80class AsyncTaskPageData { 81 enum Type { 82 LoadWidgetPreviewData 83 } 84 85 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, 86 AsyncTaskCallback postR) { 87 page = p; 88 items = l; 89 sourceImages = si; 90 generatedImages = new ArrayList<Bitmap>(); 91 maxImageWidth = maxImageHeight = -1; 92 doInBackgroundCallback = bgR; 93 postExecuteCallback = postR; 94 } 95 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR, 96 AsyncTaskCallback postR) { 97 page = p; 98 items = l; 99 generatedImages = new ArrayList<Bitmap>(); 100 maxImageWidth = cw; 101 maxImageHeight = ch; 102 doInBackgroundCallback = bgR; 103 postExecuteCallback = postR; 104 } 105 void cleanup(boolean cancelled) { 106 // Clean up any references to source/generated bitmaps 107 if (sourceImages != null) { 108 if (cancelled) { 109 for (Bitmap b : sourceImages) { 110 b.recycle(); 111 } 112 } 113 sourceImages.clear(); 114 } 115 if (generatedImages != null) { 116 if (cancelled) { 117 for (Bitmap b : generatedImages) { 118 b.recycle(); 119 } 120 } 121 generatedImages.clear(); 122 } 123 } 124 int page; 125 ArrayList<Object> items; 126 ArrayList<Bitmap> sourceImages; 127 ArrayList<Bitmap> generatedImages; 128 int maxImageWidth; 129 int maxImageHeight; 130 AsyncTaskCallback doInBackgroundCallback; 131 AsyncTaskCallback postExecuteCallback; 132} 133 134/** 135 * A generic template for an async task used in AppsCustomize. 136 */ 137class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { 138 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { 139 page = p; 140 threadPriority = Process.THREAD_PRIORITY_DEFAULT; 141 dataType = ty; 142 } 143 @Override 144 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { 145 if (params.length != 1) return null; 146 // Load each of the widget previews in the background 147 params[0].doInBackgroundCallback.run(this, params[0]); 148 return params[0]; 149 } 150 @Override 151 protected void onPostExecute(AsyncTaskPageData result) { 152 // All the widget previews are loaded, so we can just callback to inflate the page 153 result.postExecuteCallback.run(this, result); 154 } 155 156 void setThreadPriority(int p) { 157 threadPriority = p; 158 } 159 void syncThreadPriority() { 160 Process.setThreadPriority(threadPriority); 161 } 162 163 // The page that this async task is associated with 164 AsyncTaskPageData.Type dataType; 165 int page; 166 int threadPriority; 167} 168 169abstract class WeakReferenceThreadLocal<T> { 170 private ThreadLocal<WeakReference<T>> mThreadLocal; 171 public WeakReferenceThreadLocal() { 172 mThreadLocal = new ThreadLocal<WeakReference<T>>(); 173 } 174 175 abstract T initialValue(); 176 177 public void set(T t) { 178 mThreadLocal.set(new WeakReference<T>(t)); 179 } 180 181 public T get() { 182 WeakReference<T> reference = mThreadLocal.get(); 183 T obj; 184 if (reference == null) { 185 obj = initialValue(); 186 mThreadLocal.set(new WeakReference<T>(obj)); 187 return obj; 188 } else { 189 obj = reference.get(); 190 if (obj == null) { 191 obj = initialValue(); 192 mThreadLocal.set(new WeakReference<T>(obj)); 193 } 194 return obj; 195 } 196 } 197} 198 199class CanvasCache extends WeakReferenceThreadLocal<Canvas> { 200 @Override 201 protected Canvas initialValue() { 202 return new Canvas(); 203 } 204} 205 206class PaintCache extends WeakReferenceThreadLocal<Paint> { 207 @Override 208 protected Paint initialValue() { 209 return null; 210 } 211} 212 213class BitmapCache extends WeakReferenceThreadLocal<Bitmap> { 214 @Override 215 protected Bitmap initialValue() { 216 return null; 217 } 218} 219 220class RectCache extends WeakReferenceThreadLocal<Rect> { 221 @Override 222 protected Rect initialValue() { 223 return new Rect(); 224 } 225} 226 227/** 228 * The Apps/Customize page that displays all the applications, widgets, and shortcuts. 229 */ 230public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements 231 View.OnClickListener, View.OnKeyListener, DragSource, 232 PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener, 233 LauncherTransitionable { 234 static final String TAG = "AppsCustomizePagedView"; 235 236 /** 237 * The different content types that this paged view can show. 238 */ 239 public enum ContentType { 240 Applications, 241 Widgets 242 } 243 244 // Refs 245 private Launcher mLauncher; 246 private DragController mDragController; 247 private final LayoutInflater mLayoutInflater; 248 private final PackageManager mPackageManager; 249 250 // Save and Restore 251 private int mSaveInstanceStateItemIndex = -1; 252 private PagedViewIcon mPressedIcon; 253 254 // Content 255 private ArrayList<ApplicationInfo> mApps; 256 private ArrayList<Object> mWidgets; 257 258 // Cling 259 private boolean mHasShownAllAppsCling; 260 private int mClingFocusedX; 261 private int mClingFocusedY; 262 263 // Caching 264 private Canvas mCanvas; 265 private IconCache mIconCache; 266 267 // Dimens 268 private int mContentWidth; 269 private int mAppIconSize; 270 private int mMaxAppCellCountX, mMaxAppCellCountY; 271 private int mWidgetCountX, mWidgetCountY; 272 private int mWidgetWidthGap, mWidgetHeightGap; 273 private final float sWidgetPreviewIconPaddingPercentage = 0.25f; 274 private PagedViewCellLayout mWidgetSpacingLayout; 275 private int mNumAppsPages; 276 private int mNumWidgetPages; 277 278 // Relating to the scroll and overscroll effects 279 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); 280 private static float CAMERA_DISTANCE = 6500; 281 private static float TRANSITION_SCALE_FACTOR = 0.74f; 282 private static float TRANSITION_PIVOT = 0.65f; 283 private static float TRANSITION_MAX_ROTATION = 22; 284 private static final boolean PERFORM_OVERSCROLL_ROTATION = true; 285 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); 286 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4); 287 288 // Previews & outlines 289 ArrayList<AppsCustomizeAsyncTask> mRunningTasks; 290 private static final int sPageSleepDelay = 200; 291 292 private Runnable mInflateWidgetRunnable = null; 293 private Runnable mBindWidgetRunnable = null; 294 static final int WIDGET_NO_CLEANUP_REQUIRED = -1; 295 static final int WIDGET_PRELOAD_PENDING = 0; 296 static final int WIDGET_BOUND = 1; 297 static final int WIDGET_INFLATED = 2; 298 int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED; 299 int mWidgetLoadingId = -1; 300 PendingAddWidgetInfo mCreateWidgetInfo = null; 301 private boolean mDraggingWidget = false; 302 303 private Toast mWidgetInstructionToast; 304 305 // Deferral of loading widget previews during launcher transitions 306 private boolean mInTransition; 307 private ArrayList<AsyncTaskPageData> mDeferredSyncWidgetPageItems = 308 new ArrayList<AsyncTaskPageData>(); 309 private ArrayList<Runnable> mDeferredPrepareLoadWidgetPreviewsTasks = 310 new ArrayList<Runnable>(); 311 312 // Used for drawing shortcut previews 313 BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache(); 314 PaintCache mCachedShortcutPreviewPaint = new PaintCache(); 315 CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache(); 316 317 // Used for drawing widget previews 318 CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache(); 319 RectCache mCachedAppWidgetPreviewSrcRect = new RectCache(); 320 RectCache mCachedAppWidgetPreviewDestRect = new RectCache(); 321 PaintCache mCachedAppWidgetPreviewPaint = new PaintCache(); 322 323 public AppsCustomizePagedView(Context context, AttributeSet attrs) { 324 super(context, attrs); 325 mLayoutInflater = LayoutInflater.from(context); 326 mPackageManager = context.getPackageManager(); 327 mApps = new ArrayList<ApplicationInfo>(); 328 mWidgets = new ArrayList<Object>(); 329 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); 330 mCanvas = new Canvas(); 331 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>(); 332 333 // Save the default widget preview background 334 Resources resources = context.getResources(); 335 mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 336 337 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); 338 mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1); 339 mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1); 340 mWidgetWidthGap = 341 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0); 342 mWidgetHeightGap = 343 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0); 344 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); 345 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); 346 mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0); 347 mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0); 348 a.recycle(); 349 mWidgetSpacingLayout = new PagedViewCellLayout(getContext()); 350 351 // The padding on the non-matched dimension for the default widget preview icons 352 // (top + bottom) 353 mFadeInAdjacentScreens = false; 354 355 // Unless otherwise specified this view is important for accessibility. 356 if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 357 setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES); 358 } 359 } 360 361 @Override 362 protected void init() { 363 super.init(); 364 mCenterPagesVertically = false; 365 366 Context context = getContext(); 367 Resources r = context.getResources(); 368 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); 369 } 370 371 @Override 372 protected void onUnhandledTap(MotionEvent ev) { 373 if (LauncherApplication.isScreenLarge()) { 374 // Dismiss AppsCustomize if we tap 375 mLauncher.showWorkspace(true); 376 } 377 } 378 379 /** Returns the item index of the center item on this page so that we can restore to this 380 * item index when we rotate. */ 381 private int getMiddleComponentIndexOnCurrentPage() { 382 int i = -1; 383 if (getPageCount() > 0) { 384 int currentPage = getCurrentPage(); 385 if (currentPage < mNumAppsPages) { 386 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage); 387 PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout(); 388 int numItemsPerPage = mCellCountX * mCellCountY; 389 int childCount = childrenLayout.getChildCount(); 390 if (childCount > 0) { 391 i = (currentPage * numItemsPerPage) + (childCount / 2); 392 } 393 } else { 394 int numApps = mApps.size(); 395 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage); 396 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 397 int childCount = layout.getChildCount(); 398 if (childCount > 0) { 399 i = numApps + 400 ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2); 401 } 402 } 403 } 404 return i; 405 } 406 407 /** Get the index of the item to restore to if we need to restore the current page. */ 408 int getSaveInstanceStateIndex() { 409 if (mSaveInstanceStateItemIndex == -1) { 410 mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage(); 411 } 412 return mSaveInstanceStateItemIndex; 413 } 414 415 /** Returns the page in the current orientation which is expected to contain the specified 416 * item index. */ 417 int getPageForComponent(int index) { 418 if (index < 0) return 0; 419 420 if (index < mApps.size()) { 421 int numItemsPerPage = mCellCountX * mCellCountY; 422 return (index / numItemsPerPage); 423 } else { 424 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 425 return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage); 426 } 427 } 428 429 /** Restores the page for an item at the specified index */ 430 void restorePageForIndex(int index) { 431 if (index < 0) return; 432 mSaveInstanceStateItemIndex = index; 433 } 434 435 private void updatePageCounts() { 436 mNumWidgetPages = (int) Math.ceil(mWidgets.size() / 437 (float) (mWidgetCountX * mWidgetCountY)); 438 mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); 439 } 440 441 protected void onDataReady(int width, int height) { 442 // Note that we transpose the counts in portrait so that we get a similar layout 443 boolean isLandscape = getResources().getConfiguration().orientation == 444 Configuration.ORIENTATION_LANDSCAPE; 445 int maxCellCountX = Integer.MAX_VALUE; 446 int maxCellCountY = Integer.MAX_VALUE; 447 if (LauncherApplication.isScreenLarge()) { 448 maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() : 449 LauncherModel.getCellCountY()); 450 maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() : 451 LauncherModel.getCellCountX()); 452 } 453 if (mMaxAppCellCountX > -1) { 454 maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX); 455 } 456 if (mMaxAppCellCountY > -1) { 457 maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY); 458 } 459 460 // Now that the data is ready, we can calculate the content width, the number of cells to 461 // use for each page 462 mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 463 mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 464 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 465 mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY); 466 mCellCountX = mWidgetSpacingLayout.getCellCountX(); 467 mCellCountY = mWidgetSpacingLayout.getCellCountY(); 468 updatePageCounts(); 469 470 // Force a measure to update recalculate the gaps 471 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 472 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 473 mWidgetSpacingLayout.measure(widthSpec, heightSpec); 474 mContentWidth = mWidgetSpacingLayout.getContentWidth(); 475 476 AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost(); 477 final boolean hostIsTransitioning = host.isTransitioning(); 478 479 // Restore the page 480 int page = getPageForComponent(mSaveInstanceStateItemIndex); 481 invalidatePageData(Math.max(0, page), hostIsTransitioning); 482 483 // Show All Apps cling if we are finished transitioning, otherwise, we will try again when 484 // the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be 485 // returned while animating) 486 if (!hostIsTransitioning) { 487 post(new Runnable() { 488 @Override 489 public void run() { 490 showAllAppsCling(); 491 } 492 }); 493 } 494 } 495 496 void showAllAppsCling() { 497 if (!mHasShownAllAppsCling && isDataReady()) { 498 mHasShownAllAppsCling = true; 499 // Calculate the position for the cling punch through 500 int[] offset = new int[2]; 501 int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY); 502 mLauncher.getDragLayer().getLocationInDragLayer(this, offset); 503 // PagedViews are centered horizontally but top aligned 504 pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + 505 offset[0]; 506 pos[1] += offset[1]; 507 mLauncher.showFirstRunAllAppsCling(pos); 508 } 509 } 510 511 @Override 512 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 513 int width = MeasureSpec.getSize(widthMeasureSpec); 514 int height = MeasureSpec.getSize(heightMeasureSpec); 515 if (!isDataReady()) { 516 if (!mApps.isEmpty() && !mWidgets.isEmpty()) { 517 setDataIsReady(); 518 setMeasuredDimension(width, height); 519 onDataReady(width, height); 520 } 521 } 522 523 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 524 } 525 526 public void onPackagesUpdated() { 527 // Get the list of widgets and shortcuts 528 mWidgets.clear(); 529 List<AppWidgetProviderInfo> widgets = 530 AppWidgetManager.getInstance(mLauncher).getInstalledProviders(); 531 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 532 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0); 533 for (AppWidgetProviderInfo widget : widgets) { 534 if (widget.minWidth > 0 && widget.minHeight > 0) { 535 // Ensure that all widgets we show can be added on a workspace of this size 536 int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget); 537 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget); 538 int minSpanX = Math.min(spanXY[0], minSpanXY[0]); 539 int minSpanY = Math.min(spanXY[1], minSpanXY[1]); 540 if (minSpanX <= LauncherModel.getCellCountX() && 541 minSpanY <= LauncherModel.getCellCountY()) { 542 mWidgets.add(widget); 543 } else { 544 Log.e(TAG, "Widget " + widget.provider + " can not fit on this device (" + 545 widget.minWidth + ", " + widget.minHeight + ")"); 546 } 547 } else { 548 Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" + 549 widget.minWidth + ", " + widget.minHeight + ")"); 550 } 551 } 552 mWidgets.addAll(shortcuts); 553 Collections.sort(mWidgets, 554 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); 555 updatePageCounts(); 556 invalidateOnDataChange(); 557 } 558 559 @Override 560 public void onClick(View v) { 561 // When we have exited all apps or are in transition, disregard clicks 562 if (!mLauncher.isAllAppsCustomizeOpen() || 563 mLauncher.getWorkspace().isSwitchingState()) return; 564 565 if (v instanceof PagedViewIcon) { 566 // Animate some feedback to the click 567 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); 568 569 // Lock the drawable state to pressed until we return to Launcher 570 if (mPressedIcon != null) { 571 mPressedIcon.lockDrawableState(); 572 } 573 574 // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled 575 // to be consistent. So re-enable the flag here, and we will re-disable it as necessary 576 // when Launcher resumes and we are still in AllApps. 577 mLauncher.updateWallpaperVisibility(true); 578 mLauncher.startActivitySafely(v, appInfo.intent, appInfo); 579 580 } else if (v instanceof PagedViewWidget) { 581 // Let the user know that they have to long press to add a widget 582 if (mWidgetInstructionToast != null) { 583 mWidgetInstructionToast.cancel(); 584 } 585 mWidgetInstructionToast = Toast.makeText(getContext(),R.string.long_press_widget_to_add, 586 Toast.LENGTH_SHORT); 587 mWidgetInstructionToast.show(); 588 589 // Create a little animation to show that the widget can move 590 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 591 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); 592 AnimatorSet bounce = LauncherAnimUtils.createAnimatorSet(); 593 ValueAnimator tyuAnim = LauncherAnimUtils.ofFloat(p, "translationY", offsetY); 594 tyuAnim.setDuration(125); 595 ValueAnimator tydAnim = LauncherAnimUtils.ofFloat(p, "translationY", 0f); 596 tydAnim.setDuration(100); 597 bounce.play(tyuAnim).before(tydAnim); 598 bounce.setInterpolator(new AccelerateInterpolator()); 599 bounce.start(); 600 } 601 } 602 603 public boolean onKey(View v, int keyCode, KeyEvent event) { 604 return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event); 605 } 606 607 /* 608 * PagedViewWithDraggableItems implementation 609 */ 610 @Override 611 protected void determineDraggingStart(android.view.MotionEvent ev) { 612 // Disable dragging by pulling an app down for now. 613 } 614 615 private void beginDraggingApplication(View v) { 616 mLauncher.getWorkspace().onDragStartedWithItem(v); 617 mLauncher.getWorkspace().beginDragShared(v, this); 618 } 619 620 private void preloadWidget(final PendingAddWidgetInfo info) { 621 final AppWidgetProviderInfo pInfo = info.info; 622 if (pInfo.configure != null) { 623 return; 624 } 625 626 mWidgetCleanupState = WIDGET_PRELOAD_PENDING; 627 mBindWidgetRunnable = new Runnable() { 628 @Override 629 public void run() { 630 mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId(); 631 if (AppWidgetManager.getInstance(mLauncher) 632 .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) { 633 mWidgetCleanupState = WIDGET_BOUND; 634 } 635 } 636 }; 637 post(mBindWidgetRunnable); 638 639 mInflateWidgetRunnable = new Runnable() { 640 @Override 641 public void run() { 642 AppWidgetHostView hostView = mLauncher. 643 getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo); 644 info.boundWidget = hostView; 645 mWidgetCleanupState = WIDGET_INFLATED; 646 hostView.setVisibility(INVISIBLE); 647 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX, 648 info.spanY, info, false); 649 650 // We want the first widget layout to be the correct size. This will be important 651 // for width size reporting to the AppWidgetManager. 652 DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0], 653 unScaledSize[1]); 654 lp.x = lp.y = 0; 655 lp.customPosition = true; 656 hostView.setLayoutParams(lp); 657 mLauncher.getDragLayer().addView(hostView); 658 } 659 }; 660 post(mInflateWidgetRunnable); 661 } 662 663 @Override 664 public void onShortPress(View v) { 665 // We are anticipating a long press, and we use this time to load bind and instantiate 666 // the widget. This will need to be cleaned up if it turns out no long press occurs. 667 if (mCreateWidgetInfo != null) { 668 // Just in case the cleanup process wasn't properly executed. This shouldn't happen. 669 cleanupWidgetPreloading(false); 670 } 671 mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag()); 672 preloadWidget(mCreateWidgetInfo); 673 } 674 675 private void cleanupWidgetPreloading(boolean widgetWasAdded) { 676 if (!widgetWasAdded) { 677 // If the widget was not added, we may need to do further cleanup. 678 PendingAddWidgetInfo info = mCreateWidgetInfo; 679 mCreateWidgetInfo = null; 680 681 if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) { 682 // We never did any preloading, so just remove pending callbacks to do so 683 removeCallbacks(mBindWidgetRunnable); 684 removeCallbacks(mInflateWidgetRunnable); 685 } else if (mWidgetCleanupState == WIDGET_BOUND) { 686 // Delete the widget id which was allocated 687 if (mWidgetLoadingId != -1) { 688 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId); 689 } 690 691 // We never got around to inflating the widget, so remove the callback to do so. 692 removeCallbacks(mInflateWidgetRunnable); 693 } else if (mWidgetCleanupState == WIDGET_INFLATED) { 694 // Delete the widget id which was allocated 695 if (mWidgetLoadingId != -1) { 696 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId); 697 } 698 699 // The widget was inflated and added to the DragLayer -- remove it. 700 AppWidgetHostView widget = info.boundWidget; 701 mLauncher.getDragLayer().removeView(widget); 702 } 703 } 704 mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED; 705 mWidgetLoadingId = -1; 706 mCreateWidgetInfo = null; 707 PagedViewWidget.resetShortPressTarget(); 708 } 709 710 @Override 711 public void cleanUpShortPress(View v) { 712 if (!mDraggingWidget) { 713 cleanupWidgetPreloading(false); 714 } 715 } 716 717 private boolean beginDraggingWidget(View v) { 718 mDraggingWidget = true; 719 // Get the widget preview as the drag representation 720 ImageView image = (ImageView) v.findViewById(R.id.widget_preview); 721 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); 722 723 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and 724 // we abort the drag. 725 if (image.getDrawable() == null) { 726 mDraggingWidget = false; 727 return false; 728 } 729 730 // Compose the drag image 731 Bitmap preview; 732 Bitmap outline; 733 float scale = 1f; 734 if (createItemInfo instanceof PendingAddWidgetInfo) { 735 // This can happen in some weird cases involving multi-touch. We can't start dragging 736 // the widget if this is null, so we break out. 737 if (mCreateWidgetInfo == null) { 738 return false; 739 } 740 741 PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo; 742 createItemInfo = createWidgetInfo; 743 int spanX = createItemInfo.spanX; 744 int spanY = createItemInfo.spanY; 745 int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY, 746 createWidgetInfo, true); 747 748 FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable(); 749 float minScale = 1.25f; 750 int maxWidth, maxHeight; 751 maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]); 752 maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]); 753 preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage, 754 createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight); 755 756 // Determine the image view drawable scale relative to the preview 757 float[] mv = new float[9]; 758 Matrix m = new Matrix(); 759 m.setRectToRect( 760 new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()), 761 new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(), 762 (float) previewDrawable.getIntrinsicHeight()), 763 Matrix.ScaleToFit.START); 764 m.getValues(mv); 765 scale = (float) mv[0]; 766 } else { 767 PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag(); 768 Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo); 769 preview = Bitmap.createBitmap(icon.getIntrinsicWidth(), 770 icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 771 772 mCanvas.setBitmap(preview); 773 mCanvas.save(); 774 renderDrawableToBitmap(icon, preview, 0, 0, 775 icon.getIntrinsicWidth(), icon.getIntrinsicHeight()); 776 mCanvas.restore(); 777 mCanvas.setBitmap(null); 778 createItemInfo.spanX = createItemInfo.spanY = 1; 779 } 780 781 // Don't clip alpha values for the drag outline if we're using the default widget preview 782 boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo && 783 (((PendingAddWidgetInfo) createItemInfo).previewImage == 0)); 784 785 // Save the preview for the outline generation, then dim the preview 786 outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(), 787 false); 788 789 // Start the drag 790 mLauncher.lockScreenOrientation(); 791 mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, clipAlpha); 792 mDragController.startDrag(image, preview, this, createItemInfo, 793 DragController.DRAG_ACTION_COPY, null, scale); 794 outline.recycle(); 795 preview.recycle(); 796 return true; 797 } 798 799 @Override 800 protected boolean beginDragging(final View v) { 801 if (!super.beginDragging(v)) return false; 802 803 if (v instanceof PagedViewIcon) { 804 beginDraggingApplication(v); 805 } else if (v instanceof PagedViewWidget) { 806 if (!beginDraggingWidget(v)) { 807 return false; 808 } 809 } 810 811 // We delay entering spring-loaded mode slightly to make sure the UI 812 // thready is free of any work. 813 postDelayed(new Runnable() { 814 @Override 815 public void run() { 816 // We don't enter spring-loaded mode if the drag has been cancelled 817 if (mLauncher.getDragController().isDragging()) { 818 // Dismiss the cling 819 mLauncher.dismissAllAppsCling(null); 820 821 // Reset the alpha on the dragged icon before we drag 822 resetDrawableState(); 823 824 // Go into spring loaded mode (must happen before we startDrag()) 825 mLauncher.enterSpringLoadedDragMode(); 826 } 827 } 828 }, 150); 829 830 return true; 831 } 832 833 /** 834 * Clean up after dragging. 835 * 836 * @param target where the item was dragged to (can be null if the item was flung) 837 */ 838 private void endDragging(View target, boolean isFlingToDelete, boolean success) { 839 if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() && 840 !(target instanceof DeleteDropTarget))) { 841 // Exit spring loaded mode if we have not successfully dropped or have not handled the 842 // drop in Workspace 843 mLauncher.exitSpringLoadedDragMode(); 844 } 845 mLauncher.unlockScreenOrientation(false); 846 } 847 848 @Override 849 public View getContent() { 850 return null; 851 } 852 853 @Override 854 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) { 855 mInTransition = true; 856 if (toWorkspace) { 857 cancelAllTasks(); 858 } 859 } 860 861 @Override 862 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 863 } 864 865 @Override 866 public void onLauncherTransitionStep(Launcher l, float t) { 867 } 868 869 @Override 870 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 871 mInTransition = false; 872 for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) { 873 onSyncWidgetPageItems(d); 874 } 875 mDeferredSyncWidgetPageItems.clear(); 876 for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) { 877 r.run(); 878 } 879 mDeferredPrepareLoadWidgetPreviewsTasks.clear(); 880 mForceDrawAllChildrenNextFrame = !toWorkspace; 881 } 882 883 @Override 884 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, 885 boolean success) { 886 // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling 887 if (isFlingToDelete) return; 888 889 endDragging(target, false, success); 890 891 // Display an error message if the drag failed due to there not being enough space on the 892 // target layout we were dropping on. 893 if (!success) { 894 boolean showOutOfSpaceMessage = false; 895 if (target instanceof Workspace) { 896 int currentScreen = mLauncher.getCurrentWorkspaceScreen(); 897 Workspace workspace = (Workspace) target; 898 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); 899 ItemInfo itemInfo = (ItemInfo) d.dragInfo; 900 if (layout != null) { 901 layout.calculateSpans(itemInfo); 902 showOutOfSpaceMessage = 903 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); 904 } 905 } 906 if (showOutOfSpaceMessage) { 907 mLauncher.showOutOfSpaceMessage(false); 908 } 909 910 d.deferDragViewCleanupPostAnimation = false; 911 } 912 cleanupWidgetPreloading(success); 913 mDraggingWidget = false; 914 } 915 916 @Override 917 public void onFlingToDeleteCompleted() { 918 // We just dismiss the drag when we fling, so cleanup here 919 endDragging(null, true, true); 920 cleanupWidgetPreloading(false); 921 mDraggingWidget = false; 922 } 923 924 @Override 925 public boolean supportsFlingToDelete() { 926 return true; 927 } 928 929 @Override 930 protected void onDetachedFromWindow() { 931 super.onDetachedFromWindow(); 932 cancelAllTasks(); 933 } 934 935 public void clearAllWidgetPages() { 936 cancelAllTasks(); 937 int count = getChildCount(); 938 for (int i = 0; i < count; i++) { 939 View v = getPageAt(i); 940 if (v instanceof PagedViewGridLayout) { 941 ((PagedViewGridLayout) v).removeAllViewsOnPage(); 942 mDirtyPageContent.set(i, true); 943 } 944 } 945 } 946 947 private void cancelAllTasks() { 948 // Clean up all the async tasks 949 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 950 while (iter.hasNext()) { 951 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 952 task.cancel(false); 953 iter.remove(); 954 mDirtyPageContent.set(task.page, true); 955 956 // We've already preallocated the views for the data to load into, so clear them as well 957 View v = getPageAt(task.page); 958 if (v instanceof PagedViewGridLayout) { 959 ((PagedViewGridLayout) v).removeAllViewsOnPage(); 960 } 961 } 962 mDeferredSyncWidgetPageItems.clear(); 963 mDeferredPrepareLoadWidgetPreviewsTasks.clear(); 964 } 965 966 public void setContentType(ContentType type) { 967 if (type == ContentType.Widgets) { 968 invalidatePageData(mNumAppsPages, true); 969 } else if (type == ContentType.Applications) { 970 invalidatePageData(0, true); 971 } 972 } 973 974 protected void snapToPage(int whichPage, int delta, int duration) { 975 super.snapToPage(whichPage, delta, duration); 976 updateCurrentTab(whichPage); 977 978 // Update the thread priorities given the direction lookahead 979 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 980 while (iter.hasNext()) { 981 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 982 int pageIndex = task.page; 983 if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) || 984 (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) { 985 task.setThreadPriority(getThreadPriorityForPage(pageIndex)); 986 } else { 987 task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST); 988 } 989 } 990 } 991 992 private void updateCurrentTab(int currentPage) { 993 AppsCustomizeTabHost tabHost = getTabHost(); 994 if (tabHost != null) { 995 String tag = tabHost.getCurrentTabTag(); 996 if (tag != null) { 997 if (currentPage >= mNumAppsPages && 998 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { 999 tabHost.setCurrentTabFromContent(ContentType.Widgets); 1000 } else if (currentPage < mNumAppsPages && 1001 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { 1002 tabHost.setCurrentTabFromContent(ContentType.Applications); 1003 } 1004 } 1005 } 1006 } 1007 1008 /* 1009 * Apps PagedView implementation 1010 */ 1011 private void setVisibilityOnChildren(ViewGroup layout, int visibility) { 1012 int childCount = layout.getChildCount(); 1013 for (int i = 0; i < childCount; ++i) { 1014 layout.getChildAt(i).setVisibility(visibility); 1015 } 1016 } 1017 private void setupPage(PagedViewCellLayout layout) { 1018 layout.setCellCount(mCellCountX, mCellCountY); 1019 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 1020 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 1021 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 1022 1023 // Note: We force a measure here to get around the fact that when we do layout calculations 1024 // immediately after syncing, we don't have a proper width. That said, we already know the 1025 // expected page width, so we can actually optimize by hiding all the TextView-based 1026 // children that are expensive to measure, and let that happen naturally later. 1027 setVisibilityOnChildren(layout, View.GONE); 1028 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 1029 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 1030 layout.setMinimumWidth(getPageContentWidth()); 1031 layout.measure(widthSpec, heightSpec); 1032 setVisibilityOnChildren(layout, View.VISIBLE); 1033 } 1034 1035 public void syncAppsPageItems(int page, boolean immediate) { 1036 // ensure that we have the right number of items on the pages 1037 int numCells = mCellCountX * mCellCountY; 1038 int startIndex = page * numCells; 1039 int endIndex = Math.min(startIndex + numCells, mApps.size()); 1040 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); 1041 1042 layout.removeAllViewsOnPage(); 1043 ArrayList<Object> items = new ArrayList<Object>(); 1044 ArrayList<Bitmap> images = new ArrayList<Bitmap>(); 1045 for (int i = startIndex; i < endIndex; ++i) { 1046 ApplicationInfo info = mApps.get(i); 1047 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( 1048 R.layout.apps_customize_application, layout, false); 1049 icon.applyFromApplicationInfo(info, true, this); 1050 icon.setOnClickListener(this); 1051 icon.setOnLongClickListener(this); 1052 icon.setOnTouchListener(this); 1053 icon.setOnKeyListener(this); 1054 1055 int index = i - startIndex; 1056 int x = index % mCellCountX; 1057 int y = index / mCellCountX; 1058 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 1059 1060 items.add(info); 1061 images.add(info.iconBitmap); 1062 } 1063 1064 layout.createHardwareLayers(); 1065 } 1066 1067 /** 1068 * A helper to return the priority for loading of the specified widget page. 1069 */ 1070 private int getWidgetPageLoadPriority(int page) { 1071 // If we are snapping to another page, use that index as the target page index 1072 int toPage = mCurrentPage; 1073 if (mNextPage > -1) { 1074 toPage = mNextPage; 1075 } 1076 1077 // We use the distance from the target page as an initial guess of priority, but if there 1078 // are no pages of higher priority than the page specified, then bump up the priority of 1079 // the specified page. 1080 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1081 int minPageDiff = Integer.MAX_VALUE; 1082 while (iter.hasNext()) { 1083 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1084 minPageDiff = Math.abs(task.page - toPage); 1085 } 1086 1087 int rawPageDiff = Math.abs(page - toPage); 1088 return rawPageDiff - Math.min(rawPageDiff, minPageDiff); 1089 } 1090 /** 1091 * Return the appropriate thread priority for loading for a given page (we give the current 1092 * page much higher priority) 1093 */ 1094 private int getThreadPriorityForPage(int page) { 1095 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below 1096 int pageDiff = getWidgetPageLoadPriority(page); 1097 if (pageDiff <= 0) { 1098 return Process.THREAD_PRIORITY_LESS_FAVORABLE; 1099 } else if (pageDiff <= 1) { 1100 return Process.THREAD_PRIORITY_LOWEST; 1101 } else { 1102 return Process.THREAD_PRIORITY_LOWEST; 1103 } 1104 } 1105 private int getSleepForPage(int page) { 1106 int pageDiff = getWidgetPageLoadPriority(page); 1107 return Math.max(0, pageDiff * sPageSleepDelay); 1108 } 1109 /** 1110 * Creates and executes a new AsyncTask to load a page of widget previews. 1111 */ 1112 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, 1113 int cellWidth, int cellHeight, int cellCountX) { 1114 1115 // Prune all tasks that are no longer needed 1116 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1117 while (iter.hasNext()) { 1118 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1119 int taskPage = task.page; 1120 if (taskPage < getAssociatedLowerPageBound(mCurrentPage) || 1121 taskPage > getAssociatedUpperPageBound(mCurrentPage)) { 1122 task.cancel(false); 1123 iter.remove(); 1124 } else { 1125 task.setThreadPriority(getThreadPriorityForPage(taskPage)); 1126 } 1127 } 1128 1129 // We introduce a slight delay to order the loading of side pages so that we don't thrash 1130 final int sleepMs = getSleepForPage(page); 1131 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, 1132 new AsyncTaskCallback() { 1133 @Override 1134 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 1135 try { 1136 try { 1137 Thread.sleep(sleepMs); 1138 } catch (Exception e) {} 1139 loadWidgetPreviewsInBackground(task, data); 1140 } finally { 1141 if (task.isCancelled()) { 1142 data.cleanup(true); 1143 } 1144 } 1145 } 1146 }, 1147 new AsyncTaskCallback() { 1148 @Override 1149 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 1150 mRunningTasks.remove(task); 1151 if (task.isCancelled()) return; 1152 // do cleanup inside onSyncWidgetPageItems 1153 onSyncWidgetPageItems(data); 1154 } 1155 }); 1156 1157 // Ensure that the task is appropriately prioritized and runs in parallel 1158 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, 1159 AsyncTaskPageData.Type.LoadWidgetPreviewData); 1160 t.setThreadPriority(getThreadPriorityForPage(page)); 1161 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); 1162 mRunningTasks.add(t); 1163 } 1164 1165 /* 1166 * Widgets PagedView implementation 1167 */ 1168 private void setupPage(PagedViewGridLayout layout) { 1169 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 1170 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 1171 1172 // Note: We force a measure here to get around the fact that when we do layout calculations 1173 // immediately after syncing, we don't have a proper width. 1174 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 1175 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 1176 layout.setMinimumWidth(getPageContentWidth()); 1177 layout.measure(widthSpec, heightSpec); 1178 } 1179 1180 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { 1181 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f); 1182 } 1183 1184 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 1185 float scale) { 1186 if (bitmap != null) { 1187 Canvas c = new Canvas(bitmap); 1188 c.scale(scale, scale); 1189 Rect oldBounds = d.copyBounds(); 1190 d.setBounds(x, y, x + w, y + h); 1191 d.draw(c); 1192 d.setBounds(oldBounds); // Restore the bounds 1193 c.setBitmap(null); 1194 } 1195 } 1196 1197 private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) { 1198 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get(); 1199 final Canvas c = mCachedShortcutPreviewCanvas.get(); 1200 if (tempBitmap == null || 1201 tempBitmap.getWidth() != maxWidth || 1202 tempBitmap.getHeight() != maxHeight) { 1203 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888); 1204 mCachedShortcutPreviewBitmap.set(tempBitmap); 1205 } else { 1206 c.setBitmap(tempBitmap); 1207 c.drawColor(0, PorterDuff.Mode.CLEAR); 1208 c.setBitmap(null); 1209 } 1210 // Render the icon 1211 Drawable icon = mIconCache.getFullResIcon(info); 1212 1213 int paddingTop = 1214 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top); 1215 int paddingLeft = 1216 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left); 1217 int paddingRight = 1218 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right); 1219 1220 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight); 1221 1222 renderDrawableToBitmap( 1223 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth); 1224 1225 Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888); 1226 c.setBitmap(preview); 1227 Paint p = mCachedShortcutPreviewPaint.get(); 1228 if (p == null) { 1229 p = new Paint(); 1230 ColorMatrix colorMatrix = new ColorMatrix(); 1231 colorMatrix.setSaturation(0); 1232 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); 1233 p.setAlpha((int) (255 * 0.06f)); 1234 //float density = 1f; 1235 //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL)); 1236 mCachedShortcutPreviewPaint.set(p); 1237 } 1238 c.drawBitmap(tempBitmap, 0, 0, p); 1239 c.setBitmap(null); 1240 1241 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize); 1242 1243 return preview; 1244 } 1245 1246 private Bitmap getWidgetPreview(ComponentName provider, int previewImage, 1247 int iconId, int cellHSpan, int cellVSpan, int maxWidth, 1248 int maxHeight) { 1249 // Load the preview image if possible 1250 String packageName = provider.getPackageName(); 1251 if (maxWidth < 0) maxWidth = Integer.MAX_VALUE; 1252 if (maxHeight < 0) maxHeight = Integer.MAX_VALUE; 1253 1254 Drawable drawable = null; 1255 if (previewImage != 0) { 1256 drawable = mPackageManager.getDrawable(packageName, previewImage, null); 1257 if (drawable == null) { 1258 Log.w(TAG, "Can't load widget preview drawable 0x" + 1259 Integer.toHexString(previewImage) + " for provider: " + provider); 1260 } 1261 } 1262 1263 int bitmapWidth; 1264 int bitmapHeight; 1265 Bitmap defaultPreview = null; 1266 boolean widgetPreviewExists = (drawable != null); 1267 if (widgetPreviewExists) { 1268 bitmapWidth = drawable.getIntrinsicWidth(); 1269 bitmapHeight = drawable.getIntrinsicHeight(); 1270 } else { 1271 // Generate a preview image if we couldn't load one 1272 if (cellHSpan < 1) cellHSpan = 1; 1273 if (cellVSpan < 1) cellVSpan = 1; 1274 1275 BitmapDrawable previewDrawable = (BitmapDrawable) getResources() 1276 .getDrawable(R.drawable.widget_preview_tile); 1277 final int previewDrawableWidth = previewDrawable 1278 .getIntrinsicWidth(); 1279 final int previewDrawableHeight = previewDrawable 1280 .getIntrinsicHeight(); 1281 bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips 1282 bitmapHeight = previewDrawableHeight * cellVSpan; 1283 1284 defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, 1285 Config.ARGB_8888); 1286 final Canvas c = mCachedAppWidgetPreviewCanvas.get(); 1287 c.setBitmap(defaultPreview); 1288 previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight); 1289 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT, 1290 Shader.TileMode.REPEAT); 1291 previewDrawable.draw(c); 1292 c.setBitmap(null); 1293 1294 // Draw the icon in the top left corner 1295 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); 1296 int smallestSide = Math.min(bitmapWidth, bitmapHeight); 1297 float iconScale = Math.min((float) smallestSide 1298 / (mAppIconSize + 2 * minOffset), 1f); 1299 1300 try { 1301 Drawable icon = null; 1302 int hoffset = 1303 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2); 1304 int yoffset = 1305 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2); 1306 if (iconId > 0) 1307 icon = mIconCache.getFullResIcon(packageName, iconId); 1308 if (icon != null) { 1309 renderDrawableToBitmap(icon, defaultPreview, hoffset, 1310 yoffset, (int) (mAppIconSize * iconScale), 1311 (int) (mAppIconSize * iconScale)); 1312 } 1313 } catch (Resources.NotFoundException e) { 1314 } 1315 } 1316 1317 // Scale to fit width only - let the widget preview be clipped in the 1318 // vertical dimension 1319 float scale = 1f; 1320 if (bitmapWidth > maxWidth) { 1321 scale = maxWidth / (float) bitmapWidth; 1322 } 1323 if (scale != 1f) { 1324 bitmapWidth = (int) (scale * bitmapWidth); 1325 bitmapHeight = (int) (scale * bitmapHeight); 1326 } 1327 1328 Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, 1329 Config.ARGB_8888); 1330 1331 // Draw the scaled preview into the final bitmap 1332 if (widgetPreviewExists) { 1333 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, 1334 bitmapHeight); 1335 } else { 1336 final Canvas c = mCachedAppWidgetPreviewCanvas.get(); 1337 final Rect src = mCachedAppWidgetPreviewSrcRect.get(); 1338 final Rect dest = mCachedAppWidgetPreviewDestRect.get(); 1339 c.setBitmap(preview); 1340 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight()); 1341 dest.set(0, 0, preview.getWidth(), preview.getHeight()); 1342 1343 Paint p = mCachedAppWidgetPreviewPaint.get(); 1344 if (p == null) { 1345 p = new Paint(); 1346 p.setFilterBitmap(true); 1347 mCachedAppWidgetPreviewPaint.set(p); 1348 } 1349 c.drawBitmap(defaultPreview, src, dest, p); 1350 c.setBitmap(null); 1351 } 1352 return preview; 1353 } 1354 1355 public void syncWidgetPageItems(final int page, final boolean immediate) { 1356 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 1357 1358 // Calculate the dimensions of each cell we are giving to each widget 1359 final ArrayList<Object> items = new ArrayList<Object>(); 1360 int contentWidth = mWidgetSpacingLayout.getContentWidth(); 1361 final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight 1362 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); 1363 int contentHeight = mWidgetSpacingLayout.getContentHeight(); 1364 final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom 1365 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); 1366 1367 // Prepare the set of widgets to load previews for in the background 1368 int offset = (page - mNumAppsPages) * numItemsPerPage; 1369 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { 1370 items.add(mWidgets.get(i)); 1371 } 1372 1373 // Prepopulate the pages with the other widget info, and fill in the previews later 1374 final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page); 1375 layout.setColumnCount(layout.getCellCountX()); 1376 for (int i = 0; i < items.size(); ++i) { 1377 Object rawInfo = items.get(i); 1378 PendingAddItemInfo createItemInfo = null; 1379 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( 1380 R.layout.apps_customize_widget, layout, false); 1381 if (rawInfo instanceof AppWidgetProviderInfo) { 1382 // Fill in the widget information 1383 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1384 createItemInfo = new PendingAddWidgetInfo(info, null, null); 1385 1386 // Determine the widget spans and min resize spans. 1387 int[] spanXY = Launcher.getSpanForWidget(mLauncher, info); 1388 createItemInfo.spanX = spanXY[0]; 1389 createItemInfo.spanY = spanXY[1]; 1390 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info); 1391 createItemInfo.minSpanX = minSpanXY[0]; 1392 createItemInfo.minSpanY = minSpanXY[1]; 1393 1394 widget.applyFromAppWidgetProviderInfo(info, -1, spanXY); 1395 widget.setTag(createItemInfo); 1396 widget.setShortPressListener(this); 1397 } else if (rawInfo instanceof ResolveInfo) { 1398 // Fill in the shortcuts information 1399 ResolveInfo info = (ResolveInfo) rawInfo; 1400 createItemInfo = new PendingAddShortcutInfo(info.activityInfo); 1401 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 1402 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, 1403 info.activityInfo.name); 1404 widget.applyFromResolveInfo(mPackageManager, info); 1405 widget.setTag(createItemInfo); 1406 } 1407 widget.setOnClickListener(this); 1408 widget.setOnLongClickListener(this); 1409 widget.setOnTouchListener(this); 1410 widget.setOnKeyListener(this); 1411 1412 // Layout each widget 1413 int ix = i % mWidgetCountX; 1414 int iy = i / mWidgetCountX; 1415 GridLayout.LayoutParams lp = new GridLayout.LayoutParams( 1416 GridLayout.spec(iy, GridLayout.LEFT), 1417 GridLayout.spec(ix, GridLayout.TOP)); 1418 lp.width = cellWidth; 1419 lp.height = cellHeight; 1420 lp.setGravity(Gravity.TOP | Gravity.LEFT); 1421 if (ix > 0) lp.leftMargin = mWidgetWidthGap; 1422 if (iy > 0) lp.topMargin = mWidgetHeightGap; 1423 layout.addView(widget, lp); 1424 } 1425 1426 // wait until a call on onLayout to start loading, because 1427 // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out 1428 // TODO: can we do a measure/layout immediately? 1429 layout.setOnLayoutListener(new Runnable() { 1430 public void run() { 1431 // Load the widget previews 1432 int maxPreviewWidth = cellWidth; 1433 int maxPreviewHeight = cellHeight; 1434 if (layout.getChildCount() > 0) { 1435 PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0); 1436 int[] maxSize = w.getPreviewSize(); 1437 maxPreviewWidth = maxSize[0]; 1438 maxPreviewHeight = maxSize[1]; 1439 } 1440 if (immediate) { 1441 AsyncTaskPageData data = new AsyncTaskPageData(page, items, 1442 maxPreviewWidth, maxPreviewHeight, null, null); 1443 loadWidgetPreviewsInBackground(null, data); 1444 onSyncWidgetPageItems(data); 1445 } else { 1446 if (mInTransition) { 1447 mDeferredPrepareLoadWidgetPreviewsTasks.add(this); 1448 } else { 1449 prepareLoadWidgetPreviewsTask(page, items, 1450 maxPreviewWidth, maxPreviewHeight, mWidgetCountX); 1451 } 1452 } 1453 } 1454 }); 1455 } 1456 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, 1457 AsyncTaskPageData data) { 1458 // loadWidgetPreviewsInBackground can be called without a task to load a set of widget 1459 // previews synchronously 1460 if (task != null) { 1461 // Ensure that this task starts running at the correct priority 1462 task.syncThreadPriority(); 1463 } 1464 1465 // Load each of the widget/shortcut previews 1466 ArrayList<Object> items = data.items; 1467 ArrayList<Bitmap> images = data.generatedImages; 1468 int count = items.size(); 1469 for (int i = 0; i < count; ++i) { 1470 if (task != null) { 1471 // Ensure we haven't been cancelled yet 1472 if (task.isCancelled()) break; 1473 // Before work on each item, ensure that this task is running at the correct 1474 // priority 1475 task.syncThreadPriority(); 1476 } 1477 1478 Object rawInfo = items.get(i); 1479 if (rawInfo instanceof AppWidgetProviderInfo) { 1480 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1481 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info); 1482 1483 int maxWidth = Math.min(data.maxImageWidth, 1484 mWidgetSpacingLayout.estimateCellWidth(cellSpans[0])); 1485 int maxHeight = Math.min(data.maxImageHeight, 1486 mWidgetSpacingLayout.estimateCellHeight(cellSpans[1])); 1487 Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon, 1488 cellSpans[0], cellSpans[1], maxWidth, maxHeight); 1489 images.add(b); 1490 } else if (rawInfo instanceof ResolveInfo) { 1491 // Fill in the shortcuts information 1492 ResolveInfo info = (ResolveInfo) rawInfo; 1493 images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight)); 1494 } 1495 } 1496 } 1497 1498 private void onSyncWidgetPageItems(AsyncTaskPageData data) { 1499 if (mInTransition) { 1500 mDeferredSyncWidgetPageItems.add(data); 1501 return; 1502 } 1503 try { 1504 int page = data.page; 1505 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page); 1506 1507 ArrayList<Object> items = data.items; 1508 int count = items.size(); 1509 for (int i = 0; i < count; ++i) { 1510 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); 1511 if (widget != null) { 1512 Bitmap preview = data.generatedImages.get(i); 1513 widget.applyPreview(new FastBitmapDrawable(preview), i); 1514 } 1515 } 1516 1517 layout.createHardwareLayer(); 1518 invalidate(); 1519 1520 // Update all thread priorities 1521 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1522 while (iter.hasNext()) { 1523 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1524 int pageIndex = task.page; 1525 task.setThreadPriority(getThreadPriorityForPage(pageIndex)); 1526 } 1527 } finally { 1528 data.cleanup(false); 1529 } 1530 } 1531 1532 @Override 1533 public void syncPages() { 1534 removeAllViews(); 1535 cancelAllTasks(); 1536 1537 Context context = getContext(); 1538 for (int j = 0; j < mNumWidgetPages; ++j) { 1539 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, 1540 mWidgetCountY); 1541 setupPage(layout); 1542 addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT, 1543 LayoutParams.MATCH_PARENT)); 1544 } 1545 1546 for (int i = 0; i < mNumAppsPages; ++i) { 1547 PagedViewCellLayout layout = new PagedViewCellLayout(context); 1548 setupPage(layout); 1549 addView(layout); 1550 } 1551 } 1552 1553 @Override 1554 public void syncPageItems(int page, boolean immediate) { 1555 if (page < mNumAppsPages) { 1556 syncAppsPageItems(page, immediate); 1557 } else { 1558 syncWidgetPageItems(page, immediate); 1559 } 1560 } 1561 1562 // We want our pages to be z-ordered such that the further a page is to the left, the higher 1563 // it is in the z-order. This is important to insure touch events are handled correctly. 1564 View getPageAt(int index) { 1565 return getChildAt(indexToPage(index)); 1566 } 1567 1568 @Override 1569 protected int indexToPage(int index) { 1570 return getChildCount() - index - 1; 1571 } 1572 1573 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. 1574 @Override 1575 protected void screenScrolled(int screenCenter) { 1576 super.screenScrolled(screenCenter); 1577 1578 for (int i = 0; i < getChildCount(); i++) { 1579 View v = getPageAt(i); 1580 if (v != null) { 1581 float scrollProgress = getScrollProgress(screenCenter, v, i); 1582 1583 float interpolatedProgress = 1584 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); 1585 float scale = (1 - interpolatedProgress) + 1586 interpolatedProgress * TRANSITION_SCALE_FACTOR; 1587 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); 1588 1589 float alpha; 1590 1591 if (scrollProgress < 0) { 1592 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1593 1 - Math.abs(scrollProgress)) : 1.0f; 1594 } else { 1595 // On large screens we need to fade the page as it nears its leftmost position 1596 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress); 1597 } 1598 1599 v.setCameraDistance(mDensity * CAMERA_DISTANCE); 1600 int pageWidth = v.getMeasuredWidth(); 1601 int pageHeight = v.getMeasuredHeight(); 1602 1603 if (PERFORM_OVERSCROLL_ROTATION) { 1604 if (i == 0 && scrollProgress < 0) { 1605 // Overscroll to the left 1606 v.setPivotX(TRANSITION_PIVOT * pageWidth); 1607 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1608 scale = 1.0f; 1609 alpha = 1.0f; 1610 // On the first page, we don't want the page to have any lateral motion 1611 translationX = 0; 1612 } else if (i == getChildCount() - 1 && scrollProgress > 0) { 1613 // Overscroll to the right 1614 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); 1615 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1616 scale = 1.0f; 1617 alpha = 1.0f; 1618 // On the last page, we don't want the page to have any lateral motion. 1619 translationX = 0; 1620 } else { 1621 v.setPivotY(pageHeight / 2.0f); 1622 v.setPivotX(pageWidth / 2.0f); 1623 v.setRotationY(0f); 1624 } 1625 } 1626 1627 v.setTranslationX(translationX); 1628 v.setScaleX(scale); 1629 v.setScaleY(scale); 1630 v.setAlpha(alpha); 1631 1632 // If the view has 0 alpha, we set it to be invisible so as to prevent 1633 // it from accepting touches 1634 if (alpha == 0) { 1635 v.setVisibility(INVISIBLE); 1636 } else if (v.getVisibility() != VISIBLE) { 1637 v.setVisibility(VISIBLE); 1638 } 1639 } 1640 } 1641 } 1642 1643 protected void overScroll(float amount) { 1644 acceleratedOverScroll(amount); 1645 } 1646 1647 /** 1648 * Used by the parent to get the content width to set the tab bar to 1649 * @return 1650 */ 1651 public int getPageContentWidth() { 1652 return mContentWidth; 1653 } 1654 1655 @Override 1656 protected void onPageEndMoving() { 1657 super.onPageEndMoving(); 1658 mForceDrawAllChildrenNextFrame = true; 1659 // We reset the save index when we change pages so that it will be recalculated on next 1660 // rotation 1661 mSaveInstanceStateItemIndex = -1; 1662 } 1663 1664 /* 1665 * AllAppsView implementation 1666 */ 1667 public void setup(Launcher launcher, DragController dragController) { 1668 mLauncher = launcher; 1669 mDragController = dragController; 1670 } 1671 1672 /** 1673 * We should call thise method whenever the core data changes (mApps, mWidgets) so that we can 1674 * appropriately determine when to invalidate the PagedView page data. In cases where the data 1675 * has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the 1676 * next onMeasure() pass, which will trigger an invalidatePageData() itself. 1677 */ 1678 private void invalidateOnDataChange() { 1679 if (!isDataReady()) { 1680 // The next layout pass will trigger data-ready if both widgets and apps are set, so 1681 // request a layout to trigger the page data when ready. 1682 requestLayout(); 1683 } else { 1684 cancelAllTasks(); 1685 invalidatePageData(); 1686 } 1687 } 1688 1689 public void setApps(ArrayList<ApplicationInfo> list) { 1690 mApps = list; 1691 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); 1692 updatePageCounts(); 1693 invalidateOnDataChange(); 1694 } 1695 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1696 // We add it in place, in alphabetical order 1697 int count = list.size(); 1698 for (int i = 0; i < count; ++i) { 1699 ApplicationInfo info = list.get(i); 1700 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); 1701 if (index < 0) { 1702 mApps.add(-(index + 1), info); 1703 } 1704 } 1705 } 1706 public void addApps(ArrayList<ApplicationInfo> list) { 1707 addAppsWithoutInvalidate(list); 1708 updatePageCounts(); 1709 invalidateOnDataChange(); 1710 } 1711 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { 1712 ComponentName removeComponent = item.intent.getComponent(); 1713 int length = list.size(); 1714 for (int i = 0; i < length; ++i) { 1715 ApplicationInfo info = list.get(i); 1716 if (info.intent.getComponent().equals(removeComponent)) { 1717 return i; 1718 } 1719 } 1720 return -1; 1721 } 1722 private int findAppByPackage(List<ApplicationInfo> list, String packageName) { 1723 int length = list.size(); 1724 for (int i = 0; i < length; ++i) { 1725 ApplicationInfo info = list.get(i); 1726 if (ItemInfo.getPackageName(info.intent).equals(packageName)) { 1727 return i; 1728 } 1729 } 1730 return -1; 1731 } 1732 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1733 // loop through all the apps and remove apps that have the same component 1734 int length = list.size(); 1735 for (int i = 0; i < length; ++i) { 1736 ApplicationInfo info = list.get(i); 1737 int removeIndex = findAppByComponent(mApps, info); 1738 if (removeIndex > -1) { 1739 Log.d(TAG, "Removing app in removeAppsWithoutInvalidate: " + info); 1740 mApps.remove(removeIndex); 1741 } 1742 } 1743 } 1744 private void removeAppsWithPackageNameWithoutInvalidate(ArrayList<String> packageNames) { 1745 // loop through all the package names and remove apps that have the same package name 1746 for (String pn : packageNames) { 1747 int removeIndex = findAppByPackage(mApps, pn); 1748 while (removeIndex > -1) { 1749 Log.d(TAG, "Removing app in removeAppsWithPackageNameWithoutInvalidate: " 1750 + mApps.get(removeIndex)); 1751 mApps.remove(removeIndex); 1752 removeIndex = findAppByPackage(mApps, pn); 1753 } 1754 } 1755 } 1756 public void removeApps(ArrayList<String> packageNames) { 1757 removeAppsWithPackageNameWithoutInvalidate(packageNames); 1758 updatePageCounts(); 1759 invalidateOnDataChange(); 1760 } 1761 public void updateApps(ArrayList<ApplicationInfo> list) { 1762 // We remove and re-add the updated applications list because it's properties may have 1763 // changed (ie. the title), and this will ensure that the items will be in their proper 1764 // place in the list. 1765 removeAppsWithoutInvalidate(list); 1766 addAppsWithoutInvalidate(list); 1767 updatePageCounts(); 1768 invalidateOnDataChange(); 1769 } 1770 1771 public void reset() { 1772 // If we have reset, then we should not continue to restore the previous state 1773 mSaveInstanceStateItemIndex = -1; 1774 1775 AppsCustomizeTabHost tabHost = getTabHost(); 1776 String tag = tabHost.getCurrentTabTag(); 1777 if (tag != null) { 1778 if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { 1779 tabHost.setCurrentTabFromContent(ContentType.Applications); 1780 } 1781 } 1782 1783 if (mCurrentPage != 0) { 1784 invalidatePageData(0); 1785 } 1786 } 1787 1788 private AppsCustomizeTabHost getTabHost() { 1789 return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane); 1790 } 1791 1792 public void dumpState() { 1793 // TODO: Dump information related to current list of Applications, Widgets, etc. 1794 ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps); 1795 dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets); 1796 } 1797 1798 private void dumpAppWidgetProviderInfoList(String tag, String label, 1799 ArrayList<Object> list) { 1800 Log.d(tag, label + " size=" + list.size()); 1801 for (Object i: list) { 1802 if (i instanceof AppWidgetProviderInfo) { 1803 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; 1804 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage 1805 + " resizeMode=" + info.resizeMode + " configure=" + info.configure 1806 + " initialLayout=" + info.initialLayout 1807 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); 1808 } else if (i instanceof ResolveInfo) { 1809 ResolveInfo info = (ResolveInfo) i; 1810 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" 1811 + info.icon); 1812 } 1813 } 1814 } 1815 1816 public void surrender() { 1817 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we 1818 // should stop this now. 1819 1820 // Stop all background tasks 1821 cancelAllTasks(); 1822 } 1823 1824 @Override 1825 public void iconPressed(PagedViewIcon icon) { 1826 // Reset the previously pressed icon and store a reference to the pressed icon so that 1827 // we can reset it on return to Launcher (in Launcher.onResume()) 1828 if (mPressedIcon != null) { 1829 mPressedIcon.resetDrawableState(); 1830 } 1831 mPressedIcon = icon; 1832 } 1833 1834 public void resetDrawableState() { 1835 if (mPressedIcon != null) { 1836 mPressedIcon.resetDrawableState(); 1837 mPressedIcon = null; 1838 } 1839 } 1840 1841 /* 1842 * We load an extra page on each side to prevent flashes from scrolling and loading of the 1843 * widget previews in the background with the AsyncTasks. 1844 */ 1845 final static int sLookBehindPageCount = 2; 1846 final static int sLookAheadPageCount = 2; 1847 protected int getAssociatedLowerPageBound(int page) { 1848 final int count = getChildCount(); 1849 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1); 1850 int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0); 1851 return windowMinIndex; 1852 } 1853 protected int getAssociatedUpperPageBound(int page) { 1854 final int count = getChildCount(); 1855 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1); 1856 int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1), 1857 count - 1); 1858 return windowMaxIndex; 1859 } 1860 1861 @Override 1862 protected String getCurrentPageDescription() { 1863 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 1864 int stringId = R.string.default_scroll_format; 1865 int count = 0; 1866 1867 if (page < mNumAppsPages) { 1868 stringId = R.string.apps_customize_apps_scroll_format; 1869 count = mNumAppsPages; 1870 } else { 1871 page -= mNumAppsPages; 1872 stringId = R.string.apps_customize_widgets_scroll_format; 1873 count = mNumWidgetPages; 1874 } 1875 1876 return String.format(getContext().getString(stringId), page + 1, count); 1877 } 1878} 1879