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