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