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