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