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