AppsCustomizePagedView.java revision acb5f99c64c24421cdaca1474f83871f9a2ba33c
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.MaskFilter; 38import android.graphics.Matrix; 39import android.graphics.Paint; 40import android.graphics.PorterDuff; 41import android.graphics.Rect; 42import android.graphics.RectF; 43import android.graphics.Shader; 44import android.graphics.TableMaskFilter; 45import android.graphics.drawable.BitmapDrawable; 46import android.graphics.drawable.Drawable; 47import android.os.AsyncTask; 48import android.os.Process; 49import android.util.AttributeSet; 50import android.util.Log; 51import android.view.Gravity; 52import android.view.KeyEvent; 53import android.view.LayoutInflater; 54import android.view.MotionEvent; 55import android.view.View; 56import android.view.ViewGroup; 57import android.view.animation.AccelerateInterpolator; 58import android.view.animation.DecelerateInterpolator; 59import android.widget.GridLayout; 60import android.widget.ImageView; 61import android.widget.Toast; 62 63import com.android.launcher.R; 64import com.android.launcher2.DropTarget.DragObject; 65 66import java.lang.ref.WeakReference; 67import java.util.ArrayList; 68import java.util.Collections; 69import java.util.Iterator; 70import java.util.List; 71 72/** 73 * A simple callback interface which also provides the results of the task. 74 */ 75interface AsyncTaskCallback { 76 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); 77} 78 79/** 80 * The data needed to perform either of the custom AsyncTasks. 81 */ 82class AsyncTaskPageData { 83 enum Type { 84 LoadWidgetPreviewData 85 } 86 87 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, 88 AsyncTaskCallback postR) { 89 page = p; 90 items = l; 91 sourceImages = si; 92 generatedImages = new ArrayList<Bitmap>(); 93 maxImageWidth = maxImageHeight = -1; 94 doInBackgroundCallback = bgR; 95 postExecuteCallback = postR; 96 } 97 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR, 98 AsyncTaskCallback postR) { 99 page = p; 100 items = l; 101 generatedImages = new ArrayList<Bitmap>(); 102 maxImageWidth = cw; 103 maxImageHeight = ch; 104 doInBackgroundCallback = bgR; 105 postExecuteCallback = postR; 106 } 107 void cleanup(boolean cancelled) { 108 // Clean up any references to source/generated bitmaps 109 if (sourceImages != null) { 110 if (cancelled) { 111 for (Bitmap b : sourceImages) { 112 b.recycle(); 113 } 114 } 115 sourceImages.clear(); 116 } 117 if (generatedImages != null) { 118 if (cancelled) { 119 for (Bitmap b : generatedImages) { 120 b.recycle(); 121 } 122 } 123 generatedImages.clear(); 124 } 125 } 126 int page; 127 ArrayList<Object> items; 128 ArrayList<Bitmap> sourceImages; 129 ArrayList<Bitmap> generatedImages; 130 int maxImageWidth; 131 int maxImageHeight; 132 AsyncTaskCallback doInBackgroundCallback; 133 AsyncTaskCallback postExecuteCallback; 134} 135 136/** 137 * A generic template for an async task used in AppsCustomize. 138 */ 139class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { 140 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { 141 page = p; 142 threadPriority = Process.THREAD_PRIORITY_DEFAULT; 143 dataType = ty; 144 } 145 @Override 146 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { 147 if (params.length != 1) return null; 148 // Load each of the widget previews in the background 149 params[0].doInBackgroundCallback.run(this, params[0]); 150 return params[0]; 151 } 152 @Override 153 protected void onPostExecute(AsyncTaskPageData result) { 154 // All the widget previews are loaded, so we can just callback to inflate the page 155 result.postExecuteCallback.run(this, result); 156 } 157 158 void setThreadPriority(int p) { 159 threadPriority = p; 160 } 161 void syncThreadPriority() { 162 Process.setThreadPriority(threadPriority); 163 } 164 165 // The page that this async task is associated with 166 AsyncTaskPageData.Type dataType; 167 int page; 168 int threadPriority; 169} 170 171abstract class WeakReferenceThreadLocal<T> { 172 private ThreadLocal<WeakReference<T>> mThreadLocal; 173 public WeakReferenceThreadLocal() { 174 mThreadLocal = new ThreadLocal<WeakReference<T>>(); 175 } 176 177 abstract T initialValue(); 178 179 public void set(T t) { 180 mThreadLocal.set(new WeakReference<T>(t)); 181 } 182 183 public T get() { 184 WeakReference<T> reference = mThreadLocal.get(); 185 T obj; 186 if (reference == null) { 187 obj = initialValue(); 188 mThreadLocal.set(new WeakReference<T>(obj)); 189 return obj; 190 } else { 191 obj = reference.get(); 192 if (obj == null) { 193 obj = initialValue(); 194 mThreadLocal.set(new WeakReference<T>(obj)); 195 } 196 return obj; 197 } 198 } 199} 200 201class CanvasCache extends WeakReferenceThreadLocal<Canvas> { 202 @Override 203 protected Canvas initialValue() { 204 return new Canvas(); 205 } 206} 207 208class PaintCache extends WeakReferenceThreadLocal<Paint> { 209 @Override 210 protected Paint initialValue() { 211 return null; 212 } 213} 214 215class BitmapCache extends WeakReferenceThreadLocal<Bitmap> { 216 @Override 217 protected Bitmap initialValue() { 218 return null; 219 } 220} 221 222class RectCache extends WeakReferenceThreadLocal<Rect> { 223 @Override 224 protected Rect initialValue() { 225 return new Rect(); 226 } 227} 228 229/** 230 * The Apps/Customize page that displays all the applications, widgets, and shortcuts. 231 */ 232public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements 233 View.OnClickListener, View.OnKeyListener, DragSource, 234 PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener, 235 LauncherTransitionable { 236 static final String TAG = "AppsCustomizePagedView"; 237 238 /** 239 * The different content types that this paged view can show. 240 */ 241 public enum ContentType { 242 Applications, 243 Widgets 244 } 245 246 // Refs 247 private Launcher mLauncher; 248 private DragController mDragController; 249 private final LayoutInflater mLayoutInflater; 250 private final PackageManager mPackageManager; 251 252 // Save and Restore 253 private int mSaveInstanceStateItemIndex = -1; 254 private PagedViewIcon mPressedIcon; 255 256 // Content 257 private ArrayList<ApplicationInfo> mApps; 258 private ArrayList<Object> mWidgets; 259 260 // Cling 261 private boolean mHasShownAllAppsCling; 262 private int mClingFocusedX; 263 private int mClingFocusedY; 264 265 // Caching 266 private Canvas mCanvas; 267 private IconCache mIconCache; 268 269 // Dimens 270 private int mContentWidth; 271 private int mAppIconSize; 272 private int mMaxAppCellCountX, mMaxAppCellCountY; 273 private int mWidgetCountX, mWidgetCountY; 274 private int mWidgetWidthGap, mWidgetHeightGap; 275 private final float sWidgetPreviewIconPaddingPercentage = 0.25f; 276 private PagedViewCellLayout mWidgetSpacingLayout; 277 private int mNumAppsPages; 278 private int mNumWidgetPages; 279 280 // Relating to the scroll and overscroll effects 281 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); 282 private static float CAMERA_DISTANCE = 6500; 283 private static float TRANSITION_SCALE_FACTOR = 0.74f; 284 private static float TRANSITION_PIVOT = 0.65f; 285 private static float TRANSITION_MAX_ROTATION = 22; 286 private static final boolean PERFORM_OVERSCROLL_ROTATION = true; 287 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); 288 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4); 289 290 // Previews & outlines 291 ArrayList<AppsCustomizeAsyncTask> mRunningTasks; 292 private static final int sPageSleepDelay = 200; 293 294 private Runnable mInflateWidgetRunnable = null; 295 private Runnable mBindWidgetRunnable = null; 296 static final int WIDGET_NO_CLEANUP_REQUIRED = -1; 297 static final int WIDGET_PRELOAD_PENDING = 0; 298 static final int WIDGET_BOUND = 1; 299 static final int WIDGET_INFLATED = 2; 300 int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED; 301 int mWidgetLoadingId = -1; 302 PendingAddWidgetInfo mCreateWidgetInfo = null; 303 private boolean mDraggingWidget = false; 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 Toast.makeText(getContext(), R.string.long_press_widget_to_add, 583 Toast.LENGTH_SHORT).show(); 584 585 // Create a little animation to show that the widget can move 586 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 587 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); 588 AnimatorSet bounce = LauncherAnimUtils.createAnimatorSet(); 589 ValueAnimator tyuAnim = LauncherAnimUtils.ofFloat(p, "translationY", offsetY); 590 tyuAnim.setDuration(125); 591 ValueAnimator tydAnim = LauncherAnimUtils.ofFloat(p, "translationY", 0f); 592 tydAnim.setDuration(100); 593 bounce.play(tyuAnim).before(tydAnim); 594 bounce.setInterpolator(new AccelerateInterpolator()); 595 bounce.start(); 596 } 597 } 598 599 public boolean onKey(View v, int keyCode, KeyEvent event) { 600 return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event); 601 } 602 603 /* 604 * PagedViewWithDraggableItems implementation 605 */ 606 @Override 607 protected void determineDraggingStart(android.view.MotionEvent ev) { 608 // Disable dragging by pulling an app down for now. 609 } 610 611 private void beginDraggingApplication(View v) { 612 mLauncher.getWorkspace().onDragStartedWithItem(v); 613 mLauncher.getWorkspace().beginDragShared(v, this); 614 } 615 616 private void preloadWidget(final PendingAddWidgetInfo info) { 617 final AppWidgetProviderInfo pInfo = info.info; 618 if (pInfo.configure != null) { 619 return; 620 } 621 622 mWidgetCleanupState = WIDGET_PRELOAD_PENDING; 623 mBindWidgetRunnable = new Runnable() { 624 @Override 625 public void run() { 626 mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId(); 627 if (AppWidgetManager.getInstance(mLauncher) 628 .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) { 629 mWidgetCleanupState = WIDGET_BOUND; 630 } 631 } 632 }; 633 post(mBindWidgetRunnable); 634 635 mInflateWidgetRunnable = new Runnable() { 636 @Override 637 public void run() { 638 AppWidgetHostView hostView = mLauncher. 639 getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo); 640 info.boundWidget = hostView; 641 mWidgetCleanupState = WIDGET_INFLATED; 642 hostView.setVisibility(INVISIBLE); 643 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX, 644 info.spanY, info, false); 645 646 // We want the first widget layout to be the correct size. This will be important 647 // for width size reporting to the AppWidgetManager. 648 DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0], 649 unScaledSize[1]); 650 lp.x = lp.y = 0; 651 lp.customPosition = true; 652 hostView.setLayoutParams(lp); 653 mLauncher.getDragLayer().addView(hostView); 654 } 655 }; 656 post(mInflateWidgetRunnable); 657 } 658 659 @Override 660 public void onShortPress(View v) { 661 // We are anticipating a long press, and we use this time to load bind and instantiate 662 // the widget. This will need to be cleaned up if it turns out no long press occurs. 663 if (mCreateWidgetInfo != null) { 664 // Just in case the cleanup process wasn't properly executed. This shouldn't happen. 665 cleanupWidgetPreloading(false); 666 } 667 mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag()); 668 preloadWidget(mCreateWidgetInfo); 669 } 670 671 private void cleanupWidgetPreloading(boolean widgetWasAdded) { 672 if (!widgetWasAdded) { 673 // If the widget was not added, we may need to do further cleanup. 674 PendingAddWidgetInfo info = mCreateWidgetInfo; 675 mCreateWidgetInfo = null; 676 677 if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) { 678 // We never did any preloading, so just remove pending callbacks to do so 679 removeCallbacks(mBindWidgetRunnable); 680 removeCallbacks(mInflateWidgetRunnable); 681 } else if (mWidgetCleanupState == WIDGET_BOUND) { 682 // Delete the widget id which was allocated 683 if (mWidgetLoadingId != -1) { 684 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId); 685 } 686 687 // We never got around to inflating the widget, so remove the callback to do so. 688 removeCallbacks(mInflateWidgetRunnable); 689 } else if (mWidgetCleanupState == WIDGET_INFLATED) { 690 // Delete the widget id which was allocated 691 if (mWidgetLoadingId != -1) { 692 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId); 693 } 694 695 // The widget was inflated and added to the DragLayer -- remove it. 696 AppWidgetHostView widget = info.boundWidget; 697 mLauncher.getDragLayer().removeView(widget); 698 } 699 } 700 mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED; 701 mWidgetLoadingId = -1; 702 mCreateWidgetInfo = null; 703 PagedViewWidget.resetShortPressTarget(); 704 } 705 706 @Override 707 public void cleanUpShortPress(View v) { 708 if (!mDraggingWidget) { 709 cleanupWidgetPreloading(false); 710 } 711 } 712 713 private boolean beginDraggingWidget(View v) { 714 mDraggingWidget = true; 715 // Get the widget preview as the drag representation 716 ImageView image = (ImageView) v.findViewById(R.id.widget_preview); 717 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); 718 719 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and 720 // we abort the drag. 721 if (image.getDrawable() == null) { 722 mDraggingWidget = false; 723 return false; 724 } 725 726 // Compose the drag image 727 Bitmap preview; 728 Bitmap outline; 729 float scale = 1f; 730 if (createItemInfo instanceof PendingAddWidgetInfo) { 731 // This can happen in some weird cases involving multi-touch. We can't start dragging 732 // the widget if this is null, so we break out. 733 if (mCreateWidgetInfo == null) { 734 return false; 735 } 736 737 PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo; 738 createItemInfo = createWidgetInfo; 739 int spanX = createItemInfo.spanX; 740 int spanY = createItemInfo.spanY; 741 int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY, 742 createWidgetInfo, true); 743 744 FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable(); 745 float minScale = 1.25f; 746 int maxWidth, maxHeight; 747 maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]); 748 maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]); 749 preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage, 750 createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight); 751 752 // Determine the image view drawable scale relative to the preview 753 float[] mv = new float[9]; 754 Matrix m = new Matrix(); 755 m.setRectToRect( 756 new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()), 757 new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(), 758 (float) previewDrawable.getIntrinsicHeight()), 759 Matrix.ScaleToFit.START); 760 m.getValues(mv); 761 scale = (float) mv[0]; 762 } else { 763 PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag(); 764 Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo); 765 preview = Bitmap.createBitmap(icon.getIntrinsicWidth(), 766 icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); 767 768 mCanvas.setBitmap(preview); 769 mCanvas.save(); 770 renderDrawableToBitmap(icon, preview, 0, 0, 771 icon.getIntrinsicWidth(), icon.getIntrinsicHeight()); 772 mCanvas.restore(); 773 mCanvas.setBitmap(null); 774 createItemInfo.spanX = createItemInfo.spanY = 1; 775 } 776 777 // We use a custom alpha clip table for the default widget previews 778 Paint alphaClipPaint = null; 779 if (createItemInfo instanceof PendingAddWidgetInfo) { 780 if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) { 781 MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255); 782 alphaClipPaint = new Paint(); 783 alphaClipPaint.setMaskFilter(alphaClipTable); 784 } 785 } 786 787 // Save the preview for the outline generation, then dim the preview 788 outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(), 789 false); 790 791 // Start the drag 792 alphaClipPaint = null; 793 mLauncher.lockScreenOrientation(); 794 mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint); 795 mDragController.startDrag(image, preview, this, createItemInfo, 796 DragController.DRAG_ACTION_COPY, null, scale); 797 outline.recycle(); 798 preview.recycle(); 799 return true; 800 } 801 802 @Override 803 protected boolean beginDragging(final View v) { 804 if (!super.beginDragging(v)) return false; 805 806 if (v instanceof PagedViewIcon) { 807 beginDraggingApplication(v); 808 } else if (v instanceof PagedViewWidget) { 809 if (!beginDraggingWidget(v)) { 810 return false; 811 } 812 } 813 814 // We delay entering spring-loaded mode slightly to make sure the UI 815 // thready is free of any work. 816 postDelayed(new Runnable() { 817 @Override 818 public void run() { 819 // We don't enter spring-loaded mode if the drag has been cancelled 820 if (mLauncher.getDragController().isDragging()) { 821 // Dismiss the cling 822 mLauncher.dismissAllAppsCling(null); 823 824 // Reset the alpha on the dragged icon before we drag 825 resetDrawableState(); 826 827 // Go into spring loaded mode (must happen before we startDrag()) 828 mLauncher.enterSpringLoadedDragMode(); 829 } 830 } 831 }, 150); 832 833 return true; 834 } 835 836 /** 837 * Clean up after dragging. 838 * 839 * @param target where the item was dragged to (can be null if the item was flung) 840 */ 841 private void endDragging(View target, boolean isFlingToDelete, boolean success) { 842 if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() && 843 !(target instanceof DeleteDropTarget))) { 844 // Exit spring loaded mode if we have not successfully dropped or have not handled the 845 // drop in Workspace 846 mLauncher.exitSpringLoadedDragMode(); 847 } 848 mLauncher.unlockScreenOrientation(false); 849 } 850 851 @Override 852 public View getContent() { 853 return null; 854 } 855 856 @Override 857 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) { 858 mInTransition = true; 859 if (toWorkspace) { 860 cancelAllTasks(); 861 } 862 } 863 864 @Override 865 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) { 866 } 867 868 @Override 869 public void onLauncherTransitionStep(Launcher l, float t) { 870 } 871 872 @Override 873 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) { 874 mInTransition = false; 875 for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) { 876 onSyncWidgetPageItems(d); 877 } 878 mDeferredSyncWidgetPageItems.clear(); 879 for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) { 880 r.run(); 881 } 882 mDeferredPrepareLoadWidgetPreviewsTasks.clear(); 883 mForceDrawAllChildrenNextFrame = !toWorkspace; 884 } 885 886 @Override 887 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, 888 boolean success) { 889 // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling 890 if (isFlingToDelete) return; 891 892 endDragging(target, false, success); 893 894 // Display an error message if the drag failed due to there not being enough space on the 895 // target layout we were dropping on. 896 if (!success) { 897 boolean showOutOfSpaceMessage = false; 898 if (target instanceof Workspace) { 899 int currentScreen = mLauncher.getCurrentWorkspaceScreen(); 900 Workspace workspace = (Workspace) target; 901 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); 902 ItemInfo itemInfo = (ItemInfo) d.dragInfo; 903 if (layout != null) { 904 layout.calculateSpans(itemInfo); 905 showOutOfSpaceMessage = 906 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); 907 } 908 } 909 if (showOutOfSpaceMessage) { 910 mLauncher.showOutOfSpaceMessage(false); 911 } 912 913 d.deferDragViewCleanupPostAnimation = false; 914 } 915 cleanupWidgetPreloading(success); 916 mDraggingWidget = false; 917 } 918 919 @Override 920 public void onFlingToDeleteCompleted() { 921 // We just dismiss the drag when we fling, so cleanup here 922 endDragging(null, true, true); 923 cleanupWidgetPreloading(false); 924 mDraggingWidget = false; 925 } 926 927 @Override 928 public boolean supportsFlingToDelete() { 929 return true; 930 } 931 932 @Override 933 protected void onDetachedFromWindow() { 934 super.onDetachedFromWindow(); 935 cancelAllTasks(); 936 } 937 938 public void clearAllWidgetPages() { 939 cancelAllTasks(); 940 int count = getChildCount(); 941 for (int i = 0; i < count; i++) { 942 View v = getPageAt(i); 943 if (v instanceof PagedViewGridLayout) { 944 ((PagedViewGridLayout) v).removeAllViewsOnPage(); 945 mDirtyPageContent.set(i, true); 946 } 947 } 948 } 949 950 private void cancelAllTasks() { 951 // Clean up all the async tasks 952 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 953 while (iter.hasNext()) { 954 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 955 task.cancel(false); 956 iter.remove(); 957 mDirtyPageContent.set(task.page, true); 958 959 // We've already preallocated the views for the data to load into, so clear them as well 960 View v = getPageAt(task.page); 961 if (v instanceof PagedViewGridLayout) { 962 ((PagedViewGridLayout) v).removeAllViewsOnPage(); 963 } 964 } 965 mDeferredSyncWidgetPageItems.clear(); 966 mDeferredPrepareLoadWidgetPreviewsTasks.clear(); 967 } 968 969 public void setContentType(ContentType type) { 970 if (type == ContentType.Widgets) { 971 invalidatePageData(mNumAppsPages, true); 972 } else if (type == ContentType.Applications) { 973 invalidatePageData(0, true); 974 } 975 } 976 977 protected void snapToPage(int whichPage, int delta, int duration) { 978 super.snapToPage(whichPage, delta, duration); 979 updateCurrentTab(whichPage); 980 981 // Update the thread priorities given the direction lookahead 982 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 983 while (iter.hasNext()) { 984 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 985 int pageIndex = task.page; 986 if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) || 987 (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) { 988 task.setThreadPriority(getThreadPriorityForPage(pageIndex)); 989 } else { 990 task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST); 991 } 992 } 993 } 994 995 private void updateCurrentTab(int currentPage) { 996 AppsCustomizeTabHost tabHost = getTabHost(); 997 if (tabHost != null) { 998 String tag = tabHost.getCurrentTabTag(); 999 if (tag != null) { 1000 if (currentPage >= mNumAppsPages && 1001 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { 1002 tabHost.setCurrentTabFromContent(ContentType.Widgets); 1003 } else if (currentPage < mNumAppsPages && 1004 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { 1005 tabHost.setCurrentTabFromContent(ContentType.Applications); 1006 } 1007 } 1008 } 1009 } 1010 1011 /* 1012 * Apps PagedView implementation 1013 */ 1014 private void setVisibilityOnChildren(ViewGroup layout, int visibility) { 1015 int childCount = layout.getChildCount(); 1016 for (int i = 0; i < childCount; ++i) { 1017 layout.getChildAt(i).setVisibility(visibility); 1018 } 1019 } 1020 private void setupPage(PagedViewCellLayout layout) { 1021 layout.setCellCount(mCellCountX, mCellCountY); 1022 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 1023 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 1024 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 1025 1026 // Note: We force a measure here to get around the fact that when we do layout calculations 1027 // immediately after syncing, we don't have a proper width. That said, we already know the 1028 // expected page width, so we can actually optimize by hiding all the TextView-based 1029 // children that are expensive to measure, and let that happen naturally later. 1030 setVisibilityOnChildren(layout, View.GONE); 1031 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 1032 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 1033 layout.setMinimumWidth(getPageContentWidth()); 1034 layout.measure(widthSpec, heightSpec); 1035 setVisibilityOnChildren(layout, View.VISIBLE); 1036 } 1037 1038 public void syncAppsPageItems(int page, boolean immediate) { 1039 // ensure that we have the right number of items on the pages 1040 int numCells = mCellCountX * mCellCountY; 1041 int startIndex = page * numCells; 1042 int endIndex = Math.min(startIndex + numCells, mApps.size()); 1043 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); 1044 1045 layout.removeAllViewsOnPage(); 1046 ArrayList<Object> items = new ArrayList<Object>(); 1047 ArrayList<Bitmap> images = new ArrayList<Bitmap>(); 1048 for (int i = startIndex; i < endIndex; ++i) { 1049 ApplicationInfo info = mApps.get(i); 1050 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( 1051 R.layout.apps_customize_application, layout, false); 1052 icon.applyFromApplicationInfo(info, true, this); 1053 icon.setOnClickListener(this); 1054 icon.setOnLongClickListener(this); 1055 icon.setOnTouchListener(this); 1056 icon.setOnKeyListener(this); 1057 1058 int index = i - startIndex; 1059 int x = index % mCellCountX; 1060 int y = index / mCellCountX; 1061 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 1062 1063 items.add(info); 1064 images.add(info.iconBitmap); 1065 } 1066 1067 layout.createHardwareLayers(); 1068 } 1069 1070 /** 1071 * A helper to return the priority for loading of the specified widget page. 1072 */ 1073 private int getWidgetPageLoadPriority(int page) { 1074 // If we are snapping to another page, use that index as the target page index 1075 int toPage = mCurrentPage; 1076 if (mNextPage > -1) { 1077 toPage = mNextPage; 1078 } 1079 1080 // We use the distance from the target page as an initial guess of priority, but if there 1081 // are no pages of higher priority than the page specified, then bump up the priority of 1082 // the specified page. 1083 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1084 int minPageDiff = Integer.MAX_VALUE; 1085 while (iter.hasNext()) { 1086 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1087 minPageDiff = Math.abs(task.page - toPage); 1088 } 1089 1090 int rawPageDiff = Math.abs(page - toPage); 1091 return rawPageDiff - Math.min(rawPageDiff, minPageDiff); 1092 } 1093 /** 1094 * Return the appropriate thread priority for loading for a given page (we give the current 1095 * page much higher priority) 1096 */ 1097 private int getThreadPriorityForPage(int page) { 1098 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below 1099 int pageDiff = getWidgetPageLoadPriority(page); 1100 if (pageDiff <= 0) { 1101 return Process.THREAD_PRIORITY_LESS_FAVORABLE; 1102 } else if (pageDiff <= 1) { 1103 return Process.THREAD_PRIORITY_LOWEST; 1104 } else { 1105 return Process.THREAD_PRIORITY_LOWEST; 1106 } 1107 } 1108 private int getSleepForPage(int page) { 1109 int pageDiff = getWidgetPageLoadPriority(page); 1110 return Math.max(0, pageDiff * sPageSleepDelay); 1111 } 1112 /** 1113 * Creates and executes a new AsyncTask to load a page of widget previews. 1114 */ 1115 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, 1116 int cellWidth, int cellHeight, int cellCountX) { 1117 1118 // Prune all tasks that are no longer needed 1119 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1120 while (iter.hasNext()) { 1121 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1122 int taskPage = task.page; 1123 if (taskPage < getAssociatedLowerPageBound(mCurrentPage) || 1124 taskPage > getAssociatedUpperPageBound(mCurrentPage)) { 1125 task.cancel(false); 1126 iter.remove(); 1127 } else { 1128 task.setThreadPriority(getThreadPriorityForPage(taskPage)); 1129 } 1130 } 1131 1132 // We introduce a slight delay to order the loading of side pages so that we don't thrash 1133 final int sleepMs = getSleepForPage(page); 1134 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, 1135 new AsyncTaskCallback() { 1136 @Override 1137 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 1138 try { 1139 try { 1140 Thread.sleep(sleepMs); 1141 } catch (Exception e) {} 1142 loadWidgetPreviewsInBackground(task, data); 1143 } finally { 1144 if (task.isCancelled()) { 1145 data.cleanup(true); 1146 } 1147 } 1148 } 1149 }, 1150 new AsyncTaskCallback() { 1151 @Override 1152 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 1153 mRunningTasks.remove(task); 1154 if (task.isCancelled()) return; 1155 // do cleanup inside onSyncWidgetPageItems 1156 onSyncWidgetPageItems(data); 1157 } 1158 }); 1159 1160 // Ensure that the task is appropriately prioritized and runs in parallel 1161 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, 1162 AsyncTaskPageData.Type.LoadWidgetPreviewData); 1163 t.setThreadPriority(getThreadPriorityForPage(page)); 1164 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); 1165 mRunningTasks.add(t); 1166 } 1167 1168 /* 1169 * Widgets PagedView implementation 1170 */ 1171 private void setupPage(PagedViewGridLayout layout) { 1172 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 1173 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 1174 1175 // Note: We force a measure here to get around the fact that when we do layout calculations 1176 // immediately after syncing, we don't have a proper width. 1177 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 1178 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 1179 layout.setMinimumWidth(getPageContentWidth()); 1180 layout.measure(widthSpec, heightSpec); 1181 } 1182 1183 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { 1184 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f); 1185 } 1186 1187 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 1188 float scale) { 1189 if (bitmap != null) { 1190 Canvas c = new Canvas(bitmap); 1191 c.scale(scale, scale); 1192 Rect oldBounds = d.copyBounds(); 1193 d.setBounds(x, y, x + w, y + h); 1194 d.draw(c); 1195 d.setBounds(oldBounds); // Restore the bounds 1196 c.setBitmap(null); 1197 } 1198 } 1199 1200 private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) { 1201 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get(); 1202 final Canvas c = mCachedShortcutPreviewCanvas.get(); 1203 if (tempBitmap == null || 1204 tempBitmap.getWidth() != maxWidth || 1205 tempBitmap.getHeight() != maxHeight) { 1206 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888); 1207 mCachedShortcutPreviewBitmap.set(tempBitmap); 1208 } else { 1209 c.setBitmap(tempBitmap); 1210 c.drawColor(0, PorterDuff.Mode.CLEAR); 1211 c.setBitmap(null); 1212 } 1213 // Render the icon 1214 Drawable icon = mIconCache.getFullResIcon(info); 1215 1216 int paddingTop = 1217 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top); 1218 int paddingLeft = 1219 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left); 1220 int paddingRight = 1221 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right); 1222 1223 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight); 1224 1225 renderDrawableToBitmap( 1226 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth); 1227 1228 Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888); 1229 c.setBitmap(preview); 1230 Paint p = mCachedShortcutPreviewPaint.get(); 1231 if (p == null) { 1232 p = new Paint(); 1233 ColorMatrix colorMatrix = new ColorMatrix(); 1234 colorMatrix.setSaturation(0); 1235 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix)); 1236 p.setAlpha((int) (255 * 0.06f)); 1237 //float density = 1f; 1238 //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL)); 1239 mCachedShortcutPreviewPaint.set(p); 1240 } 1241 c.drawBitmap(tempBitmap, 0, 0, p); 1242 c.setBitmap(null); 1243 1244 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize); 1245 1246 return preview; 1247 } 1248 1249 private Bitmap getWidgetPreview(ComponentName provider, int previewImage, 1250 int iconId, int cellHSpan, int cellVSpan, int maxWidth, 1251 int maxHeight) { 1252 // Load the preview image if possible 1253 String packageName = provider.getPackageName(); 1254 if (maxWidth < 0) maxWidth = Integer.MAX_VALUE; 1255 if (maxHeight < 0) maxHeight = Integer.MAX_VALUE; 1256 1257 Drawable drawable = null; 1258 if (previewImage != 0) { 1259 drawable = mPackageManager.getDrawable(packageName, previewImage, null); 1260 if (drawable == null) { 1261 Log.w(TAG, "Can't load widget preview drawable 0x" + 1262 Integer.toHexString(previewImage) + " for provider: " + provider); 1263 } 1264 } 1265 1266 int bitmapWidth; 1267 int bitmapHeight; 1268 Bitmap defaultPreview = null; 1269 boolean widgetPreviewExists = (drawable != null); 1270 if (widgetPreviewExists) { 1271 bitmapWidth = drawable.getIntrinsicWidth(); 1272 bitmapHeight = drawable.getIntrinsicHeight(); 1273 } else { 1274 // Generate a preview image if we couldn't load one 1275 if (cellHSpan < 1) cellHSpan = 1; 1276 if (cellVSpan < 1) cellVSpan = 1; 1277 1278 BitmapDrawable previewDrawable = (BitmapDrawable) getResources() 1279 .getDrawable(R.drawable.widget_preview_tile); 1280 final int previewDrawableWidth = previewDrawable 1281 .getIntrinsicWidth(); 1282 final int previewDrawableHeight = previewDrawable 1283 .getIntrinsicHeight(); 1284 bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips 1285 bitmapHeight = previewDrawableHeight * cellVSpan; 1286 1287 defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, 1288 Config.ARGB_8888); 1289 final Canvas c = mCachedAppWidgetPreviewCanvas.get(); 1290 c.setBitmap(defaultPreview); 1291 previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight); 1292 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT, 1293 Shader.TileMode.REPEAT); 1294 previewDrawable.draw(c); 1295 c.setBitmap(null); 1296 1297 // Draw the icon in the top left corner 1298 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); 1299 int smallestSide = Math.min(bitmapWidth, bitmapHeight); 1300 float iconScale = Math.min((float) smallestSide 1301 / (mAppIconSize + 2 * minOffset), 1f); 1302 1303 try { 1304 Drawable icon = null; 1305 int hoffset = 1306 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2); 1307 int yoffset = 1308 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2); 1309 if (iconId > 0) 1310 icon = mIconCache.getFullResIcon(packageName, iconId); 1311 if (icon != null) { 1312 renderDrawableToBitmap(icon, defaultPreview, hoffset, 1313 yoffset, (int) (mAppIconSize * iconScale), 1314 (int) (mAppIconSize * iconScale)); 1315 } 1316 } catch (Resources.NotFoundException e) { 1317 } 1318 } 1319 1320 // Scale to fit width only - let the widget preview be clipped in the 1321 // vertical dimension 1322 float scale = 1f; 1323 if (bitmapWidth > maxWidth) { 1324 scale = maxWidth / (float) bitmapWidth; 1325 } 1326 if (scale != 1f) { 1327 bitmapWidth = (int) (scale * bitmapWidth); 1328 bitmapHeight = (int) (scale * bitmapHeight); 1329 } 1330 1331 Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, 1332 Config.ARGB_8888); 1333 1334 // Draw the scaled preview into the final bitmap 1335 if (widgetPreviewExists) { 1336 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, 1337 bitmapHeight); 1338 } else { 1339 final Canvas c = mCachedAppWidgetPreviewCanvas.get(); 1340 final Rect src = mCachedAppWidgetPreviewSrcRect.get(); 1341 final Rect dest = mCachedAppWidgetPreviewDestRect.get(); 1342 c.setBitmap(preview); 1343 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight()); 1344 dest.set(0, 0, preview.getWidth(), preview.getHeight()); 1345 1346 Paint p = mCachedAppWidgetPreviewPaint.get(); 1347 if (p == null) { 1348 p = new Paint(); 1349 p.setFilterBitmap(true); 1350 mCachedAppWidgetPreviewPaint.set(p); 1351 } 1352 c.drawBitmap(defaultPreview, src, dest, p); 1353 c.setBitmap(null); 1354 } 1355 return preview; 1356 } 1357 1358 public void syncWidgetPageItems(final int page, final boolean immediate) { 1359 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 1360 1361 // Calculate the dimensions of each cell we are giving to each widget 1362 final ArrayList<Object> items = new ArrayList<Object>(); 1363 int contentWidth = mWidgetSpacingLayout.getContentWidth(); 1364 final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight 1365 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); 1366 int contentHeight = mWidgetSpacingLayout.getContentHeight(); 1367 final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom 1368 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); 1369 1370 // Prepare the set of widgets to load previews for in the background 1371 int offset = (page - mNumAppsPages) * numItemsPerPage; 1372 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { 1373 items.add(mWidgets.get(i)); 1374 } 1375 1376 // Prepopulate the pages with the other widget info, and fill in the previews later 1377 final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page); 1378 layout.setColumnCount(layout.getCellCountX()); 1379 for (int i = 0; i < items.size(); ++i) { 1380 Object rawInfo = items.get(i); 1381 PendingAddItemInfo createItemInfo = null; 1382 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( 1383 R.layout.apps_customize_widget, layout, false); 1384 if (rawInfo instanceof AppWidgetProviderInfo) { 1385 // Fill in the widget information 1386 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1387 createItemInfo = new PendingAddWidgetInfo(info, null, null); 1388 1389 // Determine the widget spans and min resize spans. 1390 int[] spanXY = Launcher.getSpanForWidget(mLauncher, info); 1391 createItemInfo.spanX = spanXY[0]; 1392 createItemInfo.spanY = spanXY[1]; 1393 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info); 1394 createItemInfo.minSpanX = minSpanXY[0]; 1395 createItemInfo.minSpanY = minSpanXY[1]; 1396 1397 widget.applyFromAppWidgetProviderInfo(info, -1, spanXY); 1398 widget.setTag(createItemInfo); 1399 widget.setShortPressListener(this); 1400 } else if (rawInfo instanceof ResolveInfo) { 1401 // Fill in the shortcuts information 1402 ResolveInfo info = (ResolveInfo) rawInfo; 1403 createItemInfo = new PendingAddShortcutInfo(info.activityInfo); 1404 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 1405 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, 1406 info.activityInfo.name); 1407 widget.applyFromResolveInfo(mPackageManager, info); 1408 widget.setTag(createItemInfo); 1409 } 1410 widget.setOnClickListener(this); 1411 widget.setOnLongClickListener(this); 1412 widget.setOnTouchListener(this); 1413 widget.setOnKeyListener(this); 1414 1415 // Layout each widget 1416 int ix = i % mWidgetCountX; 1417 int iy = i / mWidgetCountX; 1418 GridLayout.LayoutParams lp = new GridLayout.LayoutParams( 1419 GridLayout.spec(iy, GridLayout.LEFT), 1420 GridLayout.spec(ix, GridLayout.TOP)); 1421 lp.width = cellWidth; 1422 lp.height = cellHeight; 1423 lp.setGravity(Gravity.TOP | Gravity.LEFT); 1424 if (ix > 0) lp.leftMargin = mWidgetWidthGap; 1425 if (iy > 0) lp.topMargin = mWidgetHeightGap; 1426 layout.addView(widget, lp); 1427 } 1428 1429 // wait until a call on onLayout to start loading, because 1430 // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out 1431 // TODO: can we do a measure/layout immediately? 1432 layout.setOnLayoutListener(new Runnable() { 1433 public void run() { 1434 // Load the widget previews 1435 int maxPreviewWidth = cellWidth; 1436 int maxPreviewHeight = cellHeight; 1437 if (layout.getChildCount() > 0) { 1438 PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0); 1439 int[] maxSize = w.getPreviewSize(); 1440 maxPreviewWidth = maxSize[0]; 1441 maxPreviewHeight = maxSize[1]; 1442 } 1443 if (immediate) { 1444 AsyncTaskPageData data = new AsyncTaskPageData(page, items, 1445 maxPreviewWidth, maxPreviewHeight, null, null); 1446 loadWidgetPreviewsInBackground(null, data); 1447 onSyncWidgetPageItems(data); 1448 } else { 1449 if (mInTransition) { 1450 mDeferredPrepareLoadWidgetPreviewsTasks.add(this); 1451 } else { 1452 prepareLoadWidgetPreviewsTask(page, items, 1453 maxPreviewWidth, maxPreviewHeight, mWidgetCountX); 1454 } 1455 } 1456 } 1457 }); 1458 } 1459 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, 1460 AsyncTaskPageData data) { 1461 // loadWidgetPreviewsInBackground can be called without a task to load a set of widget 1462 // previews synchronously 1463 if (task != null) { 1464 // Ensure that this task starts running at the correct priority 1465 task.syncThreadPriority(); 1466 } 1467 1468 // Load each of the widget/shortcut previews 1469 ArrayList<Object> items = data.items; 1470 ArrayList<Bitmap> images = data.generatedImages; 1471 int count = items.size(); 1472 for (int i = 0; i < count; ++i) { 1473 if (task != null) { 1474 // Ensure we haven't been cancelled yet 1475 if (task.isCancelled()) break; 1476 // Before work on each item, ensure that this task is running at the correct 1477 // priority 1478 task.syncThreadPriority(); 1479 } 1480 1481 Object rawInfo = items.get(i); 1482 if (rawInfo instanceof AppWidgetProviderInfo) { 1483 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1484 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info); 1485 1486 int maxWidth = Math.min(data.maxImageWidth, 1487 mWidgetSpacingLayout.estimateCellWidth(cellSpans[0])); 1488 int maxHeight = Math.min(data.maxImageHeight, 1489 mWidgetSpacingLayout.estimateCellHeight(cellSpans[1])); 1490 Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon, 1491 cellSpans[0], cellSpans[1], maxWidth, maxHeight); 1492 images.add(b); 1493 } else if (rawInfo instanceof ResolveInfo) { 1494 // Fill in the shortcuts information 1495 ResolveInfo info = (ResolveInfo) rawInfo; 1496 images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight)); 1497 } 1498 } 1499 } 1500 1501 private void onSyncWidgetPageItems(AsyncTaskPageData data) { 1502 if (mInTransition) { 1503 mDeferredSyncWidgetPageItems.add(data); 1504 return; 1505 } 1506 try { 1507 int page = data.page; 1508 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page); 1509 1510 ArrayList<Object> items = data.items; 1511 int count = items.size(); 1512 for (int i = 0; i < count; ++i) { 1513 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); 1514 if (widget != null) { 1515 Bitmap preview = data.generatedImages.get(i); 1516 widget.applyPreview(new FastBitmapDrawable(preview), i); 1517 } 1518 } 1519 1520 layout.createHardwareLayer(); 1521 invalidate(); 1522 1523 // Update all thread priorities 1524 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 1525 while (iter.hasNext()) { 1526 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 1527 int pageIndex = task.page; 1528 task.setThreadPriority(getThreadPriorityForPage(pageIndex)); 1529 } 1530 } finally { 1531 data.cleanup(false); 1532 } 1533 } 1534 1535 @Override 1536 public void syncPages() { 1537 removeAllViews(); 1538 cancelAllTasks(); 1539 1540 Context context = getContext(); 1541 for (int j = 0; j < mNumWidgetPages; ++j) { 1542 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, 1543 mWidgetCountY); 1544 setupPage(layout); 1545 addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT, 1546 LayoutParams.MATCH_PARENT)); 1547 } 1548 1549 for (int i = 0; i < mNumAppsPages; ++i) { 1550 PagedViewCellLayout layout = new PagedViewCellLayout(context); 1551 setupPage(layout); 1552 addView(layout); 1553 } 1554 } 1555 1556 @Override 1557 public void syncPageItems(int page, boolean immediate) { 1558 if (page < mNumAppsPages) { 1559 syncAppsPageItems(page, immediate); 1560 } else { 1561 syncWidgetPageItems(page, immediate); 1562 } 1563 } 1564 1565 // We want our pages to be z-ordered such that the further a page is to the left, the higher 1566 // it is in the z-order. This is important to insure touch events are handled correctly. 1567 View getPageAt(int index) { 1568 return getChildAt(indexToPage(index)); 1569 } 1570 1571 @Override 1572 protected int indexToPage(int index) { 1573 return getChildCount() - index - 1; 1574 } 1575 1576 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. 1577 @Override 1578 protected void screenScrolled(int screenCenter) { 1579 super.screenScrolled(screenCenter); 1580 1581 for (int i = 0; i < getChildCount(); i++) { 1582 View v = getPageAt(i); 1583 if (v != null) { 1584 float scrollProgress = getScrollProgress(screenCenter, v, i); 1585 1586 float interpolatedProgress = 1587 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); 1588 float scale = (1 - interpolatedProgress) + 1589 interpolatedProgress * TRANSITION_SCALE_FACTOR; 1590 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); 1591 1592 float alpha; 1593 1594 if (scrollProgress < 0) { 1595 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1596 1 - Math.abs(scrollProgress)) : 1.0f; 1597 } else { 1598 // On large screens we need to fade the page as it nears its leftmost position 1599 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress); 1600 } 1601 1602 v.setCameraDistance(mDensity * CAMERA_DISTANCE); 1603 int pageWidth = v.getMeasuredWidth(); 1604 int pageHeight = v.getMeasuredHeight(); 1605 1606 if (PERFORM_OVERSCROLL_ROTATION) { 1607 if (i == 0 && scrollProgress < 0) { 1608 // Overscroll to the left 1609 v.setPivotX(TRANSITION_PIVOT * pageWidth); 1610 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1611 scale = 1.0f; 1612 alpha = 1.0f; 1613 // On the first page, we don't want the page to have any lateral motion 1614 translationX = 0; 1615 } else if (i == getChildCount() - 1 && scrollProgress > 0) { 1616 // Overscroll to the right 1617 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); 1618 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1619 scale = 1.0f; 1620 alpha = 1.0f; 1621 // On the last page, we don't want the page to have any lateral motion. 1622 translationX = 0; 1623 } else { 1624 v.setPivotY(pageHeight / 2.0f); 1625 v.setPivotX(pageWidth / 2.0f); 1626 v.setRotationY(0f); 1627 } 1628 } 1629 1630 v.setTranslationX(translationX); 1631 v.setScaleX(scale); 1632 v.setScaleY(scale); 1633 v.setAlpha(alpha); 1634 1635 // If the view has 0 alpha, we set it to be invisible so as to prevent 1636 // it from accepting touches 1637 if (alpha == 0) { 1638 v.setVisibility(INVISIBLE); 1639 } else if (v.getVisibility() != VISIBLE) { 1640 v.setVisibility(VISIBLE); 1641 } 1642 } 1643 } 1644 } 1645 1646 protected void overScroll(float amount) { 1647 acceleratedOverScroll(amount); 1648 } 1649 1650 /** 1651 * Used by the parent to get the content width to set the tab bar to 1652 * @return 1653 */ 1654 public int getPageContentWidth() { 1655 return mContentWidth; 1656 } 1657 1658 @Override 1659 protected void onPageEndMoving() { 1660 super.onPageEndMoving(); 1661 mForceDrawAllChildrenNextFrame = true; 1662 // We reset the save index when we change pages so that it will be recalculated on next 1663 // rotation 1664 mSaveInstanceStateItemIndex = -1; 1665 } 1666 1667 /* 1668 * AllAppsView implementation 1669 */ 1670 public void setup(Launcher launcher, DragController dragController) { 1671 mLauncher = launcher; 1672 mDragController = dragController; 1673 } 1674 1675 /** 1676 * We should call thise method whenever the core data changes (mApps, mWidgets) so that we can 1677 * appropriately determine when to invalidate the PagedView page data. In cases where the data 1678 * has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the 1679 * next onMeasure() pass, which will trigger an invalidatePageData() itself. 1680 */ 1681 private void invalidateOnDataChange() { 1682 if (!isDataReady()) { 1683 // The next layout pass will trigger data-ready if both widgets and apps are set, so 1684 // request a layout to trigger the page data when ready. 1685 requestLayout(); 1686 } else { 1687 cancelAllTasks(); 1688 invalidatePageData(); 1689 } 1690 } 1691 1692 public void setApps(ArrayList<ApplicationInfo> list) { 1693 mApps = list; 1694 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); 1695 updatePageCounts(); 1696 invalidateOnDataChange(); 1697 } 1698 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1699 // We add it in place, in alphabetical order 1700 int count = list.size(); 1701 for (int i = 0; i < count; ++i) { 1702 ApplicationInfo info = list.get(i); 1703 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); 1704 if (index < 0) { 1705 mApps.add(-(index + 1), info); 1706 } 1707 } 1708 } 1709 public void addApps(ArrayList<ApplicationInfo> list) { 1710 addAppsWithoutInvalidate(list); 1711 updatePageCounts(); 1712 invalidateOnDataChange(); 1713 } 1714 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { 1715 ComponentName removeComponent = item.intent.getComponent(); 1716 int length = list.size(); 1717 for (int i = 0; i < length; ++i) { 1718 ApplicationInfo info = list.get(i); 1719 if (info.intent.getComponent().equals(removeComponent)) { 1720 return i; 1721 } 1722 } 1723 return -1; 1724 } 1725 private int findAppByPackage(List<ApplicationInfo> list, String packageName) { 1726 int length = list.size(); 1727 for (int i = 0; i < length; ++i) { 1728 ApplicationInfo info = list.get(i); 1729 if (ItemInfo.getPackageName(info.intent).equals(packageName)) { 1730 return i; 1731 } 1732 } 1733 return -1; 1734 } 1735 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1736 // loop through all the apps and remove apps that have the same component 1737 int length = list.size(); 1738 for (int i = 0; i < length; ++i) { 1739 ApplicationInfo info = list.get(i); 1740 int removeIndex = findAppByComponent(mApps, info); 1741 if (removeIndex > -1) { 1742 mApps.remove(removeIndex); 1743 } 1744 } 1745 } 1746 private void removeAppsWithPackageNameWithoutInvalidate(ArrayList<String> packageNames) { 1747 // loop through all the package names and remove apps that have the same package name 1748 for (String pn : packageNames) { 1749 int removeIndex = findAppByPackage(mApps, pn); 1750 while (removeIndex > -1) { 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