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