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