AppsCustomizePagedView.java revision 563ed71d682cc979a095fff7d27f1afe378508df
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( 509 info, mPageViewIconCache, true, isHardwareAccelerated() && (numPages > 1)); 510 icon.setOnClickListener(this); 511 icon.setOnLongClickListener(this); 512 icon.setOnTouchListener(this); 513 514 int index = i - startIndex; 515 int x = index % mCellCountX; 516 int y = index / mCellCountX; 517 setupPage(layout); 518 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 519 } 520 } 521 /* 522 * Widgets PagedView implementation 523 */ 524 private void setupPage(PagedViewExtendedLayout layout) { 525 layout.setGravity(Gravity.LEFT); 526 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 527 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 528 layout.setMinimumWidth(getPageContentWidth()); 529 } 530 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 531 float scaleX, float scaleY) { 532 Canvas c = new Canvas(); 533 if (bitmap != null) c.setBitmap(bitmap); 534 c.save(); 535 c.scale(scaleX, scaleY); 536 Rect oldBounds = d.copyBounds(); 537 d.setBounds(x, y, x + w, y + h); 538 d.draw(c); 539 d.setBounds(oldBounds); // Restore the bounds 540 c.restore(); 541 } 542 private FastBitmapDrawable getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { 543 // Return the cached version if necessary 544 Bitmap cachedBitmap = mWidgetPreviewCache.get(info); 545 if (cachedBitmap != null) { 546 return new FastBitmapDrawable(cachedBitmap); 547 } 548 549 Resources resources = mLauncher.getResources(); 550 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 551 // We only need to make it wide enough so as not allow the preview to be scaled 552 int expectedWidth = cellWidth; 553 int expectedHeight = mWidgetPreviewIconPaddedDimension; 554 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage); 555 556 // Render the icon 557 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888); 558 Drawable icon = mIconCache.getFullResIcon(info, mPackageManager); 559 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, 560 mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, 1f, 1f); 561 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f); 562 FastBitmapDrawable iconDrawable = new FastBitmapDrawable(preview); 563 iconDrawable.setBounds(0, 0, expectedWidth, expectedHeight); 564 mWidgetPreviewCache.put(info, preview); 565 return iconDrawable; 566 } 567 private FastBitmapDrawable getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan, 568 int cellVSpan, int cellWidth, int cellHeight) { 569 // Return the cached version if necessary 570 Bitmap cachedBitmap = mWidgetPreviewCache.get(info); 571 if (cachedBitmap != null) { 572 return new FastBitmapDrawable(cachedBitmap); 573 } 574 575 // Calculate the size of the drawable 576 cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan)); 577 cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan)); 578 int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan); 579 int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan); 580 581 // Scale down the bitmap to fit the space 582 float widgetPreviewScale = (float) cellWidth / expectedWidth; 583 expectedWidth = (int) (widgetPreviewScale * expectedWidth); 584 expectedHeight = (int) (widgetPreviewScale * expectedHeight); 585 586 // Load the preview image if possible 587 String packageName = info.provider.getPackageName(); 588 Drawable drawable = null; 589 FastBitmapDrawable newDrawable = null; 590 if (info.previewImage != 0) { 591 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null); 592 if (drawable == null) { 593 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) 594 + " for provider: " + info.provider); 595 } else { 596 // Scale down the preview to the dimensions we want 597 int imageWidth = drawable.getIntrinsicWidth(); 598 int imageHeight = drawable.getIntrinsicHeight(); 599 float aspect = (float) imageWidth / imageHeight; 600 int newWidth = imageWidth; 601 int newHeight = imageHeight; 602 if (aspect > 1f) { 603 newWidth = expectedWidth; 604 newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth)); 605 } else { 606 newHeight = expectedHeight; 607 newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight)); 608 } 609 610 Bitmap preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888); 611 renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f); 612 newDrawable = new FastBitmapDrawable(preview); 613 newDrawable.setBounds(0, 0, newWidth, newHeight); 614 mWidgetPreviewCache.put(info, preview); 615 } 616 } 617 618 // Generate a preview image if we couldn't load one 619 if (drawable == null) { 620 Resources resources = mLauncher.getResources(); 621 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 622 623 // Specify the dimensions of the bitmap 624 if (info.minWidth >= info.minHeight) { 625 expectedWidth = cellWidth; 626 expectedHeight = mWidgetPreviewIconPaddedDimension; 627 } else { 628 // Note that in vertical widgets, we might not have enough space due to the text 629 // label, so be conservative and use the width as a height bound 630 expectedWidth = mWidgetPreviewIconPaddedDimension; 631 expectedHeight = cellWidth; 632 } 633 634 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888); 635 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth, 636 expectedHeight, 1f,1f); 637 638 // Draw the icon in the top left corner 639 try { 640 Drawable icon = null; 641 if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null); 642 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application); 643 644 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage); 645 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f); 646 } catch (Resources.NotFoundException e) {} 647 648 newDrawable = new FastBitmapDrawable(preview); 649 newDrawable.setBounds(0, 0, expectedWidth, expectedHeight); 650 mWidgetPreviewCache.put(info, preview); 651 } 652 return newDrawable; 653 } 654 public void syncWidgetPages() { 655 // Ensure that we have the right number of pages 656 Context context = getContext(); 657 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY; 658 int numPages = (int) Math.ceil(mWidgets.size() / (float) numWidgetsPerPage); 659 for (int i = 0; i < numPages; ++i) { 660 PagedViewExtendedLayout layout = new PagedViewExtendedLayout(context); 661 setupPage(layout); 662 addView(layout); 663 } 664 } 665 public void syncWidgetPageItems(int page) { 666 Context context = getContext(); 667 PagedViewExtendedLayout layout = (PagedViewExtendedLayout) getChildAt(page); 668 layout.removeAllViews(); 669 670 // Calculate the dimensions of each cell we are giving to each widget 671 FrameLayout container = new FrameLayout(context); 672 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY; 673 int offset = page * numWidgetsPerPage; 674 int cellWidth = ((mWidgetSpacingLayout.getContentWidth() - mPageLayoutWidthGap 675 - ((mWidgetCountX - 1) * mWidgetCellWidthGap)) / mWidgetCountX); 676 int cellHeight = ((mWidgetSpacingLayout.getContentHeight() - mPageLayoutHeightGap 677 - ((mWidgetCountY - 1) * mWidgetCellHeightGap)) / mWidgetCountY); 678 for (int i = 0; i < Math.min(numWidgetsPerPage, mWidgets.size() - offset); ++i) { 679 Object rawInfo = mWidgets.get(offset + i); 680 PendingAddItemInfo createItemInfo = null; 681 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate( 682 R.layout.apps_customize_widget, layout, false); 683 if (rawInfo instanceof AppWidgetProviderInfo) { 684 // Fill in the widget information 685 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo; 686 createItemInfo = new PendingAddWidgetInfo(info, null, null); 687 final int[] cellSpans = CellLayout.rectToCell(getResources(), info.minWidth, 688 info.minHeight, null); 689 FastBitmapDrawable preview = getWidgetPreview(info, cellSpans[0], cellSpans[1], 690 cellWidth, cellHeight); 691 widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans, null, false); 692 widget.setTag(createItemInfo); 693 } else if (rawInfo instanceof ResolveInfo) { 694 // Fill in the shortcuts information 695 ResolveInfo info = (ResolveInfo) rawInfo; 696 createItemInfo = new PendingAddItemInfo(); 697 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; 698 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName, 699 info.activityInfo.name); 700 FastBitmapDrawable preview = getShortcutPreview(info, cellWidth, cellHeight); 701 widget.applyFromResolveInfo(mPackageManager, info, preview, null, false); 702 widget.setTag(createItemInfo); 703 } 704 widget.setOnClickListener(this); 705 widget.setOnLongClickListener(this); 706 widget.setOnTouchListener(this); 707 708 // Layout each widget 709 FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(cellWidth, cellHeight); 710 int ix = i % mWidgetCountX; 711 int iy = i / mWidgetCountX; 712 lp.leftMargin = (ix * cellWidth) + (ix * mWidgetCellWidthGap); 713 lp.topMargin = (iy * cellHeight) + (iy * mWidgetCellHeightGap); 714 container.addView(widget, lp); 715 } 716 layout.addView(container, new LinearLayout.LayoutParams( 717 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 718 } 719 @Override 720 public void syncPages() { 721 removeAllViews(); 722 switch (mContentType) { 723 case Applications: 724 syncAppsPages(); 725 break; 726 case Widgets: 727 syncWidgetPages(); 728 break; 729 } 730 } 731 @Override 732 public void syncPageItems(int page) { 733 switch (mContentType) { 734 case Applications: 735 syncAppsPageItems(page); 736 break; 737 case Widgets: 738 syncWidgetPageItems(page); 739 break; 740 } 741 } 742 743 /** 744 * Used by the parent to get the content width to set the tab bar to 745 * @return 746 */ 747 public int getPageContentWidth() { 748 return mContentWidth; 749 } 750 751 /* 752 * AllAppsView implementation 753 */ 754 @Override 755 public void setup(Launcher launcher, DragController dragController) { 756 mLauncher = launcher; 757 mDragController = dragController; 758 } 759 @Override 760 public void zoom(float zoom, boolean animate) { 761 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed() 762 } 763 @Override 764 public boolean isVisible() { 765 return (getVisibility() == VISIBLE); 766 } 767 @Override 768 public boolean isAnimating() { 769 return false; 770 } 771 @Override 772 public void setApps(ArrayList<ApplicationInfo> list) { 773 mApps = list; 774 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR); 775 invalidatePageData(); 776 } 777 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 778 // We add it in place, in alphabetical order 779 int count = list.size(); 780 for (int i = 0; i < count; ++i) { 781 ApplicationInfo info = list.get(i); 782 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR); 783 if (index < 0) { 784 mApps.add(-(index + 1), info); 785 } 786 } 787 } 788 @Override 789 public void addApps(ArrayList<ApplicationInfo> list) { 790 addAppsWithoutInvalidate(list); 791 invalidatePageData(); 792 } 793 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) { 794 ComponentName removeComponent = item.intent.getComponent(); 795 int length = list.size(); 796 for (int i = 0; i < length; ++i) { 797 ApplicationInfo info = list.get(i); 798 if (info.intent.getComponent().equals(removeComponent)) { 799 return i; 800 } 801 } 802 return -1; 803 } 804 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) { 805 // loop through all the apps and remove apps that have the same component 806 int length = list.size(); 807 for (int i = 0; i < length; ++i) { 808 ApplicationInfo info = list.get(i); 809 int removeIndex = findAppByComponent(mApps, info); 810 if (removeIndex > -1) { 811 mApps.remove(removeIndex); 812 mPageViewIconCache.removeOutline(new PagedViewIconCache.Key(info)); 813 } 814 } 815 } 816 @Override 817 public void removeApps(ArrayList<ApplicationInfo> list) { 818 removeAppsWithoutInvalidate(list); 819 invalidatePageData(); 820 } 821 @Override 822 public void updateApps(ArrayList<ApplicationInfo> list) { 823 // We remove and re-add the updated applications list because it's properties may have 824 // changed (ie. the title), and this will ensure that the items will be in their proper 825 // place in the list. 826 removeAppsWithoutInvalidate(list); 827 addAppsWithoutInvalidate(list); 828 invalidatePageData(); 829 } 830 @Override 831 public void reset() { 832 if (mContentType != ContentType.Applications) { 833 // Reset to the first page of the Apps pane 834 AppsCustomizeTabHost tabs = (AppsCustomizeTabHost) 835 mLauncher.findViewById(R.id.apps_customize_pane); 836 tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications)); 837 } else { 838 setCurrentPage(0); 839 invalidatePageData(); 840 } 841 } 842 @Override 843 public void dumpState() { 844 // TODO: Dump information related to current list of Applications, Widgets, etc. 845 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps); 846 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets); 847 } 848 private void dumpAppWidgetProviderInfoList(String tag, String label, 849 List<Object> list) { 850 Log.d(tag, label + " size=" + list.size()); 851 for (Object i: list) { 852 if (i instanceof AppWidgetProviderInfo) { 853 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i; 854 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage 855 + " resizeMode=" + info.resizeMode + " configure=" + info.configure 856 + " initialLayout=" + info.initialLayout 857 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight); 858 } else if (i instanceof ResolveInfo) { 859 ResolveInfo info = (ResolveInfo) i; 860 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon=" 861 + info.icon); 862 } 863 } 864 } 865 @Override 866 public void surrender() { 867 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we 868 // should stop this now. 869 } 870} 871