AppsCustomizePagedView.java revision b9b8ce94ff958792dd6ef81b0e50784fe8ad98a6
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 84 // Dimens 85 private int mContentWidth; 86 private int mMaxWidgetSpan, mMinWidgetSpan; 87 private int mWidgetCellWidthGap, mWidgetCellHeightGap; 88 private int mWidgetCountX, mWidgetCountY; 89 private final int mWidgetPreviewIconPaddedDimension; 90 private final float sWidgetPreviewIconPaddingPercentage = 0.25f; 91 private PagedViewCellLayout mWidgetSpacingLayout; 92 93 // Animations 94 private final float ANIMATION_SCALE = 0.5f; 95 private final int TRANSLATE_ANIM_DURATION = 400; 96 private final int DROP_ANIM_DURATION = 200; 97 98 public AppsCustomizePagedView(Context context, AttributeSet attrs) { 99 super(context, attrs); 100 mLayoutInflater = LayoutInflater.from(context); 101 mPackageManager = context.getPackageManager(); 102 mContentType = ContentType.Applications; 103 mApps = new ArrayList<ApplicationInfo>(); 104 mWidgets = new ArrayList<Object>(); 105 mWidgetPreviewCache = new LruCache<Object, Bitmap>(sWidgetPreviewCacheSize) { 106 protected int sizeOf(Object key, Bitmap value) { 107 return value.getByteCount(); 108 } 109 }; 110 111 // Save the default widget preview background 112 Resources resources = context.getResources(); 113 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview); 114 115 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0); 116 mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6); 117 mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4); 118 a.recycle(); 119 a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0); 120 mWidgetCellWidthGap = 121 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 10); 122 mWidgetCellHeightGap = 123 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 10); 124 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2); 125 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2); 126 a.recycle(); 127 128 // Create a dummy page that we can use to approximate the cell dimensions of widgets and 129 // the content width (to be used by our parent) 130 mWidgetSpacingLayout = new PagedViewCellLayout(context); 131 setupPage(mWidgetSpacingLayout); 132 mContentWidth = mWidgetSpacingLayout.getContentWidth(); 133 134 // The max widget span is the length N, such that NxN is the largest bounds that the widget 135 // preview can be before applying the widget scaling 136 mMinWidgetSpan = 1; 137 mMaxWidgetSpan = 3; 138 139 // The padding on the non-matched dimension for the default widget preview icons 140 // (top + bottom) 141 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 142 mWidgetPreviewIconPaddedDimension = 143 (int) (iconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage))); 144 } 145 146 @Override 147 protected void init() { 148 super.init(); 149 mCenterPagesVertically = false; 150 151 Context context = getContext(); 152 Resources r = context.getResources(); 153 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f); 154 } 155 156 public void onPackagesUpdated() { 157 // Get the list of widgets and shortcuts 158 mWidgets.clear(); 159 mWidgets.addAll(AppWidgetManager.getInstance(mLauncher).getInstalledProviders()); 160 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 161 mWidgets.addAll(mPackageManager.queryIntentActivities(shortcutsIntent, 0)); 162 Collections.sort(mWidgets, 163 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager)); 164 } 165 166 /** 167 * Animates the given item onto the center of a home screen, and then scales the item to 168 * look as though it's disappearing onto that screen. 169 */ 170 private void animateItemOntoScreen(View dragView, 171 final CellLayout layout, final ItemInfo info) { 172 // On the phone, we only want to fade the widget preview out 173 float[] position = new float[2]; 174 position[0] = layout.getWidth() / 2; 175 position[1] = layout.getHeight() / 2; 176 177 mLauncher.getWorkspace().mapPointFromChildToSelf(layout, position); 178 179 int dragViewWidth = dragView.getMeasuredWidth(); 180 int dragViewHeight = dragView.getMeasuredHeight(); 181 float heightOffset = 0; 182 float widthOffset = 0; 183 184 if (dragView instanceof ImageView) { 185 Drawable d = ((ImageView) dragView).getDrawable(); 186 int width = d.getIntrinsicWidth(); 187 int height = d.getIntrinsicHeight(); 188 189 if ((1.0 * width / height) >= (1.0f * dragViewWidth) / dragViewHeight) { 190 float f = (dragViewWidth / (width * 1.0f)); 191 heightOffset = ANIMATION_SCALE * (dragViewHeight - f * height) / 2; 192 } else { 193 float f = (dragViewHeight / (height * 1.0f)); 194 widthOffset = ANIMATION_SCALE * (dragViewWidth - f * width) / 2; 195 } 196 } 197 final float toX = position[0] - dragView.getMeasuredWidth() / 2 + widthOffset; 198 final float toY = position[1] - dragView.getMeasuredHeight() / 2 + heightOffset; 199 200 final DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 201 final View dragCopy = dragLayer.createDragView(dragView); 202 dragCopy.setAlpha(1.0f); 203 204 // Translate the item to the center of the appropriate home screen 205 animateIntoPosition(dragCopy, toX, toY, null); 206 207 // The drop-onto-screen animation begins a bit later, but ends at the same time. 208 final int startDelay = TRANSLATE_ANIM_DURATION - DROP_ANIM_DURATION; 209 210 // Scale down the icon and fade out the alpha 211 animateDropOntoScreen(dragCopy, info, DROP_ANIM_DURATION, startDelay); 212 } 213 214 /** 215 * Animation which scales the view down and animates its alpha, making it appear to disappear 216 * onto a home screen. 217 */ 218 private void animateDropOntoScreen( 219 final View view, final ItemInfo info, int duration, int delay) { 220 final DragLayer dragLayer = (DragLayer) mLauncher.findViewById(R.id.drag_layer); 221 final CellLayout layout = mLauncher.getWorkspace().getCurrentDropLayout(); 222 223 ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(view, 224 PropertyValuesHolder.ofFloat("alpha", 1.0f, 0.0f), 225 PropertyValuesHolder.ofFloat("scaleX", ANIMATION_SCALE), 226 PropertyValuesHolder.ofFloat("scaleY", ANIMATION_SCALE)); 227 anim.setInterpolator(new LinearInterpolator()); 228 if (delay > 0) { 229 anim.setStartDelay(delay); 230 } 231 anim.setDuration(duration); 232 anim.addListener(new AnimatorListenerAdapter() { 233 public void onAnimationEnd(Animator animation) { 234 dragLayer.removeView(view); 235 mLauncher.addExternalItemToScreen(info, layout); 236 info.dropPos = null; 237 } 238 }); 239 anim.start(); 240 } 241 242 /** 243 * Animates the x,y position of the view, and optionally execute a Runnable on animation end. 244 */ 245 private void animateIntoPosition( 246 View view, float toX, float toY, final Runnable endRunnable) { 247 ObjectAnimator anim = ObjectAnimator.ofPropertyValuesHolder(view, 248 PropertyValuesHolder.ofFloat("x", toX), 249 PropertyValuesHolder.ofFloat("y", toY)); 250 anim.setInterpolator(new DecelerateInterpolator(2.5f)); 251 anim.setDuration(TRANSLATE_ANIM_DURATION); 252 if (endRunnable != null) { 253 anim.addListener(new AnimatorListenerAdapter() { 254 @Override 255 public void onAnimationEnd(Animator animation) { 256 endRunnable.run(); 257 } 258 }); 259 } 260 anim.start(); 261 } 262 263 @Override 264 public void onClick(View v) { 265 if (v instanceof PagedViewIcon) { 266 // Animate some feedback to the click 267 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag(); 268 animateClickFeedback(v, new Runnable() { 269 @Override 270 public void run() { 271 mLauncher.startActivitySafely(appInfo.intent, appInfo); 272 } 273 }); 274 } else if (v instanceof PagedViewWidget) { 275 Workspace w = mLauncher.getWorkspace(); 276 int currentWorkspaceScreen = mLauncher.getCurrentWorkspaceScreen(); 277 final CellLayout cl = (CellLayout) w.getChildAt(currentWorkspaceScreen); 278 final View dragView = v.findViewById(R.id.widget_preview); 279 final ItemInfo itemInfo = (ItemInfo) v.getTag(); 280 animateClickFeedback(v, new Runnable() { 281 @Override 282 public void run() { 283 cl.calculateSpans(itemInfo); 284 if (cl.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY)) { 285 if (LauncherApplication.isScreenXLarge()) { 286 animateItemOntoScreen(dragView, cl, itemInfo); 287 } else { 288 mLauncher.addExternalItemToScreen(itemInfo, cl); 289 itemInfo.dropPos = null; 290 } 291 292 // Hide the pane so we can see the workspace we dropped on 293 mLauncher.showWorkspace(true); 294 } else { 295 mLauncher.showOutOfSpaceMessage(); 296 } 297 } 298 }); 299 } 300 } 301 302 /* 303 * PagedViewWithDraggableItems implementation 304 */ 305 @Override 306 protected void determineDraggingStart(android.view.MotionEvent ev) { 307 // Disable dragging by pulling an app down for now. 308 } 309 private void beginDraggingApplication(View v) { 310 // Make a copy of the ApplicationInfo 311 ApplicationInfo appInfo = new ApplicationInfo((ApplicationInfo) v.getTag()); 312 313 // Show the uninstall button if the app is uninstallable. 314 if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) != 0) { 315 DeleteZone allAppsDeleteZone = (DeleteZone) 316 mLauncher.findViewById(R.id.all_apps_delete_zone); 317 allAppsDeleteZone.setDragAndDropEnabled(true); 318 319 if ((appInfo.flags & ApplicationInfo.UPDATED_SYSTEM_APP_FLAG) != 0) { 320 allAppsDeleteZone.setText(R.string.delete_zone_label_all_apps_system_app); 321 } else { 322 allAppsDeleteZone.setText(R.string.delete_zone_label_all_apps); 323 } 324 } 325 326 // Show the info button 327 ApplicationInfoDropTarget allAppsInfoButton = 328 (ApplicationInfoDropTarget) mLauncher.findViewById(R.id.all_apps_info_target); 329 allAppsInfoButton.setDragAndDropEnabled(true); 330 331 // Compose the drag image (top compound drawable, index is 1) 332 final TextView tv = (TextView) v; 333 final Drawable icon = tv.getCompoundDrawables()[1]; 334 Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), 335 Bitmap.Config.ARGB_8888); 336 Canvas c = new Canvas(b); 337 c.translate((v.getWidth() - icon.getIntrinsicWidth()) / 2, v.getPaddingTop()); 338 icon.draw(c); 339 340 // Compose the visible rect of the drag image 341 Rect dragRect = null; 342 if (v instanceof TextView) { 343 int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size); 344 int top = v.getPaddingTop(); 345 int left = (b.getWidth() - iconSize) / 2; 346 int right = left + iconSize; 347 int bottom = top + iconSize; 348 dragRect = new Rect(left, top, right, bottom); 349 } 350 351 // Start the drag 352 mLauncher.lockScreenOrientation(); 353 mLauncher.getWorkspace().onDragStartedWithItemSpans(1, 1, b); 354 mDragController.startDrag(v, b, this, appInfo, DragController.DRAG_ACTION_COPY, dragRect); 355 b.recycle(); 356 } 357 private void beginDraggingWidget(View v) { 358 // Get the widget preview as the drag representation 359 ImageView image = (ImageView) v.findViewById(R.id.widget_preview); 360 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); 361 362 // Compose the drag image 363 Bitmap b; 364 Drawable preview = image.getDrawable(); 365 int w = preview.getIntrinsicWidth(); 366 int h = preview.getIntrinsicHeight(); 367 if (createItemInfo instanceof PendingAddWidgetInfo) { 368 PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; 369 int[] spanXY = CellLayout.rectToCell(getResources(), 370 createWidgetInfo.minWidth, createWidgetInfo.minHeight, null); 371 createItemInfo.spanX = spanXY[0]; 372 createItemInfo.spanY = spanXY[1]; 373 374 b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 375 renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1); 376 } else { 377 // Workaround for the fact that we don't keep the original ResolveInfo associated with 378 // the shortcut around. To get the icon, we just render the preview image (which has 379 // the shortcut icon) to a new drag bitmap that clips the non-icon space. 380 b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension, 381 mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888); 382 Canvas c = new Canvas(b); 383 preview.draw(c); 384 createItemInfo.spanX = createItemInfo.spanY = 1; 385 } 386 387 // Start the drag 388 mLauncher.lockScreenOrientation(); 389 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX, 390 createItemInfo.spanY, b); 391 mDragController.startDrag(image, b, this, createItemInfo, 392 DragController.DRAG_ACTION_COPY, null); 393 b.recycle(); 394 } 395 @Override 396 protected boolean beginDragging(View v) { 397 if (!super.beginDragging(v)) return false; 398 399 // Hide the pane so that the user can drop onto the workspace, we must do this first, 400 // due to how the drop target layout is computed when we start dragging to the workspace. 401 mLauncher.showWorkspace(true); 402 403 if (v instanceof PagedViewIcon) { 404 beginDraggingApplication(v); 405 } else if (v instanceof PagedViewWidget) { 406 beginDraggingWidget(v); 407 } 408 409 return true; 410 } 411 private void endDragging(boolean success) { 412 post(new Runnable() { 413 // Once the drag operation has fully completed, hence the post, we want to disable the 414 // deleteZone and the appInfoButton in all apps, and re-enable the instance which 415 // live in the workspace 416 public void run() { 417 // if onDestroy was called on Launcher, we might have already deleted the 418 // all apps delete zone / info button, so check if they are null 419 DeleteZone allAppsDeleteZone = 420 (DeleteZone) mLauncher.findViewById(R.id.all_apps_delete_zone); 421 ApplicationInfoDropTarget allAppsInfoButton = 422 (ApplicationInfoDropTarget) mLauncher.findViewById(R.id.all_apps_info_target); 423 424 if (allAppsDeleteZone != null) allAppsDeleteZone.setDragAndDropEnabled(false); 425 if (allAppsInfoButton != null) allAppsInfoButton.setDragAndDropEnabled(false); 426 } 427 }); 428 mLauncher.getWorkspace().onDragStopped(success); 429 mLauncher.unlockScreenOrientation(); 430 } 431 432 /* 433 * DragSource implementation 434 */ 435 @Override 436 public void onDragViewVisible() {} 437 @Override 438 public void onDropCompleted(View target, Object dragInfo, boolean success) { 439 endDragging(success); 440 441 // Display an error message if the drag failed due to there not being enough space on the 442 // target layout we were dropping on. 443 if (!success) { 444 boolean showOutOfSpaceMessage = false; 445 if (target instanceof Workspace) { 446 int currentScreen = mLauncher.getCurrentWorkspaceScreen(); 447 Workspace workspace = (Workspace) target; 448 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); 449 ItemInfo itemInfo = (ItemInfo) dragInfo; 450 if (layout != null) { 451 layout.calculateSpans(itemInfo); 452 showOutOfSpaceMessage = 453 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); 454 } 455 } 456 // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later. 457 if (showOutOfSpaceMessage) { 458 mLauncher.showOutOfSpaceMessage(); 459 } 460 } 461 } 462 463 public void setContentType(ContentType type) { 464 mContentType = type; 465 setCurrentPage(0); 466 invalidatePageData(); 467 } 468 469 /* 470 * Apps PagedView implementation 471 */ 472 private void setupPage(PagedViewCellLayout layout) { 473 layout.setCellCount(mCellCountX, mCellCountY); 474 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap); 475 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 476 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 477 478 // We force a measure here to get around the fact that when we do layout calculations 479 // immediately after syncing, we don't have a proper width. 480 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST); 481 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST); 482 layout.measure(widthSpec, heightSpec); 483 } 484 public void syncAppsPages() { 485 // Ensure that we have the right number of pages 486 Context context = getContext(); 487 int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY)); 488 for (int i = 0; i < numPages; ++i) { 489 PagedViewCellLayout layout = new PagedViewCellLayout(context); 490 setupPage(layout); 491 addView(layout); 492 } 493 } 494 public void syncAppsPageItems(int page) { 495 // ensure that we have the right number of items on the pages 496 int numPages = getPageCount(); 497 int numCells = mCellCountX * mCellCountY; 498 int startIndex = page * numCells; 499 int endIndex = Math.min(startIndex + numCells, mApps.size()); 500 PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page); 501 layout.removeAllViewsOnPage(); 502 for (int i = startIndex; i < endIndex; ++i) { 503 ApplicationInfo info = mApps.get(i); 504 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate( 505 R.layout.apps_customize_application, layout, false); 506 icon.applyFromApplicationInfo( 507 info, mPageViewIconCache, true, isHardwareAccelerated() && (numPages > 1)); 508 icon.setOnClickListener(this); 509 icon.setOnLongClickListener(this); 510 icon.setOnTouchListener(this); 511 512 int index = i - startIndex; 513 int x = index % mCellCountX; 514 int y = index / mCellCountX; 515 setupPage(layout); 516 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1)); 517 } 518 } 519 /* 520 * Widgets PagedView implementation 521 */ 522 private void setupPage(PagedViewExtendedLayout layout) { 523 layout.setGravity(Gravity.LEFT); 524 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop, 525 mPageLayoutPaddingRight, mPageLayoutPaddingBottom); 526 layout.setMinimumWidth(getPageContentWidth()); 527 } 528 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h, 529 float scaleX, float scaleY) { 530 Canvas c = new Canvas(); 531 if (bitmap != null) c.setBitmap(bitmap); 532 c.save(); 533 c.scale(scaleX, scaleY); 534 Rect oldBounds = d.copyBounds(); 535 d.setBounds(x, y, x + w, y + h); 536 d.draw(c); 537 d.setBounds(oldBounds); // Restore the bounds 538 c.restore(); 539 } 540 private FastBitmapDrawable getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) { 541 // Return the cached version if necessary 542 Bitmap cachedBitmap = mWidgetPreviewCache.get(info); 543 if (cachedBitmap != null) { 544 return new FastBitmapDrawable(cachedBitmap); 545 } 546 547 Resources resources = mLauncher.getResources(); 548 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size); 549 // We only need to make it wide enough so as not allow the preview to be scaled 550 int expectedWidth = cellWidth; 551 int expectedHeight = mWidgetPreviewIconPaddedDimension; 552 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage); 553 554 // Render the icon 555 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888); 556 IconCache cache = ((LauncherApplication) mLauncher.getApplication()).getIconCache(); 557 Drawable icon = cache.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