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