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