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