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