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