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