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