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