AppsCustomizePagedView.java revision 31234d811dc69c159757a6890852eb0f53d559a9
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.AppWidgetManager; 23import android.appwidget.AppWidgetProviderInfo; 24import android.content.ComponentName; 25import android.content.Context; 26import android.content.Intent; 27import android.content.pm.ActivityInfo; 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.MaskFilter; 37import android.graphics.Paint; 38import android.graphics.PorterDuff; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.TableMaskFilter; 42import android.graphics.drawable.Drawable; 43import android.os.AsyncTask; 44import android.os.Process; 45import android.util.AttributeSet; 46import android.util.Log; 47import android.view.Gravity; 48import android.view.LayoutInflater; 49import android.view.MotionEvent; 50import android.view.View; 51import android.view.ViewConfiguration; 52import android.view.ViewGroup; 53import android.view.animation.AccelerateInterpolator; 54import android.view.animation.DecelerateInterpolator; 55import android.widget.GridLayout; 56import android.widget.ImageView; 57import android.widget.Toast; 58 59import com.android.launcher.R; 60import com.android.launcher2.DropTarget.DragObject; 61 62import java.util.ArrayList; 63import java.util.Collections; 64import java.util.Iterator; 65import java.util.List; 66 67/** 68 * A simple callback interface which also provides the results of the task. 69 */ 70interface AsyncTaskCallback { 71 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data); 72} 73 74/** 75 * The data needed to perform either of the custom AsyncTasks. 76 */ 77class AsyncTaskPageData { 78 enum Type { 79 LoadWidgetPreviewData, 80 LoadHolographicIconsData 81 } 82 83 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR, 84 AsyncTaskCallback postR) { 85 page = p; 86 items = l; 87 sourceImages = si; 88 generatedImages = new ArrayList<Bitmap>(); 89 cellWidth = cellHeight = -1; 90 doInBackgroundCallback = bgR; 91 postExecuteCallback = postR; 92 } 93 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR, 94 AsyncTaskCallback postR) { 95 page = p; 96 items = l; 97 generatedImages = new ArrayList<Bitmap>(); 98 cellWidth = cw; 99 cellHeight = ch; 100 cellCountX = ccx; 101 doInBackgroundCallback = bgR; 102 postExecuteCallback = postR; 103 } 104 void cleanup(boolean cancelled) { 105 // Clean up any references to source/generated bitmaps 106 if (sourceImages != null) { 107 if (cancelled) { 108 for (Bitmap b : sourceImages) { 109 b.recycle(); 110 } 111 } 112 sourceImages.clear(); 113 } 114 if (generatedImages != null) { 115 if (cancelled) { 116 for (Bitmap b : generatedImages) { 117 b.recycle(); 118 } 119 } 120 generatedImages.clear(); 121 } 122 } 123 int page; 124 ArrayList<Object> items; 125 ArrayList<Bitmap> sourceImages; 126 ArrayList<Bitmap> generatedImages; 127 int cellWidth; 128 int cellHeight; 129 int cellCountX; 130 AsyncTaskCallback doInBackgroundCallback; 131 AsyncTaskCallback postExecuteCallback; 132} 133 134/** 135 * A generic template for an async task used in AppsCustomize. 136 */ 137class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> { 138 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) { 139 page = p; 140 threadPriority = Process.THREAD_PRIORITY_DEFAULT; 141 dataType = ty; 142 } 143 @Override 144 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) { 145 if (params.length != 1) return null; 146 // Load each of the widget previews in the background 147 params[0].doInBackgroundCallback.run(this, params[0]); 148 return params[0]; 149 } 150 @Override 151 protected void onPostExecute(AsyncTaskPageData result) { 152 // All the widget previews are loaded, so we can just callback to inflate the page 153 result.postExecuteCallback.run(this, result); 154 } 155 156 void setThreadPriority(int p) { 157 threadPriority = p; 158 } 159 void syncThreadPriority() { 160 Process.setThreadPriority(threadPriority); 161 } 162 163 // The page that this async task is associated with 164 AsyncTaskPageData.Type dataType; 165 int page; 166 int threadPriority; 167} 168 169/** 170 * The Apps/Customize page that displays all the applications, widgets, and shortcuts. 171 */ 172public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements 173 AllAppsView, View.OnClickListener, DragSource { 174 static final String LOG_TAG = "AppsCustomizePagedView"; 175 176 /** 177 * The different content types that this paged view can show. 178 */ 179 public enum ContentType { 180 Applications, 181 Widgets 182 } 183 184 // Refs 185 private Launcher mLauncher; 186 private DragController mDragController; 187 private final LayoutInflater mLayoutInflater; 188 private final PackageManager mPackageManager; 189 190 // Save and Restore 191 private int mSaveInstanceStateItemIndex = -1; 192 193 // Content 194 private ArrayList<ApplicationInfo> mApps; 195 private ArrayList<Object> mWidgets; 196 197 // Cling 198 private int mClingFocusedX; 199 private int mClingFocusedY; 200 201 // Caching 202 private Canvas mCanvas; 203 private Drawable mDefaultWidgetBackground; 204 private IconCache mIconCache; 205 private int mDragViewMultiplyColor; 206 207 // Dimens 208 private int mContentWidth; 209 private int mAppIconSize; 210 private int mMaxAppCellCountX, mMaxAppCellCountY; 211 private int mWidgetCountX, mWidgetCountY; 212 private int mWidgetWidthGap, mWidgetHeightGap; 213 private final int mWidgetPreviewIconPaddedDimension; 214 private final float sWidgetPreviewIconPaddingPercentage = 0.25f; 215 private PagedViewCellLayout mWidgetSpacingLayout; 216 private int mNumAppsPages; 217 private int mNumWidgetPages; 218 219 // Relating to the scroll and overscroll effects 220 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f); 221 private static float CAMERA_DISTANCE = 6500; 222 private static float TRANSITION_SCALE_FACTOR = 0.74f; 223 private static float TRANSITION_PIVOT = 0.65f; 224 private static float TRANSITION_MAX_ROTATION = 22; 225 private static final boolean PERFORM_OVERSCROLL_ROTATION = true; 226 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f); 227 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4); 228 229 // Previews & outlines 230 ArrayList<AppsCustomizeAsyncTask> mRunningTasks; 231 private HolographicOutlineHelper mHolographicOutlineHelper; 232 private static final int sPageSleepDelay = 150; 233 234 public AppsCustomizePagedView(Context context, AttributeSet attrs) { 235 super(context, attrs); 236 mLayoutInflater = LayoutInflater.from(context); 237 mPackageManager = context.getPackageManager(); 238 mApps = new ArrayList<ApplicationInfo>(); 239 mWidgets = new ArrayList<Object>(); 240 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); 241 mHolographicOutlineHelper = new HolographicOutlineHelper(); 242 mCanvas = new Canvas(); 243 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>(); 244 245 // Save the default widget preview background 246 Resources resources = context.getResources(); 247 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo); 248 mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 249 mDragViewMultiplyColor = resources.getColor(R.color.drag_view_multiply_color); 250 251 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); 252 mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1); 253 mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1); 254 mWidgetWidthGap = 255 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0); 256 mWidgetHeightGap = 257 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0); 258 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); 259 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); 260 mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0); 261 mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0); 262 a.recycle(); 263 mWidgetSpacingLayout = new PagedViewCellLayout(getContext()); 264 265 // The padding on the non-matched dimension for the default widget preview icons 266 // (top + bottom) 267 mWidgetPreviewIconPaddedDimension = 268 (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); 269 mFadeInAdjacentScreens = false; 270 } 271 272 @Override 273 protected void init() { 274 super.init(); 275 mCenterPagesVertically = false; 276 277 Context context = getContext(); 278 Resources r = context.getResources(); 279 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); 280 } 281 282 @Override 283 protected void onUnhandledTap(MotionEvent ev) { 284 if (LauncherApplication.isScreenLarge()) { 285 // Dismiss AppsCustomize if we tap 286 mLauncher.showWorkspace(true); 287 } 288 } 289 290 /** Returns the item index of the center item on this page so that we can restore to this 291 * item index when we rotate. */ 292 private int getMiddleComponentIndexOnCurrentPage() { 293 int i = -1; 294 if (getPageCount() > 0) { 295 int currentPage = getCurrentPage(); 296 if (currentPage < mNumAppsPages) { 297 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage); 298 PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout(); 299 int numItemsPerPage = mCellCountX * mCellCountY; 300 int childCount = childrenLayout.getChildCount(); 301 if (childCount > 0) { 302 i = (currentPage * numItemsPerPage) + (childCount / 2); 303 } 304 } else { 305 int numApps = mApps.size(); 306 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage); 307 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 308 int childCount = layout.getChildCount(); 309 if (childCount > 0) { 310 i = numApps + 311 ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2); 312 } 313 } 314 } 315 return i; 316 } 317 318 /** Get the index of the item to restore to if we need to restore the current page. */ 319 int getSaveInstanceStateIndex() { 320 if (mSaveInstanceStateItemIndex == -1) { 321 mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage(); 322 } 323 return mSaveInstanceStateItemIndex; 324 } 325 326 /** Returns the page in the current orientation which is expected to contain the specified 327 * item index. */ 328 int getPageForComponent(int index) { 329 if (index < 0) return 0; 330 331 if (index < mApps.size()) { 332 int numItemsPerPage = mCellCountX * mCellCountY; 333 return (index / numItemsPerPage); 334 } else { 335 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 336 return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage); 337 } 338 } 339 340 /** 341 * This differs from isDataReady as this is the test done if isDataReady is not set. 342 */ 343 private boolean testDataReady() { 344 // We only do this test once, and we default to the Applications page, so we only really 345 // have to wait for there to be apps. 346 // TODO: What if one of them is validly empty 347 return !mApps.isEmpty() && !mWidgets.isEmpty(); 348 } 349 350 /** Restores the page for an item at the specified index */ 351 void restorePageForIndex(int index) { 352 if (index < 0) return; 353 mSaveInstanceStateItemIndex = index; 354 } 355 356 private void updatePageCounts() { 357 mNumWidgetPages = (int) Math.ceil(mWidgets.size() / 358 (float) (mWidgetCountX * mWidgetCountY)); 359 mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); 360 } 361 362 protected void onDataReady(int width, int height) { 363 // Note that we transpose the counts in portrait so that we get a similar layout 364 boolean isLandscape = getResources().getConfiguration().orientation == 365 Configuration.ORIENTATION_LANDSCAPE; 366 int maxCellCountX = Integer.MAX_VALUE; 367 int maxCellCountY = Integer.MAX_VALUE; 368 if (LauncherApplication.isScreenLarge()) { 369 maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() : 370 LauncherModel.getCellCountY()); 371 maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() : 372 LauncherModel.getCellCountX()); 373 } 374 if (mMaxAppCellCountX > -1) { 375 maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX); 376 } 377 if (mMaxAppCellCountY > -1) { 378 maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY); 379 } 380 381 // Now that the data is ready, we can calculate the content width, the number of cells to 382 // use for each page 383 mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 384 mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 385 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 386 mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY); 387 mCellCountX = mWidgetSpacingLayout.getCellCountX(); 388 mCellCountY = mWidgetSpacingLayout.getCellCountY(); 389 updatePageCounts(); 390 391 // Force a measure to update recalculate the gaps 392 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 393 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 394 mWidgetSpacingLayout.measure(widthSpec, heightSpec); 395 mContentWidth = mWidgetSpacingLayout.getContentWidth(); 396 397 // Restore the page 398 int page = getPageForComponent(mSaveInstanceStateItemIndex); 399 invalidatePageData(Math.max(0, page)); 400 401 // Calculate the position for the cling punch through 402 int[] offset = new int[2]; 403 int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY); 404 mLauncher.getDragLayer().getLocationInDragLayer(this, offset); 405 pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 + offset[0]; 406 pos[1] += (getMeasuredHeight() - mWidgetSpacingLayout.getMeasuredHeight()) / 2 + offset[1]; 407 mLauncher.showFirstRunAllAppsCling(pos); 408 409 } 410 411 @Override 412 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 413 int width = MeasureSpec.getSize(widthMeasureSpec); 414 int height = MeasureSpec.getSize(heightMeasureSpec); 415 if (!isDataReady()) { 416 if (testDataReady()) { 417 setDataIsReady(); 418 setMeasuredDimension(width, height); 419 onDataReady(width, height); 420 } 421 } 422 423 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 424 } 425 426 /** Removes and returns the ResolveInfo with the specified ComponentName */ 427 private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list, 428 ComponentName cn) { 429 Iterator<ResolveInfo> iter = list.iterator(); 430 while (iter.hasNext()) { 431 ResolveInfo rinfo = iter.next(); 432 ActivityInfo info = rinfo.activityInfo; 433 ComponentName c = new ComponentName(info.packageName, info.name); 434 if (c.equals(cn)) { 435 iter.remove(); 436 return rinfo; 437 } 438 } 439 return null; 440 } 441 442 public void onPackagesUpdated() { 443 // TODO: this isn't ideal, but we actually need to delay here. This call is triggered 444 // by a broadcast receiver, and in order for it to work correctly, we need to know that 445 // the AppWidgetService has already received and processed the same broadcast. Since there 446 // is no guarantee about ordering of broadcast receipt, we just delay here. Ideally, 447 // we should have a more precise way of ensuring the AppWidgetService is up to date. 448 postDelayed(new Runnable() { 449 public void run() { 450 updatePackages(); 451 } 452 }, 500); 453 } 454 455 public void updatePackages() { 456 // Get the list of widgets and shortcuts 457 boolean wasEmpty = mWidgets.isEmpty(); 458 mWidgets.clear(); 459 List<AppWidgetProviderInfo> widgets = 460 AppWidgetManager.getInstance(mLauncher).getInstalledProviders(); 461 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 462 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0); 463 mWidgets.addAll(widgets); 464 mWidgets.addAll(shortcuts); 465 Collections.sort(mWidgets, 466 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); 467 updatePageCounts(); 468 469 if (wasEmpty) { 470 // The next layout pass will trigger data-ready if both widgets and apps are set, so request 471 // a layout to do this test and invalidate the page data when ready. 472 if (testDataReady()) requestLayout(); 473 } else { 474 cancelAllTasks(); 475 invalidatePageData(); 476 } 477 } 478 479 @Override 480 public void onClick(View v) { 481 // When we have exited all apps or are in transition, disregard clicks 482 if (!mLauncher.isAllAppsCustomizeOpen() || 483 mLauncher.getWorkspace().isSwitchingState()) return; 484 485 if (v instanceof PagedViewIcon) { 486 // Animate some feedback to the click 487 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); 488 animateClickFeedback(v, new Runnable() { 489 @Override 490 public void run() { 491 mLauncher.startActivitySafely(appInfo.intent, appInfo); 492 } 493 }); 494 } else if (v instanceof PagedViewWidget) { 495 // Let the user know that they have to long press to add a widget 496 Toast.makeText(getContext(), R.string.long_press_widget_to_add, 497 Toast.LENGTH_SHORT).show(); 498 499 // Create a little animation to show that the widget can move 500 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY); 501 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview); 502 AnimatorSet bounce = new AnimatorSet(); 503 ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY); 504 tyuAnim.setDuration(125); 505 ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f); 506 tydAnim.setDuration(100); 507 bounce.play(tyuAnim).before(tydAnim); 508 bounce.setInterpolator(new AccelerateInterpolator()); 509 bounce.start(); 510 } 511 } 512 513 /* 514 * PagedViewWithDraggableItems implementation 515 */ 516 @Override 517 protected void determineDraggingStart(android.view.MotionEvent ev) { 518 // Disable dragging by pulling an app down for now. 519 } 520 521 private void beginDraggingApplication(View v) { 522 mLauncher.getWorkspace().onDragStartedWithItem(v); 523 mLauncher.getWorkspace().beginDragShared(v, this); 524 } 525 526 private void beginDraggingWidget(View v) { 527 // Get the widget preview as the drag representation 528 ImageView image = (ImageView) v.findViewById(R.id.widget_preview); 529 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); 530 531 // Compose the drag image 532 Bitmap b; 533 Drawable preview = image.getDrawable(); 534 RectF mTmpScaleRect = new RectF(0f,0f,1f,1f); 535 image.getImageMatrix().mapRect(mTmpScaleRect); 536 float scale = mTmpScaleRect.right; 537 int w = (int) (preview.getIntrinsicWidth() * scale); 538 int h = (int) (preview.getIntrinsicHeight() * scale); 539 if (createItemInfo instanceof PendingAddWidgetInfo) { 540 PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; 541 int[] spanXY = mLauncher.getSpanForWidget(createWidgetInfo, null); 542 createItemInfo.spanX = spanXY[0]; 543 createItemInfo.spanY = spanXY[1]; 544 545 b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 546 renderDrawableToBitmap(preview, b, 0, 0, w, h, scale, mDragViewMultiplyColor); 547 } else { 548 // Workaround for the fact that we don't keep the original ResolveInfo associated with 549 // the shortcut around. To get the icon, we just render the preview image (which has 550 // the shortcut icon) to a new drag bitmap that clips the non-icon space. 551 b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, 552 mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); 553 mCanvas.setBitmap(b); 554 mCanvas.save(); 555 preview.draw(mCanvas); 556 mCanvas.restore(); 557 mCanvas.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); 558 mCanvas.setBitmap(null); 559 createItemInfo.spanX = createItemInfo.spanY = 1; 560 } 561 562 // We use a custom alpha clip table for the default widget previews 563 Paint alphaClipPaint = null; 564 if (createItemInfo instanceof PendingAddWidgetInfo) { 565 if (((PendingAddWidgetInfo) createItemInfo).hasDefaultPreview) { 566 MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255); 567 alphaClipPaint = new Paint(); 568 alphaClipPaint.setMaskFilter(alphaClipTable); 569 } 570 } 571 572 // Start the drag 573 mLauncher.lockScreenOrientationOnLargeUI(); 574 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, 575 createItemInfo.spanY, b, alphaClipPaint); 576 mDragController.startDrag(image, b, this, createItemInfo, 577 DragController.DRAG_ACTION_COPY, null); 578 b.recycle(); 579 } 580 @Override 581 protected boolean beginDragging(View v) { 582 // Dismiss the cling 583 mLauncher.dismissAllAppsCling(null); 584 585 if (!super.beginDragging(v)) return false; 586 587 // Go into spring loaded mode (must happen before we startDrag()) 588 mLauncher.enterSpringLoadedDragMode(); 589 590 if (v instanceof PagedViewIcon) { 591 beginDraggingApplication(v); 592 } else if (v instanceof PagedViewWidget) { 593 beginDraggingWidget(v); 594 } 595 return true; 596 } 597 private void endDragging(View target, boolean success) { 598 mLauncher.getWorkspace().onDragStopped(success); 599 if (!success || (target != mLauncher.getWorkspace() && 600 !(target instanceof DeleteDropTarget))) { 601 // Exit spring loaded mode if we have not successfully dropped or have not handled the 602 // drop in Workspace 603 mLauncher.exitSpringLoadedDragMode(); 604 } 605 mLauncher.unlockScreenOrientationOnLargeUI(); 606 607 } 608 609 @Override 610 public void onDropCompleted(View target, DragObject d, boolean success) { 611 endDragging(target, success); 612 613 // Display an error message if the drag failed due to there not being enough space on the 614 // target layout we were dropping on. 615 if (!success) { 616 boolean showOutOfSpaceMessage = false; 617 if (target instanceof Workspace) { 618 int currentScreen = mLauncher.getCurrentWorkspaceScreen(); 619 Workspace workspace = (Workspace) target; 620 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); 621 ItemInfo itemInfo = (ItemInfo) d.dragInfo; 622 if (layout != null) { 623 layout.calculateSpans(itemInfo); 624 showOutOfSpaceMessage = 625 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); 626 } 627 } 628 if (showOutOfSpaceMessage) { 629 mLauncher.showOutOfSpaceMessage(); 630 } 631 } 632 } 633 634 @Override 635 protected void onDetachedFromWindow() { 636 super.onDetachedFromWindow(); 637 cancelAllTasks(); 638 } 639 640 private void cancelAllTasks() { 641 // Clean up all the async tasks 642 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 643 while (iter.hasNext()) { 644 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 645 task.cancel(false); 646 iter.remove(); 647 } 648 } 649 650 public void setContentType(ContentType type) { 651 if (type == ContentType.Widgets) { 652 invalidatePageData(mNumAppsPages, true); 653 } else if (type == ContentType.Applications) { 654 invalidatePageData(0, true); 655 } 656 } 657 658 protected void snapToPage(int whichPage, int delta, int duration) { 659 super.snapToPage(whichPage, delta, duration); 660 updateCurrentTab(whichPage); 661 } 662 663 private void updateCurrentTab(int currentPage) { 664 AppsCustomizeTabHost tabHost = getTabHost(); 665 String tag = tabHost.getCurrentTabTag(); 666 if (tag != null) { 667 if (currentPage >= mNumAppsPages && 668 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) { 669 tabHost.setCurrentTabFromContent(ContentType.Widgets); 670 } else if (currentPage < mNumAppsPages && 671 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { 672 tabHost.setCurrentTabFromContent(ContentType.Applications); 673 } 674 } 675 } 676 677 /* 678 * Apps PagedView implementation 679 */ 680 private void setVisibilityOnChildren(ViewGroup layout, int visibility) { 681 int childCount = layout.getChildCount(); 682 for (int i = 0; i < childCount; ++i) { 683 layout.getChildAt(i).setVisibility(visibility); 684 } 685 } 686 private void setupPage(PagedViewCellLayout layout) { 687 layout.setCellCount(mCellCountX, mCellCountY); 688 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 689 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 690 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 691 692 // Note: We force a measure here to get around the fact that when we do layout calculations 693 // immediately after syncing, we don't have a proper width. That said, we already know the 694 // expected page width, so we can actually optimize by hiding all the TextView-based 695 // children that are expensive to measure, and let that happen naturally later. 696 setVisibilityOnChildren(layout, View.GONE); 697 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 698 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 699 layout.setMinimumWidth(getPageContentWidth()); 700 layout.measure(widthSpec, heightSpec); 701 setVisibilityOnChildren(layout, View.VISIBLE); 702 } 703 704 public void syncAppsPageItems(int page, boolean immediate) { 705 // ensure that we have the right number of items on the pages 706 int numCells = mCellCountX * mCellCountY; 707 int startIndex = page * numCells; 708 int endIndex = Math.min(startIndex + numCells, mApps.size()); 709 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page); 710 711 layout.removeAllViewsOnPage(); 712 ArrayList<Object> items = new ArrayList<Object>(); 713 ArrayList<Bitmap> images = new ArrayList<Bitmap>(); 714 for (int i = startIndex; i < endIndex; ++i) { 715 ApplicationInfo info = mApps.get(i); 716 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( 717 R.layout.apps_customize_application, layout, false); 718 icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper); 719 icon.setOnClickListener(this); 720 icon.setOnLongClickListener(this); 721 icon.setOnTouchListener(this); 722 723 int index = i - startIndex; 724 int x = index % mCellCountX; 725 int y = index / mCellCountX; 726 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 727 728 items.add(info); 729 images.add(info.iconBitmap); 730 } 731 732 layout.createHardwareLayers(); 733 734 /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS 735 if (mFadeInAdjacentScreens) { 736 prepareGenerateHoloOutlinesTask(page, items, images); 737 } 738 */ 739 } 740 741 /** 742 * Return the appropriate thread priority for loading for a given page (we give the current 743 * page much higher priority) 744 */ 745 private int getThreadPriorityForPage(int page) { 746 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below 747 int pageDiff = Math.abs(page - mCurrentPage); 748 if (pageDiff <= 0) { 749 // return Process.THREAD_PRIORITY_DEFAULT; 750 return Process.THREAD_PRIORITY_MORE_FAVORABLE; 751 } else if (pageDiff <= 1) { 752 // return Process.THREAD_PRIORITY_BACKGROUND; 753 return Process.THREAD_PRIORITY_DEFAULT; 754 } else { 755 // return Process.THREAD_PRIORITY_LOWEST; 756 return Process.THREAD_PRIORITY_DEFAULT; 757 } 758 } 759 private int getSleepForPage(int page) { 760 int pageDiff = Math.abs(page - mCurrentPage) - 1; 761 return Math.max(0, pageDiff * sPageSleepDelay); 762 } 763 /** 764 * Creates and executes a new AsyncTask to load a page of widget previews. 765 */ 766 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets, 767 int cellWidth, int cellHeight, int cellCountX) { 768 // Prune all tasks that are no longer needed 769 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 770 while (iter.hasNext()) { 771 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 772 int taskPage = task.page; 773 if ((taskPage == page) || 774 taskPage < getAssociatedLowerPageBound(mCurrentPage - mNumAppsPages) || 775 taskPage > getAssociatedUpperPageBound(mCurrentPage - mNumAppsPages)) { 776 task.cancel(false); 777 iter.remove(); 778 } else { 779 task.setThreadPriority(getThreadPriorityForPage(taskPage + mNumAppsPages)); 780 } 781 } 782 783 // We introduce a slight delay to order the loading of side pages so that we don't thrash 784 final int sleepMs = getSleepForPage(page + mNumAppsPages); 785 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight, 786 cellCountX, new AsyncTaskCallback() { 787 @Override 788 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 789 try { 790 try { 791 Thread.sleep(sleepMs); 792 } catch (Exception e) {} 793 loadWidgetPreviewsInBackground(task, data); 794 } finally { 795 if (task.isCancelled()) { 796 data.cleanup(true); 797 } 798 } 799 } 800 }, 801 new AsyncTaskCallback() { 802 @Override 803 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 804 try { 805 mRunningTasks.remove(task); 806 if (task.isCancelled()) return; 807 onSyncWidgetPageItems(data); 808 } finally { 809 data.cleanup(task.isCancelled()); 810 } 811 } 812 }); 813 814 // Ensure that the task is appropriately prioritized and runs in parallel 815 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, 816 AsyncTaskPageData.Type.LoadWidgetPreviewData); 817 t.setThreadPriority(getThreadPriorityForPage(page)); 818 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData); 819 mRunningTasks.add(t); 820 } 821 /** 822 * Creates and executes a new AsyncTask to load the outlines for a page of content. 823 */ 824 private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items, 825 ArrayList<Bitmap> images) { 826 // Prune old tasks for this page 827 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator(); 828 while (iter.hasNext()) { 829 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next(); 830 int taskPage = task.page; 831 if ((taskPage == page) && 832 (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) { 833 task.cancel(false); 834 iter.remove(); 835 } 836 } 837 838 AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images, 839 new AsyncTaskCallback() { 840 @Override 841 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 842 try { 843 // Ensure that this task starts running at the correct priority 844 task.syncThreadPriority(); 845 846 ArrayList<Bitmap> images = data.generatedImages; 847 ArrayList<Bitmap> srcImages = data.sourceImages; 848 int count = srcImages.size(); 849 Canvas c = new Canvas(); 850 for (int i = 0; i < count && !task.isCancelled(); ++i) { 851 // Before work on each item, ensure that this task is running at the correct 852 // priority 853 task.syncThreadPriority(); 854 855 Bitmap b = srcImages.get(i); 856 Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(), 857 Bitmap.Config.ARGB_8888); 858 859 c.setBitmap(outline); 860 c.save(); 861 c.drawBitmap(b, 0, 0, null); 862 c.restore(); 863 c.setBitmap(null); 864 865 images.add(outline); 866 } 867 } finally { 868 if (task.isCancelled()) { 869 data.cleanup(true); 870 } 871 } 872 } 873 }, 874 new AsyncTaskCallback() { 875 @Override 876 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) { 877 try { 878 mRunningTasks.remove(task); 879 if (task.isCancelled()) return; 880 onHolographicPageItemsLoaded(data); 881 } finally { 882 data.cleanup(task.isCancelled()); 883 } 884 } 885 }); 886 887 // Ensure that the outline task always runs in the background, serially 888 AppsCustomizeAsyncTask t = 889 new AppsCustomizeAsyncTask(page, AsyncTaskPageData.Type.LoadHolographicIconsData); 890 t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 891 t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData); 892 mRunningTasks.add(t); 893 } 894 895 /* 896 * Widgets PagedView implementation 897 */ 898 private void setupPage(PagedViewGridLayout layout) { 899 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 900 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 901 902 // Note: We force a measure here to get around the fact that when we do layout calculations 903 // immediately after syncing, we don't have a proper width. 904 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 905 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 906 layout.setMinimumWidth(getPageContentWidth()); 907 layout.measure(widthSpec, heightSpec); 908 } 909 910 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) { 911 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f, 0xFFFFFFFF); 912 } 913 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 914 float scale) { 915 renderDrawableToBitmap(d, bitmap, x, y, w, h, scale, 0xFFFFFFFF); 916 } 917 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 918 float scale, int multiplyColor) { 919 if (bitmap != null) { 920 Canvas c = new Canvas(bitmap); 921 c.scale(scale, scale); 922 Rect oldBounds = d.copyBounds(); 923 d.setBounds(x, y, x + w, y + h); 924 d.draw(c); 925 d.setBounds(oldBounds); // Restore the bounds 926 if (multiplyColor != 0xFFFFFFFF) { 927 c.drawColor(mDragViewMultiplyColor, PorterDuff.Mode.MULTIPLY); 928 } 929 c.setBitmap(null); 930 } 931 } 932 private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { 933 // Render the background 934 int offset = 0; 935 int bitmapSize = mAppIconSize; 936 Bitmap preview = Bitmap.createBitmap(bitmapSize, bitmapSize, Config.ARGB_8888); 937 938 // Render the icon 939 Drawable icon = mIconCache.getFullResIcon(info); 940 renderDrawableToBitmap(icon, preview, offset, offset, mAppIconSize, mAppIconSize); 941 return preview; 942 } 943 private Bitmap getWidgetPreview(AppWidgetProviderInfo info, 944 int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) { 945 946 // Load the preview image if possible 947 String packageName = info.provider.getPackageName(); 948 Drawable drawable = null; 949 Bitmap preview = null; 950 if (info.previewImage != 0) { 951 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); 952 if (drawable == null) { 953 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) 954 + " for provider: " + info.provider); 955 } else { 956 // Map the target width/height to the cell dimensions 957 int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); 958 int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); 959 int targetCellWidth; 960 int targetCellHeight; 961 if (targetWidth >= targetHeight) { 962 targetCellWidth = Math.min(targetWidth, cellWidth); 963 targetCellHeight = (int) (cellHeight * ((float) targetCellWidth / cellWidth)); 964 } else { 965 targetCellHeight = Math.min(targetHeight, cellHeight); 966 targetCellWidth = (int) (cellWidth * ((float) targetCellHeight / cellHeight)); 967 } 968 // Map the preview to the target cell dimensions 969 int bitmapWidth = Math.min(targetCellWidth, drawable.getIntrinsicWidth()); 970 int bitmapHeight = (int) (drawable.getIntrinsicHeight() * 971 ((float) bitmapWidth / drawable.getIntrinsicWidth())); 972 973 preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); 974 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth, bitmapHeight); 975 } 976 } 977 978 // Generate a preview image if we couldn't load one 979 if (drawable == null) { 980 // TODO: This actually uses the apps customize cell layout params, where as we make want 981 // the Workspace params for more accuracy. 982 int targetWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); 983 int targetHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); 984 int bitmapWidth = targetWidth; 985 int bitmapHeight = targetHeight; 986 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage); 987 float iconScale = 1f; 988 989 // Determine the size of the bitmap we want to draw 990 if (cellHSpan == cellVSpan) { 991 // For square widgets, we just have a fixed size for 1x1 and larger-than-1x1 992 if (cellHSpan <= 1) { 993 bitmapWidth = bitmapHeight = mAppIconSize + 2 * minOffset; 994 } else { 995 bitmapWidth = bitmapHeight = mAppIconSize + 4 * minOffset; 996 } 997 } else { 998 // Otherwise, ensure that we are properly sized within the cellWidth/Height 999 if (targetWidth >= targetHeight) { 1000 bitmapWidth = Math.min(targetWidth, cellWidth); 1001 bitmapHeight = (int) (targetHeight * ((float) bitmapWidth / targetWidth)); 1002 iconScale = Math.min((float) bitmapHeight / (mAppIconSize + 2 * minOffset), 1f); 1003 } else { 1004 bitmapHeight = Math.min(targetHeight, cellHeight); 1005 bitmapWidth = (int) (targetWidth * ((float) bitmapHeight / targetHeight)); 1006 iconScale = Math.min((float) bitmapWidth / (mAppIconSize + 2 * minOffset), 1f); 1007 } 1008 } 1009 preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888); 1010 if (cellHSpan != 1 || cellVSpan != 1) { 1011 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, bitmapWidth, 1012 bitmapHeight); 1013 } 1014 1015 // Draw the icon in the top left corner 1016 try { 1017 Drawable icon = null; 1018 int hoffset = (int) (bitmapWidth / 2 - mAppIconSize * iconScale / 2); 1019 int yoffset = (int) (bitmapHeight / 2 - mAppIconSize * iconScale / 2); 1020 if (info.icon > 0) icon = mIconCache.getFullResIcon(packageName, info.icon); 1021 Resources resources = mLauncher.getResources(); 1022 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); 1023 1024 renderDrawableToBitmap(icon, preview, hoffset, yoffset, 1025 (int) (mAppIconSize * iconScale), 1026 (int) (mAppIconSize * iconScale)); 1027 } catch (Resources.NotFoundException e) {} 1028 } 1029 return preview; 1030 } 1031 1032 public void syncWidgetPageItems(int page, boolean immediate) { 1033 int numItemsPerPage = mWidgetCountX * mWidgetCountY; 1034 int contentWidth = mWidgetSpacingLayout.getContentWidth(); 1035 int contentHeight = mWidgetSpacingLayout.getContentHeight(); 1036 1037 // Calculate the dimensions of each cell we are giving to each widget 1038 ArrayList<Object> items = new ArrayList<Object>(); 1039 int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight 1040 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX); 1041 int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom 1042 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY); 1043 1044 // Prepare the set of widgets to load previews for in the background 1045 int offset = page * numItemsPerPage; 1046 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) { 1047 items.add(mWidgets.get(i)); 1048 } 1049 1050 // Prepopulate the pages with the other widget info, and fill in the previews later 1051 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); 1052 layout.setColumnCount(layout.getCellCountX()); 1053 for (int i = 0; i < items.size(); ++i) { 1054 Object rawInfo = items.get(i); 1055 PendingAddItemInfo createItemInfo = null; 1056 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( 1057 R.layout.apps_customize_widget, layout, false); 1058 if (rawInfo instanceof AppWidgetProviderInfo) { 1059 // Fill in the widget information 1060 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1061 createItemInfo = new PendingAddWidgetInfo(info, null, null); 1062 int[] cellSpans = mLauncher.getSpanForWidget(info, null); 1063 widget.applyFromAppWidgetProviderInfo(info, -1, cellSpans, 1064 mHolographicOutlineHelper); 1065 widget.setTag(createItemInfo); 1066 } else if (rawInfo instanceof ResolveInfo) { 1067 // Fill in the shortcuts information 1068 ResolveInfo info = (ResolveInfo) rawInfo; 1069 createItemInfo = new PendingAddItemInfo(); 1070 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 1071 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, 1072 info.activityInfo.name); 1073 widget.applyFromResolveInfo(mPackageManager, info, mHolographicOutlineHelper); 1074 widget.setTag(createItemInfo); 1075 } 1076 widget.setOnClickListener(this); 1077 widget.setOnLongClickListener(this); 1078 widget.setOnTouchListener(this); 1079 1080 // Layout each widget 1081 int ix = i % mWidgetCountX; 1082 int iy = i / mWidgetCountX; 1083 GridLayout.LayoutParams lp = new GridLayout.LayoutParams( 1084 GridLayout.spec(iy, GridLayout.LEFT), 1085 GridLayout.spec(ix, GridLayout.TOP)); 1086 lp.width = cellWidth; 1087 lp.height = cellHeight; 1088 lp.setGravity(Gravity.TOP | Gravity.LEFT); 1089 if (ix > 0) lp.leftMargin = mWidgetWidthGap; 1090 if (iy > 0) lp.topMargin = mWidgetHeightGap; 1091 layout.addView(widget, lp); 1092 } 1093 1094 // Load the widget previews 1095 if (immediate) { 1096 AsyncTaskPageData data = new AsyncTaskPageData(page, items, cellWidth, cellHeight, 1097 mWidgetCountX, null, null); 1098 loadWidgetPreviewsInBackground(null, data); 1099 onSyncWidgetPageItems(data); 1100 } else { 1101 prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, mWidgetCountX); 1102 } 1103 } 1104 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task, 1105 AsyncTaskPageData data) { 1106 if (task != null) { 1107 // Ensure that this task starts running at the correct priority 1108 task.syncThreadPriority(); 1109 } 1110 1111 // Load each of the widget/shortcut previews 1112 ArrayList<Object> items = data.items; 1113 ArrayList<Bitmap> images = data.generatedImages; 1114 int count = items.size(); 1115 int cellWidth = data.cellWidth; 1116 int cellHeight = data.cellHeight; 1117 for (int i = 0; i < count; ++i) { 1118 if (task != null) { 1119 // Ensure we haven't been cancelled yet 1120 if (task.isCancelled()) break; 1121 // Before work on each item, ensure that this task is running at the correct 1122 // priority 1123 task.syncThreadPriority(); 1124 } 1125 1126 Object rawInfo = items.get(i); 1127 if (rawInfo instanceof AppWidgetProviderInfo) { 1128 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 1129 int[] cellSpans = mLauncher.getSpanForWidget(info, null); 1130 images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1], 1131 cellWidth, cellHeight)); 1132 } else if (rawInfo instanceof ResolveInfo) { 1133 // Fill in the shortcuts information 1134 ResolveInfo info = (ResolveInfo) rawInfo; 1135 images.add(getShortcutPreview(info, cellWidth, cellHeight)); 1136 } 1137 } 1138 } 1139 private void onSyncWidgetPageItems(AsyncTaskPageData data) { 1140 int page = data.page; 1141 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page + mNumAppsPages); 1142 1143 ArrayList<Object> items = data.items; 1144 int count = items.size(); 1145 for (int i = 0; i < count; ++i) { 1146 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i); 1147 if (widget != null) { 1148 Bitmap preview = data.generatedImages.get(i); 1149 boolean scale = 1150 (preview.getWidth() >= data.cellWidth || 1151 preview.getHeight() >= data.cellHeight); 1152 1153 widget.applyPreview(new FastBitmapDrawable(preview), i, scale); 1154 } 1155 } 1156 layout.createHardwareLayer(); 1157 1158 invalidate(); 1159 /* TEMPORARILY DISABLE HOLOGRAPHIC ICONS 1160 if (mFadeInAdjacentScreens) { 1161 prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages); 1162 } 1163 */ 1164 } 1165 private void onHolographicPageItemsLoaded(AsyncTaskPageData data) { 1166 // Invalidate early to short-circuit children invalidates 1167 invalidate(); 1168 1169 int page = data.page; 1170 ViewGroup layout = (ViewGroup) getPageAt(page); 1171 if (layout instanceof PagedViewCellLayout) { 1172 PagedViewCellLayout cl = (PagedViewCellLayout) layout; 1173 int count = cl.getPageChildCount(); 1174 if (count != data.generatedImages.size()) return; 1175 for (int i = 0; i < count; ++i) { 1176 PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i); 1177 icon.setHolographicOutline(data.generatedImages.get(i)); 1178 } 1179 } else { 1180 int count = layout.getChildCount(); 1181 if (count != data.generatedImages.size()) return; 1182 for (int i = 0; i < count; ++i) { 1183 View v = layout.getChildAt(i); 1184 ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i)); 1185 } 1186 } 1187 } 1188 1189 @Override 1190 public void syncPages() { 1191 removeAllViews(); 1192 cancelAllTasks(); 1193 1194 Context context = getContext(); 1195 for (int j = 0; j < mNumWidgetPages; ++j) { 1196 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX, 1197 mWidgetCountY); 1198 setupPage(layout); 1199 addView(layout, new PagedViewGridLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1200 LayoutParams.MATCH_PARENT)); 1201 } 1202 1203 for (int i = 0; i < mNumAppsPages; ++i) { 1204 PagedViewCellLayout layout = new PagedViewCellLayout(context); 1205 setupPage(layout); 1206 addView(layout); 1207 } 1208 } 1209 1210 @Override 1211 public void syncPageItems(int page, boolean immediate) { 1212 if (page < mNumAppsPages) { 1213 syncAppsPageItems(page, immediate); 1214 } else { 1215 syncWidgetPageItems(page - mNumAppsPages, immediate); 1216 } 1217 } 1218 1219 // We want our pages to be z-ordered such that the further a page is to the left, the higher 1220 // it is in the z-order. This is important to insure touch events are handled correctly. 1221 View getPageAt(int index) { 1222 return getChildAt(getChildCount() - index - 1); 1223 } 1224 1225 @Override 1226 protected int indexToPage(int index) { 1227 return getChildCount() - index - 1; 1228 } 1229 1230 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack. 1231 @Override 1232 protected void screenScrolled(int screenCenter) { 1233 super.screenScrolled(screenCenter); 1234 1235 for (int i = 0; i < getChildCount(); i++) { 1236 View v = getPageAt(i); 1237 if (v != null) { 1238 float scrollProgress = getScrollProgress(screenCenter, v, i); 1239 1240 float interpolatedProgress = 1241 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0))); 1242 float scale = (1 - interpolatedProgress) + 1243 interpolatedProgress * TRANSITION_SCALE_FACTOR; 1244 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth(); 1245 1246 float alpha; 1247 1248 if (!LauncherApplication.isScreenLarge() || scrollProgress < 0) { 1249 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation( 1250 1 - Math.abs(scrollProgress)) : 1.0f; 1251 } else { 1252 // On large screens we need to fade the page as it nears its leftmost position 1253 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress); 1254 } 1255 1256 v.setCameraDistance(mDensity * CAMERA_DISTANCE); 1257 int pageWidth = v.getMeasuredWidth(); 1258 int pageHeight = v.getMeasuredHeight(); 1259 1260 if (PERFORM_OVERSCROLL_ROTATION) { 1261 if (i == 0 && scrollProgress < 0) { 1262 // Overscroll to the left 1263 v.setPivotX(TRANSITION_PIVOT * pageWidth); 1264 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1265 scale = 1.0f; 1266 alpha = 1.0f; 1267 // On the first page, we don't want the page to have any lateral motion 1268 translationX = getScrollX(); 1269 } else if (i == getChildCount() - 1 && scrollProgress > 0) { 1270 // Overscroll to the right 1271 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth); 1272 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress); 1273 scale = 1.0f; 1274 alpha = 1.0f; 1275 // On the last page, we don't want the page to have any lateral motion. 1276 translationX = getScrollX() - mMaxScrollX; 1277 } else { 1278 v.setPivotY(pageHeight / 2.0f); 1279 v.setPivotX(pageWidth / 2.0f); 1280 v.setRotationY(0f); 1281 } 1282 } 1283 1284 v.setTranslationX(translationX); 1285 v.setScaleX(scale); 1286 v.setScaleY(scale); 1287 v.setAlpha(alpha); 1288 1289 // If the view has 0 alpha, we set it to be invisible so as to prevent 1290 // it from accepting touches 1291 if (alpha < ViewConfiguration.ALPHA_THRESHOLD) { 1292 v.setVisibility(INVISIBLE); 1293 } else if (v.getVisibility() != VISIBLE) { 1294 v.setVisibility(VISIBLE); 1295 } 1296 } 1297 } 1298 } 1299 1300 protected void overScroll(float amount) { 1301 acceleratedOverScroll(amount); 1302 } 1303 1304 /** 1305 * Used by the parent to get the content width to set the tab bar to 1306 * @return 1307 */ 1308 public int getPageContentWidth() { 1309 return mContentWidth; 1310 } 1311 1312 @Override 1313 protected void onPageEndMoving() { 1314 super.onPageEndMoving(); 1315 1316 // We reset the save index when we change pages so that it will be recalculated on next 1317 // rotation 1318 mSaveInstanceStateItemIndex = -1; 1319 } 1320 1321 /* 1322 * AllAppsView implementation 1323 */ 1324 @Override 1325 public void setup(Launcher launcher, DragController dragController) { 1326 mLauncher = launcher; 1327 mDragController = dragController; 1328 } 1329 @Override 1330 public void zoom(float zoom, boolean animate) { 1331 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() 1332 } 1333 @Override 1334 public boolean isVisible() { 1335 return (getVisibility() == VISIBLE); 1336 } 1337 @Override 1338 public boolean isAnimating() { 1339 return false; 1340 } 1341 @Override 1342 public void setApps(ArrayList<ApplicationInfo> list) { 1343 mApps = list; 1344 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); 1345 updatePageCounts(); 1346 1347 // The next layout pass will trigger data-ready if both widgets and apps are set, so 1348 // request a layout to do this test and invalidate the page data when ready. 1349 if (testDataReady()) requestLayout(); 1350 } 1351 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1352 // We add it in place, in alphabetical order 1353 int count = list.size(); 1354 for (int i = 0; i < count; ++i) { 1355 ApplicationInfo info = list.get(i); 1356 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); 1357 if (index < 0) { 1358 mApps.add(-(index + 1), info); 1359 } 1360 } 1361 } 1362 @Override 1363 public void addApps(ArrayList<ApplicationInfo> list) { 1364 addAppsWithoutInvalidate(list); 1365 updatePageCounts(); 1366 invalidatePageData(); 1367 } 1368 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { 1369 ComponentName removeComponent = item.intent.getComponent(); 1370 int length = list.size(); 1371 for (int i = 0; i < length; ++i) { 1372 ApplicationInfo info = list.get(i); 1373 if (info.intent.getComponent().equals(removeComponent)) { 1374 return i; 1375 } 1376 } 1377 return -1; 1378 } 1379 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 1380 // loop through all the apps and remove apps that have the same component 1381 int length = list.size(); 1382 for (int i = 0; i < length; ++i) { 1383 ApplicationInfo info = list.get(i); 1384 int removeIndex = findAppByComponent(mApps, info); 1385 if (removeIndex > -1) { 1386 mApps.remove(removeIndex); 1387 } 1388 } 1389 } 1390 @Override 1391 public void removeApps(ArrayList<ApplicationInfo> list) { 1392 removeAppsWithoutInvalidate(list); 1393 updatePageCounts(); 1394 invalidatePageData(); 1395 } 1396 @Override 1397 public void updateApps(ArrayList<ApplicationInfo> list) { 1398 // We remove and re-add the updated applications list because it's properties may have 1399 // changed (ie. the title), and this will ensure that the items will be in their proper 1400 // place in the list. 1401 removeAppsWithoutInvalidate(list); 1402 addAppsWithoutInvalidate(list); 1403 updatePageCounts(); 1404 1405 invalidatePageData(); 1406 } 1407 1408 @Override 1409 public void reset() { 1410 AppsCustomizeTabHost tabHost = getTabHost(); 1411 String tag = tabHost.getCurrentTabTag(); 1412 if (tag != null) { 1413 if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) { 1414 tabHost.setCurrentTabFromContent(ContentType.Applications); 1415 } 1416 } 1417 if (mCurrentPage != 0) { 1418 invalidatePageData(0); 1419 } 1420 } 1421 1422 private AppsCustomizeTabHost getTabHost() { 1423 return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane); 1424 } 1425 1426 @Override 1427 public void dumpState() { 1428 // TODO: Dump information related to current list of Applications, Widgets, etc. 1429 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); 1430 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); 1431 } 1432 1433 private void dumpAppWidgetProviderInfoList(String tag, String label, 1434 ArrayList<Object> list) { 1435 Log.d(tag, label + " size=" + list.size()); 1436 for (Object i: list) { 1437 if (i instanceof AppWidgetProviderInfo) { 1438 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; 1439 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage 1440 + " resizeMode=" + info.resizeMode + " configure=" + info.configure 1441 + " initialLayout=" + info.initialLayout 1442 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); 1443 } else if (i instanceof ResolveInfo) { 1444 ResolveInfo info = (ResolveInfo) i; 1445 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" 1446 + info.icon); 1447 } 1448 } 1449 } 1450 1451 @Override 1452 public void surrender() { 1453 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we 1454 // should stop this now. 1455 1456 // Stop all background tasks 1457 cancelAllTasks(); 1458 } 1459 1460 /* 1461 * We load an extra page on each side to prevent flashes from scrolling and loading of the 1462 * widget previews in the background with the AsyncTasks. 1463 */ 1464 protected int getAssociatedLowerPageBound(int page) { 1465 return Math.max(0, page - 2); 1466 } 1467 protected int getAssociatedUpperPageBound(int page) { 1468 final int count = getChildCount(); 1469 return Math.min(page + 2, count - 1); 1470 } 1471 1472 @Override 1473 protected String getCurrentPageDescription() { 1474 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; 1475 int stringId = R.string.default_scroll_format; 1476 int count = 0; 1477 1478 if (page < mNumAppsPages) { 1479 stringId = R.string.apps_customize_apps_scroll_format; 1480 count = mNumAppsPages; 1481 } else { 1482 page -= mNumAppsPages; 1483 stringId = R.string.apps_customize_widgets_scroll_format; 1484 count = mNumWidgetPages; 1485 } 1486 1487 return String.format(mContext.getString(stringId), page + 1, count); 1488 } 1489} 1490