AppsCustomizePagedView.java revision 4dbea7920a5f52df1d35009352f7e5cba16c05fb
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 java.util.ArrayList; 20import java.util.Collections; 21import java.util.List; 22 23import android.animation.Animator; 24import android.animation.AnimatorListenerAdapter; 25import android.animation.ObjectAnimator; 26import android.animation.PropertyValuesHolder; 27import android.appwidget.AppWidgetManager; 28import android.appwidget.AppWidgetProviderInfo; 29import android.content.ComponentName; 30import android.content.Context; 31import android.content.Intent; 32import android.content.pm.PackageManager; 33import android.content.pm.ResolveInfo; 34import android.content.res.Resources; 35import android.content.res.TypedArray; 36import android.graphics.Bitmap; 37import android.graphics.Bitmap.Config; 38import android.graphics.Canvas; 39import android.graphics.Rect; 40import android.graphics.drawable.Drawable; 41import android.util.AttributeSet; 42import android.util.Log; 43import android.util.LruCache; 44import android.view.Gravity; 45import android.view.LayoutInflater; 46import android.view.View; 47import android.view.animation.DecelerateInterpolator; 48import android.view.animation.LinearInterpolator; 49import android.widget.FrameLayout; 50import android.widget.ImageView; 51import android.widget.LinearLayout; 52import android.widget.TextView; 53 54import com.android.launcher.R; 55 56public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements 57 AllAppsView, View.OnClickListener, DragSource { 58 static final String LOG_TAG = "AppsCustomizePagedView"; 59 60 /** 61 * The different content types that this paged view can show. 62 */ 63 public enum ContentType { 64 Applications, 65 Widgets 66 } 67 68 // Refs 69 private Launcher mLauncher; 70 private DragController mDragController; 71 private final LayoutInflater mLayoutInflater; 72 private final PackageManager mPackageManager; 73 74 // Content 75 private ContentType mContentType; 76 private ArrayList<ApplicationInfo> mApps; 77 private List<Object> mWidgets; 78 79 // Caching 80 private Drawable mDefaultWidgetBackground; 81 private final int sWidgetPreviewCacheSize = 1 * 1024 * 1024; // 1 MiB 82 private LruCache<Object, Bitmap> mWidgetPreviewCache; 83 private IconCache mIconCache; 84 85 // Dimens 86 private int mContentWidth; 87 private int mMaxWidgetSpan, mMinWidgetSpan; 88 private int mWidgetCellWidthGap, mWidgetCellHeightGap; 89 private int mWidgetCountX, mWidgetCountY; 90 private final int mWidgetPreviewIconPaddedDimension; 91 private final float sWidgetPreviewIconPaddingPercentage = 0.25f; 92 private PagedViewCellLayout mWidgetSpacingLayout; 93 94 // Animations 95 private final float ANIMATION_SCALE = 0.5f; 96 private final int TRANSLATE_ANIM_DURATION = 400; 97 private final int DROP_ANIM_DURATION = 200; 98 99 public AppsCustomizePagedView(Context context, AttributeSet attrs) { 100 super(context, attrs); 101 mLayoutInflater = LayoutInflater.from(context); 102 mPackageManager = context.getPackageManager(); 103 mContentType = ContentType.Applications; 104 mApps = new ArrayList<ApplicationInfo>(); 105 mWidgets = new ArrayList<Object>(); 106 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache(); 107 mWidgetPreviewCache = new LruCache<Object, Bitmap>(sWidgetPreviewCacheSize) { 108 protected int sizeOf(Object key, Bitmap value) { 109 return value.getByteCount(); 110 } 111 }; 112 113 // Save the default widget preview background 114 Resources resources = context.getResources(); 115 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview); 116 117 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0); 118 mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6); 119 mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4); 120 a.recycle(); 121 a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); 122 mWidgetCellWidthGap = 123 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 10); 124 mWidgetCellHeightGap = 125 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 10); 126 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); 127 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); 128 a.recycle(); 129 130 // Create a dummy page that we can use to approximate the cell dimensions of widgets and 131 // the content width (to be used by our parent) 132 mWidgetSpacingLayout = new PagedViewCellLayout(context); 133 setupPage(mWidgetSpacingLayout); 134 mContentWidth = mWidgetSpacingLayout.getContentWidth(); 135 136 // The max widget span is the length N, such that NxN is the largest bounds that the widget 137 // preview can be before applying the widget scaling 138 mMinWidgetSpan = 1; 139 mMaxWidgetSpan = 3; 140 141 // The padding on the non-matched dimension for the default widget preview icons 142 // (top + bottom) 143 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 144 mWidgetPreviewIconPaddedDimension = 145 (int) (iconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); 146 } 147 148 @Override 149 protected void init() { 150 super.init(); 151 mCenterPagesVertically = false; 152 153 Context context = getContext(); 154 Resources r = context.getResources(); 155 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); 156 } 157 158 public void onPackagesUpdated() { 159 // Get the list of widgets and shortcuts 160 mWidgets.clear(); 161 mWidgets.addAll(AppWidgetManager.getInstance(mLauncher).getInstalledProviders()); 162 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 163 mWidgets.addAll(mPackageManager.queryIntentActivities(shortcutsIntent, 0)); 164 Collections.sort(mWidgets, 165 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); 166 } 167 168 /** 169 * Animates the given item onto the center of a home screen, and then scales the item to 170 * look as though it's disappearing onto that screen. 171 */ 172 private void animateItemOntoScreen(View dragView, 173 final CellLayout layout, final ItemInfo info) { 174 // On the phone, we only want to fade the widget preview out 175 float[] position = new float[2]; 176 position[0] = layout.getWidth() / 2; 177 position[1] = layout.getHeight() / 2; 178 179 mLauncher.getWorkspace().mapPointFromChildToSelf(layout, position); 180 181 int dragViewWidth = dragView.getMeasuredWidth(); 182 int dragViewHeight = dragView.getMeasuredHeight(); 183 float heightOffset = 0; 184 float widthOffset = 0; 185 186 if (dragView instanceof ImageView) { 187 Drawable d = ((ImageView) dragView).getDrawable(); 188 int width = d.getIntrinsicWidth(); 189 int height = d.getIntrinsicHeight(); 190 191 if ((1.0 * width / height) >= (1.0f * dragViewWidth) / dragViewHeight) { 192 float f = (dragViewWidth / (width * 1.0f)); 193 heightOffset = ANIMATION_SCALE * (dragViewHeight - f * height) / 2; 194 } else { 195 float f = (dragViewHeight / (height * 1.0f)); 196 widthOffset = ANIMATION_SCALE * (dragViewWidth - f * width) / 2; 197 } 198 } 199 final float toX = position[0] - dragView.getMeasuredWidth() / 2 + widthOffset; 200 final float toY = position[1] - dragView.getMeasuredHeight() / 2 + heightOffset; 201 202 final DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 203 final View dragCopy = dragLayer.createDragView(dragView); 204 dragCopy.setAlpha(1.0f); 205 206 // Translate the item to the center of the appropriate home screen 207 animateIntoPosition(dragCopy, toX, toY, null); 208 209 // The drop-onto-screen animation begins a bit later, but ends at the same time. 210 final int startDelay = TRANSLATE_ANIM_DURATION - DROP_ANIM_DURATION; 211 212 // Scale down the icon and fade out the alpha 213 animateDropOntoScreen(dragCopy, info, DROP_ANIM_DURATION, startDelay); 214 } 215 216 /** 217 * Animation which scales the view down and animates its alpha, making it appear to disappear 218 * onto a home screen. 219 */ 220 private void animateDropOntoScreen( 221 final View view, final ItemInfo info, int duration, int delay) { 222 final DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 223 final CellLayout layout = mLauncher.getWorkspace().getCurrentDropLayout(); 224 225 ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(view, 226 PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f), 227 PropertyValuesHolder.ofFloat("scaleX", ANIMATION_SCALE), 228 PropertyValuesHolder.ofFloat("scaleY", ANIMATION_SCALE)); 229 anim.setInterpolator(new LinearInterpolator()); 230 if (delay > 0) { 231 anim.setStartDelay(delay); 232 } 233 anim.setDuration(duration); 234 anim.addListener(new AnimatorListenerAdapter() { 235 public void onAnimationEnd(Animator animation) { 236 dragLayer.removeView(view); 237 mLauncher.addExternalItemToScreen(info, layout); 238 info.dropPos = null; 239 } 240 }); 241 anim.start(); 242 } 243 244 /** 245 * Animates the x,y position of the view, and optionally execute a Runnable on animation end. 246 */ 247 private void animateIntoPosition( 248 View view, float toX, float toY, final Runnable endRunnable) { 249 ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(view, 250 PropertyValuesHolder.ofFloat("x", toX), 251 PropertyValuesHolder.ofFloat("y", toY)); 252 anim.setInterpolator(new DecelerateInterpolator(2.5f)); 253 anim.setDuration(TRANSLATE_ANIM_DURATION); 254 if (endRunnable != null) { 255 anim.addListener(new AnimatorListenerAdapter() { 256 @Override 257 public void onAnimationEnd(Animator animation) { 258 endRunnable.run(); 259 } 260 }); 261 } 262 anim.start(); 263 } 264 265 @Override 266 public void onClick(View v) { 267 if (v instanceof PagedViewIcon) { 268 // Animate some feedback to the click 269 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); 270 animateClickFeedback(v, new Runnable() { 271 @Override 272 public void run() { 273 mLauncher.startActivitySafely(appInfo.intent, appInfo); 274 } 275 }); 276 } else if (v instanceof PagedViewWidget) { 277 Workspace w = mLauncher.getWorkspace(); 278 int currentWorkspaceScreen = mLauncher.getCurrentWorkspaceScreen(); 279 final CellLayout cl = (CellLayout) w.getChildAt(currentWorkspaceScreen); 280 final View dragView = v.findViewById(R.id.widget_preview); 281 final ItemInfo itemInfo = (ItemInfo) v.getTag(); 282 animateClickFeedback(v, new Runnable() { 283 @Override 284 public void run() { 285 cl.calculateSpans(itemInfo); 286 if (cl.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY)) { 287 if (LauncherApplication.isScreenXLarge()) { 288 animateItemOntoScreen(dragView, cl, itemInfo); 289 } else { 290 mLauncher.addExternalItemToScreen(itemInfo, cl); 291 itemInfo.dropPos = null; 292 } 293 294 // Hide the pane so we can see the workspace we dropped on 295 mLauncher.showWorkspace(true); 296 } else { 297 mLauncher.showOutOfSpaceMessage(); 298 } 299 } 300 }); 301 } 302 } 303 304 /* 305 * PagedViewWithDraggableItems implementation 306 */ 307 @Override 308 protected void determineDraggingStart(android.view.MotionEvent ev) { 309 // Disable dragging by pulling an app down for now. 310 } 311 private void beginDraggingApplication(View v) { 312 // Make a copy of the ApplicationInfo 313 ApplicationInfo appInfo = new ApplicationInfo((ApplicationInfo) v.getTag()); 314 315 // Show the uninstall button if the app is uninstallable. 316 if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) != 0) { 317 DeleteZone allAppsDeleteZone = (DeleteZone) 318 mLauncher.findViewById(R.id.all_apps_delete_zone); 319 allAppsDeleteZone.setDragAndDropEnabled(true); 320 321 if ((appInfo.flags & ApplicationInfo.UPDATED_SYSTEM_APP_FLAG) != 0) { 322 allAppsDeleteZone.setText(R.string.delete_zone_label_all_apps_system_app); 323 } else { 324 allAppsDeleteZone.setText(R.string.delete_zone_label_all_apps); 325 } 326 } 327 328 // Show the info button 329 ApplicationInfoDropTarget allAppsInfoButton = 330 (ApplicationInfoDropTarget) mLauncher.findViewById(R.id.all_apps_info_target); 331 allAppsInfoButton.setDragAndDropEnabled(true); 332 333 // Compose the drag image (top compound drawable, index is 1) 334 final TextView tv = (TextView) v; 335 final Drawable icon = tv.getCompoundDrawables()[1]; 336 Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), 337 Bitmap.Config.ARGB_8888); 338 Canvas c = new Canvas(b); 339 c.translate((v.getWidth() - icon.getIntrinsicWidth()) / 2, v.getPaddingTop()); 340 icon.draw(c); 341 342 // Compose the visible rect of the drag image 343 Rect dragRect = null; 344 if (v instanceof TextView) { 345 int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size); 346 int top = v.getPaddingTop(); 347 int left = (b.getWidth() - iconSize) / 2; 348 int right = left + iconSize; 349 int bottom = top + iconSize; 350 dragRect = new Rect(left, top, right, bottom); 351 } 352 353 // Start the drag 354 mLauncher.lockScreenOrientation(); 355 mLauncher.getWorkspace().onDragStartedWithItemSpans(1, 1, b); 356 mDragController.startDrag(v, b, this, appInfo, DragController.DRAG_ACTION_COPY, dragRect); 357 b.recycle(); 358 } 359 private void beginDraggingWidget(View v) { 360 // Get the widget preview as the drag representation 361 ImageView image = (ImageView) v.findViewById(R.id.widget_preview); 362 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); 363 364 // Compose the drag image 365 Bitmap b; 366 Drawable preview = image.getDrawable(); 367 int w = preview.getIntrinsicWidth(); 368 int h = preview.getIntrinsicHeight(); 369 if (createItemInfo instanceof PendingAddWidgetInfo) { 370 PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; 371 int[] spanXY = CellLayout.rectToCell(getResources(), 372 createWidgetInfo.minWidth, createWidgetInfo.minHeight, null); 373 createItemInfo.spanX = spanXY[0]; 374 createItemInfo.spanY = spanXY[1]; 375 376 b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 377 renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1); 378 } else { 379 // Workaround for the fact that we don't keep the original ResolveInfo associated with 380 // the shortcut around. To get the icon, we just render the preview image (which has 381 // the shortcut icon) to a new drag bitmap that clips the non-icon space. 382 b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, 383 mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); 384 Canvas c = new Canvas(b); 385 preview.draw(c); 386 createItemInfo.spanX = createItemInfo.spanY = 1; 387 } 388 389 // Start the drag 390 mLauncher.lockScreenOrientation(); 391 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, 392 createItemInfo.spanY, b); 393 mDragController.startDrag(image, b, this, createItemInfo, 394 DragController.DRAG_ACTION_COPY, null); 395 b.recycle(); 396 } 397 @Override 398 protected boolean beginDragging(View v) { 399 if (!super.beginDragging(v)) return false; 400 401 // Hide the pane so that the user can drop onto the workspace, we must do this first, 402 // due to how the drop target layout is computed when we start dragging to the workspace. 403 mLauncher.showWorkspace(true); 404 405 if (v instanceof PagedViewIcon) { 406 beginDraggingApplication(v); 407 } else if (v instanceof PagedViewWidget) { 408 beginDraggingWidget(v); 409 } 410 411 return true; 412 } 413 private void endDragging(boolean success) { 414 post(new Runnable() { 415 // Once the drag operation has fully completed, hence the post, we want to disable the 416 // deleteZone and the appInfoButton in all apps, and re-enable the instance which 417 // live in the workspace 418 public void run() { 419 // if onDestroy was called on Launcher, we might have already deleted the 420 // all apps delete zone / info button, so check if they are null 421 DeleteZone allAppsDeleteZone = 422 (DeleteZone) mLauncher.findViewById(R.id.all_apps_delete_zone); 423 ApplicationInfoDropTarget allAppsInfoButton = 424 (ApplicationInfoDropTarget) mLauncher.findViewById(R.id.all_apps_info_target); 425 426 if (allAppsDeleteZone != null) allAppsDeleteZone.setDragAndDropEnabled(false); 427 if (allAppsInfoButton != null) allAppsInfoButton.setDragAndDropEnabled(false); 428 } 429 }); 430 mLauncher.getWorkspace().onDragStopped(success); 431 mLauncher.unlockScreenOrientation(); 432 } 433 434 /* 435 * DragSource implementation 436 */ 437 @Override 438 public void onDragViewVisible() {} 439 @Override 440 public void onDropCompleted(View target, Object dragInfo, boolean success) { 441 endDragging(success); 442 443 // Display an error message if the drag failed due to there not being enough space on the 444 // target layout we were dropping on. 445 if (!success) { 446 boolean showOutOfSpaceMessage = false; 447 if (target instanceof Workspace) { 448 int currentScreen = mLauncher.getCurrentWorkspaceScreen(); 449 Workspace workspace = (Workspace) target; 450 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); 451 ItemInfo itemInfo = (ItemInfo) dragInfo; 452 if (layout != null) { 453 layout.calculateSpans(itemInfo); 454 showOutOfSpaceMessage = 455 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); 456 } 457 } 458 // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later. 459 if (showOutOfSpaceMessage) { 460 mLauncher.showOutOfSpaceMessage(); 461 } 462 } 463 } 464 465 public void setContentType(ContentType type) { 466 mContentType = type; 467 setCurrentPage(0); 468 invalidatePageData(); 469 } 470 471 /* 472 * Apps PagedView implementation 473 */ 474 private void setupPage(PagedViewCellLayout layout) { 475 layout.setCellCount(mCellCountX, mCellCountY); 476 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 477 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 478 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 479 480 // We force a measure here to get around the fact that when we do layout calculations 481 // immediately after syncing, we don't have a proper width. 482 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 483 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 484 layout.measure(widthSpec, heightSpec); 485 } 486 public void syncAppsPages() { 487 // Ensure that we have the right number of pages 488 Context context = getContext(); 489 int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); 490 for (int i = 0; i < numPages; ++i) { 491 PagedViewCellLayout layout = new PagedViewCellLayout(context); 492 setupPage(layout); 493 addView(layout); 494 } 495 } 496 public void syncAppsPageItems(int page) { 497 // ensure that we have the right number of items on the pages 498 int numPages = getPageCount(); 499 int numCells = mCellCountX * mCellCountY; 500 int startIndex = page * numCells; 501 int endIndex = Math.min(startIndex + numCells, mApps.size()); 502 PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page); 503 layout.removeAllViewsOnPage(); 504 for (int i = startIndex; i < endIndex; ++i) { 505 ApplicationInfo info = mApps.get(i); 506 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( 507 R.layout.apps_customize_application, layout, false); 508 icon.applyFromApplicationInfo(info, mPageViewIconCache, true, (numPages > 1)); 509 icon.setOnClickListener(this); 510 icon.setOnLongClickListener(this); 511 icon.setOnTouchListener(this); 512 513 int index = i - startIndex; 514 int x = index % mCellCountX; 515 int y = index / mCellCountX; 516 setupPage(layout); 517 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 518 } 519 } 520 /* 521 * Widgets PagedView implementation 522 */ 523 private void setupPage(PagedViewExtendedLayout layout) { 524 layout.setGravity(Gravity.LEFT); 525 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 526 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 527 layout.setMinimumWidth(getPageContentWidth()); 528 } 529 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 530 float scaleX, float scaleY) { 531 Canvas c = new Canvas(); 532 if (bitmap != null) c.setBitmap(bitmap); 533 c.save(); 534 c.scale(scaleX, scaleY); 535 Rect oldBounds = d.copyBounds(); 536 d.setBounds(x, y, x + w, y + h); 537 d.draw(c); 538 d.setBounds(oldBounds); // Restore the bounds 539 c.restore(); 540 } 541 private FastBitmapDrawable getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { 542 // Return the cached version if necessary 543 Bitmap cachedBitmap = mWidgetPreviewCache.get(info); 544 if (cachedBitmap != null) { 545 return new FastBitmapDrawable(cachedBitmap); 546 } 547 548 Resources resources = mLauncher.getResources(); 549 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 550 // We only need to make it wide enough so as not allow the preview to be scaled 551 int expectedWidth = cellWidth; 552 int expectedHeight = mWidgetPreviewIconPaddedDimension; 553 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage); 554 555 // Render the icon 556 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888); 557 Drawable icon = mIconCache.getFullResIcon(info, mPackageManager); 558 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, 559 mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, 1f, 1f); 560 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f); 561 FastBitmapDrawable iconDrawable = new FastBitmapDrawable(preview); 562 iconDrawable.setBounds(0, 0, expectedWidth, expectedHeight); 563 mWidgetPreviewCache.put(info, preview); 564 return iconDrawable; 565 } 566 private FastBitmapDrawable getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, 567 int cellVSpan, int cellWidth, int cellHeight) { 568 // Return the cached version if necessary 569 Bitmap cachedBitmap = mWidgetPreviewCache.get(info); 570 if (cachedBitmap != null) { 571 return new FastBitmapDrawable(cachedBitmap); 572 } 573 574 // Calculate the size of the drawable 575 cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan)); 576 cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan)); 577 int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); 578 int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); 579 580 // Scale down the bitmap to fit the space 581 float widgetPreviewScale = (float) cellWidth / expectedWidth; 582 expectedWidth = (int) (widgetPreviewScale * expectedWidth); 583 expectedHeight = (int) (widgetPreviewScale * expectedHeight); 584 585 // Load the preview image if possible 586 String packageName = info.provider.getPackageName(); 587 Drawable drawable = null; 588 FastBitmapDrawable newDrawable = null; 589 if (info.previewImage != 0) { 590 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); 591 if (drawable == null) { 592 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) 593 + " for provider: " + info.provider); 594 } else { 595 // Scale down the preview to the dimensions we want 596 int imageWidth = drawable.getIntrinsicWidth(); 597 int imageHeight = drawable.getIntrinsicHeight(); 598 float aspect = (float) imageWidth / imageHeight; 599 int newWidth = imageWidth; 600 int newHeight = imageHeight; 601 if (aspect > 1f) { 602 newWidth = expectedWidth; 603 newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth)); 604 } else { 605 newHeight = expectedHeight; 606 newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight)); 607 } 608 609 Bitmap preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888); 610 renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f); 611 newDrawable = new FastBitmapDrawable(preview); 612 newDrawable.setBounds(0, 0, newWidth, newHeight); 613 mWidgetPreviewCache.put(info, preview); 614 } 615 } 616 617 // Generate a preview image if we couldn't load one 618 if (drawable == null) { 619 Resources resources = mLauncher.getResources(); 620 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 621 622 // Specify the dimensions of the bitmap 623 if (info.minWidth >= info.minHeight) { 624 expectedWidth = cellWidth; 625 expectedHeight = mWidgetPreviewIconPaddedDimension; 626 } else { 627 // Note that in vertical widgets, we might not have enough space due to the text 628 // label, so be conservative and use the width as a height bound 629 expectedWidth = mWidgetPreviewIconPaddedDimension; 630 expectedHeight = cellWidth; 631 } 632 633 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888); 634 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth, 635 expectedHeight, 1f,1f); 636 637 // Draw the icon in the top left corner 638 try { 639 Drawable icon = null; 640 if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null); 641 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); 642 643 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage); 644 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f); 645 } catch (Resources.NotFoundException e) {} 646 647 newDrawable = new FastBitmapDrawable(preview); 648 newDrawable.setBounds(0, 0, expectedWidth, expectedHeight); 649 mWidgetPreviewCache.put(info, preview); 650 } 651 return newDrawable; 652 } 653 public void syncWidgetPages() { 654 // Ensure that we have the right number of pages 655 Context context = getContext(); 656 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY; 657 int numPages = (int) Math.ceil(mWidgets.size() / (float) numWidgetsPerPage); 658 for (int i = 0; i < numPages; ++i) { 659 PagedViewExtendedLayout layout = new PagedViewExtendedLayout(context); 660 setupPage(layout); 661 addView(layout); 662 } 663 } 664 public void syncWidgetPageItems(int page) { 665 Context context = getContext(); 666 PagedViewExtendedLayout layout = (PagedViewExtendedLayout) getChildAt(page); 667 layout.removeAllViews(); 668 669 // Calculate the dimensions of each cell we are giving to each widget 670 FrameLayout container = new FrameLayout(context); 671 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY; 672 int offset = page * numWidgetsPerPage; 673 int cellWidth = ((mWidgetSpacingLayout.getContentWidth() - mPageLayoutWidthGap 674 - ((mWidgetCountX - 1) * mWidgetCellWidthGap)) / mWidgetCountX); 675 int cellHeight = ((mWidgetSpacingLayout.getContentHeight() - mPageLayoutHeightGap 676 - ((mWidgetCountY - 1) * mWidgetCellHeightGap)) / mWidgetCountY); 677 for (int i = 0; i < Math.min(numWidgetsPerPage, mWidgets.size() - offset); ++i) { 678 Object rawInfo = mWidgets.get(offset + i); 679 PendingAddItemInfo createItemInfo = null; 680 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( 681 R.layout.apps_customize_widget, layout, false); 682 if (rawInfo instanceof AppWidgetProviderInfo) { 683 // Fill in the widget information 684 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 685 createItemInfo = new PendingAddWidgetInfo(info, null, null); 686 final int[] cellSpans = CellLayout.rectToCell(getResources(), info.minWidth, 687 info.minHeight, null); 688 FastBitmapDrawable preview = getWidgetPreview(info, cellSpans[0], cellSpans[1], 689 cellWidth, cellHeight); 690 widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans, null, false); 691 widget.setTag(createItemInfo); 692 } else if (rawInfo instanceof ResolveInfo) { 693 // Fill in the shortcuts information 694 ResolveInfo info = (ResolveInfo) rawInfo; 695 createItemInfo = new PendingAddItemInfo(); 696 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 697 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, 698 info.activityInfo.name); 699 FastBitmapDrawable preview = getShortcutPreview(info, cellWidth, cellHeight); 700 widget.applyFromResolveInfo(mPackageManager, info, preview, null, false); 701 widget.setTag(createItemInfo); 702 } 703 widget.setOnClickListener(this); 704 widget.setOnLongClickListener(this); 705 widget.setOnTouchListener(this); 706 707 // Layout each widget 708 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(cellWidth, cellHeight); 709 int ix = i % mWidgetCountX; 710 int iy = i / mWidgetCountX; 711 lp.leftMargin = (ix * cellWidth) + (ix * mWidgetCellWidthGap); 712 lp.topMargin = (iy * cellHeight) + (iy * mWidgetCellHeightGap); 713 container.addView(widget, lp); 714 } 715 layout.addView(container, new LinearLayout.LayoutParams( 716 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 717 } 718 @Override 719 public void syncPages() { 720 removeAllViews(); 721 switch (mContentType) { 722 case Applications: 723 syncAppsPages(); 724 break; 725 case Widgets: 726 syncWidgetPages(); 727 break; 728 } 729 } 730 @Override 731 public void syncPageItems(int page) { 732 switch (mContentType) { 733 case Applications: 734 syncAppsPageItems(page); 735 break; 736 case Widgets: 737 syncWidgetPageItems(page); 738 break; 739 } 740 } 741 742 /** 743 * Used by the parent to get the content width to set the tab bar to 744 * @return 745 */ 746 public int getPageContentWidth() { 747 return mContentWidth; 748 } 749 750 /* 751 * AllAppsView implementation 752 */ 753 @Override 754 public void setup(Launcher launcher, DragController dragController) { 755 mLauncher = launcher; 756 mDragController = dragController; 757 } 758 @Override 759 public void zoom(float zoom, boolean animate) { 760 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() 761 } 762 @Override 763 public boolean isVisible() { 764 return (getVisibility() == VISIBLE); 765 } 766 @Override 767 public boolean isAnimating() { 768 return false; 769 } 770 @Override 771 public void setApps(ArrayList<ApplicationInfo> list) { 772 mApps = list; 773 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); 774 invalidatePageData(); 775 } 776 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 777 // We add it in place, in alphabetical order 778 int count = list.size(); 779 for (int i = 0; i < count; ++i) { 780 ApplicationInfo info = list.get(i); 781 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); 782 if (index < 0) { 783 mApps.add(-(index + 1), info); 784 } 785 } 786 } 787 @Override 788 public void addApps(ArrayList<ApplicationInfo> list) { 789 addAppsWithoutInvalidate(list); 790 invalidatePageData(); 791 } 792 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { 793 ComponentName removeComponent = item.intent.getComponent(); 794 int length = list.size(); 795 for (int i = 0; i < length; ++i) { 796 ApplicationInfo info = list.get(i); 797 if (info.intent.getComponent().equals(removeComponent)) { 798 return i; 799 } 800 } 801 return -1; 802 } 803 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 804 // loop through all the apps and remove apps that have the same component 805 int length = list.size(); 806 for (int i = 0; i < length; ++i) { 807 ApplicationInfo info = list.get(i); 808 int removeIndex = findAppByComponent(mApps, info); 809 if (removeIndex > -1) { 810 mApps.remove(removeIndex); 811 mPageViewIconCache.removeOutline(new PagedViewIconCache.Key(info)); 812 } 813 } 814 } 815 @Override 816 public void removeApps(ArrayList<ApplicationInfo> list) { 817 removeAppsWithoutInvalidate(list); 818 invalidatePageData(); 819 } 820 @Override 821 public void updateApps(ArrayList<ApplicationInfo> list) { 822 // We remove and re-add the updated applications list because it's properties may have 823 // changed (ie. the title), and this will ensure that the items will be in their proper 824 // place in the list. 825 removeAppsWithoutInvalidate(list); 826 addAppsWithoutInvalidate(list); 827 invalidatePageData(); 828 } 829 @Override 830 public void reset() { 831 if (mContentType != ContentType.Applications) { 832 // Reset to the first page of the Apps pane 833 AppsCustomizeTabHost tabs = (AppsCustomizeTabHost) 834 mLauncher.findViewById(R.id.apps_customize_pane); 835 tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications)); 836 } else { 837 setCurrentPage(0); 838 invalidatePageData(); 839 } 840 } 841 @Override 842 public void dumpState() { 843 // TODO: Dump information related to current list of Applications, Widgets, etc. 844 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); 845 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); 846 } 847 private void dumpAppWidgetProviderInfoList(String tag, String label, 848 List<Object> list) { 849 Log.d(tag, label + " size=" + list.size()); 850 for (Object i: list) { 851 if (i instanceof AppWidgetProviderInfo) { 852 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; 853 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage 854 + " resizeMode=" + info.resizeMode + " configure=" + info.configure 855 + " initialLayout=" + info.initialLayout 856 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); 857 } else if (i instanceof ResolveInfo) { 858 ResolveInfo info = (ResolveInfo) i; 859 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" 860 + info.icon); 861 } 862 } 863 } 864 @Override 865 public void surrender() { 866 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we 867 // should stop this now. 868 } 869} 870