blob: 0c4867cf166d4baaf252008e6e1f7e8a5b25fcfa [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 Chung63257c12011-05-05 17:06:13 -070047import android.view.ViewGroup;
Winson Chung4b576be2011-04-27 17:40:20 -070048import android.view.animation.DecelerateInterpolator;
49import android.view.animation.LinearInterpolator;
50import android.widget.FrameLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070051import android.widget.ImageView;
Winson Chung4b576be2011-04-27 17:40:20 -070052import android.widget.LinearLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070053import 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;
Winson Chung1ed747a2011-05-03 16:18:34 -070078 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;
Winson Chung4dbea792011-05-05 14:21:32 -070084 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -070085
86 // Dimens
87 private int mContentWidth;
Winson Chung4b576be2011-04-27 17:40:20 -070088 private int mMaxWidgetSpan, mMinWidgetSpan;
89 private int mWidgetCellWidthGap, mWidgetCellHeightGap;
90 private int mWidgetCountX, mWidgetCountY;
Winson Chung1ed747a2011-05-03 16:18:34 -070091 private final int mWidgetPreviewIconPaddedDimension;
92 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -070093 private PagedViewCellLayout mWidgetSpacingLayout;
94
Winson Chung4b576be2011-04-27 17:40:20 -070095 // 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
Winson Chung785d2eb2011-04-14 16:08:02 -0700100 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>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700106 mWidgets = new ArrayList<Object>();
Winson Chung4dbea792011-05-05 14:21:32 -0700107 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
Winson Chung1ed747a2011-05-03 16:18:34 -0700108 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);
Winson Chung785d2eb2011-04-14 16:08:02 -0700117
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();
Winson Chung4b576be2011-04-27 17:40:20 -0700122 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();
Winson Chung785d2eb2011-04-14 16:08:02 -0700130
Winson Chung4b576be2011-04-27 17:40:20 -0700131 // 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)
Winson Chung785d2eb2011-04-14 16:08:02 -0700133 mWidgetSpacingLayout = new PagedViewCellLayout(context);
Winson Chung4b576be2011-04-27 17:40:20 -0700134 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;
Winson Chung1ed747a2011-05-03 16:18:34 -0700141
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)));
Winson Chung785d2eb2011-04-14 16:08:02 -0700147 }
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() {
Winson Chung1ed747a2011-05-03 16:18:34 -0700160 // Get the list of widgets and shortcuts
161 mWidgets.clear();
162 mWidgets.addAll(AppWidgetManager.getInstance(mLauncher).getInstalledProviders());
Winson Chung785d2eb2011-04-14 16:08:02 -0700163 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
Winson Chung1ed747a2011-05-03 16:18:34 -0700164 mWidgets.addAll(mPackageManager.queryIntentActivities(shortcutsIntent, 0));
165 Collections.sort(mWidgets,
166 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
Winson Chung785d2eb2011-04-14 16:08:02 -0700167 }
168
Winson Chung4b576be2011-04-27 17:40:20 -0700169 /**
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;
Winson Chung785d2eb2011-04-14 16:08:02 -0700240 }
241 });
Winson Chung4b576be2011-04-27 17:40:20 -0700242 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 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700303 }
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 }
Winson Chung4b576be2011-04-27 17:40:20 -0700312 private void beginDraggingApplication(View v) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700313 // 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();
Winson Chung4b576be2011-04-27 17:40:20 -0700359 }
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);
Winson Chung1ed747a2011-05-03 16:18:34 -0700363 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700364
365 // Compose the drag image
Winson Chung1ed747a2011-05-03 16:18:34 -0700366 Bitmap b;
Winson Chung4b576be2011-04-27 17:40:20 -0700367 Drawable preview = image.getDrawable();
368 int w = preview.getIntrinsicWidth();
369 int h = preview.getIntrinsicHeight();
Winson Chung1ed747a2011-05-03 16:18:34 -0700370 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 }
Winson Chung4b576be2011-04-27 17:40:20 -0700389
390 // Start the drag
Winson Chung4b576be2011-04-27 17:40:20 -0700391 mLauncher.lockScreenOrientation();
Winson Chung1ed747a2011-05-03 16:18:34 -0700392 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
393 createItemInfo.spanY, b);
394 mDragController.startDrag(image, b, this, createItemInfo,
Winson Chung4b576be2011-04-27 17:40:20 -0700395 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
Winson Chungfc79c802011-05-02 13:35:34 -0700402 // 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
Winson Chung4b576be2011-04-27 17:40:20 -0700406 if (v instanceof PagedViewIcon) {
407 beginDraggingApplication(v);
408 } else if (v instanceof PagedViewWidget) {
409 beginDraggingWidget(v);
410 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700411
Winson Chung785d2eb2011-04-14 16:08:02 -0700412 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);
Winson Chungfc79c802011-05-02 13:35:34 -0700443
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 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700464 }
465
466 public void setContentType(ContentType type) {
467 mContentType = type;
468 setCurrentPage(0);
469 invalidatePageData();
470 }
471
472 /*
473 * Apps PagedView implementation
474 */
Winson Chung63257c12011-05-05 17:06:13 -0700475 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 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700481 private void setupPage(PagedViewCellLayout layout) {
482 layout.setCellCount(mCellCountX, mCellCountY);
483 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
484 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
485 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
486
Winson Chung63257c12011-05-05 17:06:13 -0700487 // 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);
Winson Chung785d2eb2011-04-14 16:08:02 -0700492 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
493 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -0700494 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -0700495 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -0700496 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700497 }
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);
Michael Jurkab9b8ce92011-05-05 15:05:07 -0700520 icon.applyFromApplicationInfo(
521 info, mPageViewIconCache, true, isHardwareAccelerated() && (numPages > 1));
Winson Chung785d2eb2011-04-14 16:08:02 -0700522 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;
Winson Chung63257c12011-05-05 17:06:13 -0700529 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1),
530 isHardwareAccelerated() && (numPages > 1));
Winson Chung785d2eb2011-04-14 16:08:02 -0700531 }
532 }
533 /*
534 * Widgets PagedView implementation
535 */
Winson Chung4e6a9762011-05-09 11:56:34 -0700536 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700537 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
538 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -0700539
540 // Note: We force a measure here to get around the fact that when we do layout calculations
541 // immediately after syncing, we don't have a proper width. That said, we already know the
542 // expected page width, so we can actually optimize by hiding all the TextView-based
543 // children that are expensive to measure, and let that happen naturally later.
544 setVisibilityOnChildren(layout, View.GONE);
545 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
546 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -0700547 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -0700548 layout.measure(widthSpec, heightSpec);
549 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700550 }
551 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
552 float scaleX, float scaleY) {
553 Canvas c = new Canvas();
554 if (bitmap != null) c.setBitmap(bitmap);
555 c.save();
556 c.scale(scaleX, scaleY);
557 Rect oldBounds = d.copyBounds();
558 d.setBounds(x, y, x + w, y + h);
559 d.draw(c);
560 d.setBounds(oldBounds); // Restore the bounds
561 c.restore();
562 }
Winson Chung1ed747a2011-05-03 16:18:34 -0700563 private FastBitmapDrawable getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) {
564 // Return the cached version if necessary
565 Bitmap cachedBitmap = mWidgetPreviewCache.get(info);
566 if (cachedBitmap != null) {
567 return new FastBitmapDrawable(cachedBitmap);
568 }
569
570 Resources resources = mLauncher.getResources();
571 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
572 // We only need to make it wide enough so as not allow the preview to be scaled
573 int expectedWidth = cellWidth;
574 int expectedHeight = mWidgetPreviewIconPaddedDimension;
575 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage);
576
577 // Render the icon
578 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888);
Winson Chung4dbea792011-05-05 14:21:32 -0700579 Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
Winson Chung1ed747a2011-05-03 16:18:34 -0700580 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0,
581 mWidgetPreviewIconPaddedDimension, mWidgetPreviewIconPaddedDimension, 1f, 1f);
582 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f);
583 FastBitmapDrawable iconDrawable = new FastBitmapDrawable(preview);
584 iconDrawable.setBounds(0, 0, expectedWidth, expectedHeight);
585 mWidgetPreviewCache.put(info, preview);
586 return iconDrawable;
587 }
Winson Chung4b576be2011-04-27 17:40:20 -0700588 private FastBitmapDrawable getWidgetPreview(AppWidgetProviderInfo info, int cellHSpan,
589 int cellVSpan, int cellWidth, int cellHeight) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700590 // Return the cached version if necessary
591 Bitmap cachedBitmap = mWidgetPreviewCache.get(info);
592 if (cachedBitmap != null) {
593 return new FastBitmapDrawable(cachedBitmap);
594 }
595
Winson Chung4b576be2011-04-27 17:40:20 -0700596 // Calculate the size of the drawable
597 cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan));
598 cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan));
599 int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
600 int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
601
602 // Scale down the bitmap to fit the space
603 float widgetPreviewScale = (float) cellWidth / expectedWidth;
604 expectedWidth = (int) (widgetPreviewScale * expectedWidth);
605 expectedHeight = (int) (widgetPreviewScale * expectedHeight);
606
607 // Load the preview image if possible
608 String packageName = info.provider.getPackageName();
609 Drawable drawable = null;
610 FastBitmapDrawable newDrawable = null;
611 if (info.previewImage != 0) {
612 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
613 if (drawable == null) {
614 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
615 + " for provider: " + info.provider);
616 } else {
617 // Scale down the preview to the dimensions we want
618 int imageWidth = drawable.getIntrinsicWidth();
619 int imageHeight = drawable.getIntrinsicHeight();
620 float aspect = (float) imageWidth / imageHeight;
621 int newWidth = imageWidth;
622 int newHeight = imageHeight;
623 if (aspect > 1f) {
624 newWidth = expectedWidth;
625 newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth));
626 } else {
627 newHeight = expectedHeight;
628 newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight));
629 }
630
631 Bitmap preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
632 renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f);
633 newDrawable = new FastBitmapDrawable(preview);
634 newDrawable.setBounds(0, 0, newWidth, newHeight);
Winson Chung1ed747a2011-05-03 16:18:34 -0700635 mWidgetPreviewCache.put(info, preview);
Winson Chung4b576be2011-04-27 17:40:20 -0700636 }
637 }
638
639 // Generate a preview image if we couldn't load one
640 if (drawable == null) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700641 Resources resources = mLauncher.getResources();
642 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
643
644 // Specify the dimensions of the bitmap
645 if (info.minWidth >= info.minHeight) {
646 expectedWidth = cellWidth;
647 expectedHeight = mWidgetPreviewIconPaddedDimension;
648 } else {
649 // Note that in vertical widgets, we might not have enough space due to the text
650 // label, so be conservative and use the width as a height bound
651 expectedWidth = mWidgetPreviewIconPaddedDimension;
652 expectedHeight = cellWidth;
653 }
Winson Chung4b576be2011-04-27 17:40:20 -0700654
655 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888);
Winson Chung1ed747a2011-05-03 16:18:34 -0700656 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth,
657 expectedHeight, 1f,1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700658
659 // Draw the icon in the top left corner
660 try {
661 Drawable icon = null;
662 if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
663 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
664
Winson Chung1ed747a2011-05-03 16:18:34 -0700665 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage);
Winson Chung4b576be2011-04-27 17:40:20 -0700666 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f);
667 } catch (Resources.NotFoundException e) {}
668
669 newDrawable = new FastBitmapDrawable(preview);
670 newDrawable.setBounds(0, 0, expectedWidth, expectedHeight);
Winson Chung1ed747a2011-05-03 16:18:34 -0700671 mWidgetPreviewCache.put(info, preview);
Winson Chung4b576be2011-04-27 17:40:20 -0700672 }
673 return newDrawable;
Winson Chung785d2eb2011-04-14 16:08:02 -0700674 }
675 public void syncWidgetPages() {
676 // Ensure that we have the right number of pages
677 Context context = getContext();
Winson Chung4b576be2011-04-27 17:40:20 -0700678 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY;
679 int numPages = (int) Math.ceil(mWidgets.size() / (float) numWidgetsPerPage);
Winson Chung785d2eb2011-04-14 16:08:02 -0700680 for (int i = 0; i < numPages; ++i) {
Winson Chung4e6a9762011-05-09 11:56:34 -0700681 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
682 mWidgetCountY);
Winson Chung785d2eb2011-04-14 16:08:02 -0700683 setupPage(layout);
684 addView(layout);
685 }
686 }
687 public void syncWidgetPageItems(int page) {
Winson Chung4e6a9762011-05-09 11:56:34 -0700688 PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(page);
Winson Chung4b576be2011-04-27 17:40:20 -0700689 layout.removeAllViews();
Winson Chung785d2eb2011-04-14 16:08:02 -0700690
Winson Chung4b576be2011-04-27 17:40:20 -0700691 // Calculate the dimensions of each cell we are giving to each widget
Winson Chung4b576be2011-04-27 17:40:20 -0700692 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY;
693 int offset = page * numWidgetsPerPage;
694 int cellWidth = ((mWidgetSpacingLayout.getContentWidth() - mPageLayoutWidthGap
695 - ((mWidgetCountX - 1) * mWidgetCellWidthGap)) / mWidgetCountX);
696 int cellHeight = ((mWidgetSpacingLayout.getContentHeight() - mPageLayoutHeightGap
697 - ((mWidgetCountY - 1) * mWidgetCellHeightGap)) / mWidgetCountY);
698 for (int i = 0; i < Math.min(numWidgetsPerPage, mWidgets.size() - offset); ++i) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700699 Object rawInfo = mWidgets.get(offset + i);
700 PendingAddItemInfo createItemInfo = null;
Winson Chung4b576be2011-04-27 17:40:20 -0700701 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
702 R.layout.apps_customize_widget, layout, false);
Winson Chung1ed747a2011-05-03 16:18:34 -0700703 if (rawInfo instanceof AppWidgetProviderInfo) {
704 // Fill in the widget information
705 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
706 createItemInfo = new PendingAddWidgetInfo(info, null, null);
707 final int[] cellSpans = CellLayout.rectToCell(getResources(), info.minWidth,
708 info.minHeight, null);
709 FastBitmapDrawable preview = getWidgetPreview(info, cellSpans[0], cellSpans[1],
710 cellWidth, cellHeight);
711 widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans, null, false);
712 widget.setTag(createItemInfo);
713 } else if (rawInfo instanceof ResolveInfo) {
714 // Fill in the shortcuts information
715 ResolveInfo info = (ResolveInfo) rawInfo;
716 createItemInfo = new PendingAddItemInfo();
717 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
718 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
719 info.activityInfo.name);
720 FastBitmapDrawable preview = getShortcutPreview(info, cellWidth, cellHeight);
721 widget.applyFromResolveInfo(mPackageManager, info, preview, null, false);
722 widget.setTag(createItemInfo);
723 }
Winson Chung4b576be2011-04-27 17:40:20 -0700724 widget.setOnClickListener(this);
725 widget.setOnLongClickListener(this);
726 widget.setOnTouchListener(this);
727
728 // Layout each widget
Winson Chung4b576be2011-04-27 17:40:20 -0700729 int ix = i % mWidgetCountX;
730 int iy = i / mWidgetCountX;
Winson Chung4e6a9762011-05-09 11:56:34 -0700731 PagedViewGridLayout.LayoutParams lp = new PagedViewGridLayout.LayoutParams(cellWidth,
732 cellHeight);
Winson Chung4b576be2011-04-27 17:40:20 -0700733 lp.leftMargin = (ix * cellWidth) + (ix * mWidgetCellWidthGap);
734 lp.topMargin = (iy * cellHeight) + (iy * mWidgetCellHeightGap);
Winson Chung4e6a9762011-05-09 11:56:34 -0700735 layout.addView(widget, lp);
Winson Chung785d2eb2011-04-14 16:08:02 -0700736 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700737 }
738 @Override
739 public void syncPages() {
740 removeAllViews();
741 switch (mContentType) {
742 case Applications:
743 syncAppsPages();
744 break;
745 case Widgets:
746 syncWidgetPages();
747 break;
748 }
749 }
750 @Override
751 public void syncPageItems(int page) {
752 switch (mContentType) {
753 case Applications:
754 syncAppsPageItems(page);
755 break;
756 case Widgets:
757 syncWidgetPageItems(page);
758 break;
759 }
760 }
761
762 /**
763 * Used by the parent to get the content width to set the tab bar to
764 * @return
765 */
766 public int getPageContentWidth() {
767 return mContentWidth;
768 }
769
770 /*
771 * AllAppsView implementation
772 */
773 @Override
774 public void setup(Launcher launcher, DragController dragController) {
775 mLauncher = launcher;
776 mDragController = dragController;
777 }
778 @Override
779 public void zoom(float zoom, boolean animate) {
780 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
781 }
782 @Override
783 public boolean isVisible() {
784 return (getVisibility() == VISIBLE);
785 }
786 @Override
787 public boolean isAnimating() {
788 return false;
789 }
790 @Override
791 public void setApps(ArrayList<ApplicationInfo> list) {
792 mApps = list;
793 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
794 invalidatePageData();
795 }
796 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
797 // We add it in place, in alphabetical order
798 int count = list.size();
799 for (int i = 0; i < count; ++i) {
800 ApplicationInfo info = list.get(i);
801 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
802 if (index < 0) {
803 mApps.add(-(index + 1), info);
804 }
805 }
806 }
807 @Override
808 public void addApps(ArrayList<ApplicationInfo> list) {
809 addAppsWithoutInvalidate(list);
810 invalidatePageData();
811 }
812 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
813 ComponentName removeComponent = item.intent.getComponent();
814 int length = list.size();
815 for (int i = 0; i < length; ++i) {
816 ApplicationInfo info = list.get(i);
817 if (info.intent.getComponent().equals(removeComponent)) {
818 return i;
819 }
820 }
821 return -1;
822 }
823 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
824 // loop through all the apps and remove apps that have the same component
825 int length = list.size();
826 for (int i = 0; i < length; ++i) {
827 ApplicationInfo info = list.get(i);
828 int removeIndex = findAppByComponent(mApps, info);
829 if (removeIndex > -1) {
830 mApps.remove(removeIndex);
831 mPageViewIconCache.removeOutline(new PagedViewIconCache.Key(info));
832 }
833 }
834 }
835 @Override
836 public void removeApps(ArrayList<ApplicationInfo> list) {
837 removeAppsWithoutInvalidate(list);
838 invalidatePageData();
839 }
840 @Override
841 public void updateApps(ArrayList<ApplicationInfo> list) {
842 // We remove and re-add the updated applications list because it's properties may have
843 // changed (ie. the title), and this will ensure that the items will be in their proper
844 // place in the list.
845 removeAppsWithoutInvalidate(list);
846 addAppsWithoutInvalidate(list);
847 invalidatePageData();
848 }
849 @Override
850 public void reset() {
Winson Chungfc79c802011-05-02 13:35:34 -0700851 if (mContentType != ContentType.Applications) {
852 // Reset to the first page of the Apps pane
853 AppsCustomizeTabHost tabs = (AppsCustomizeTabHost)
854 mLauncher.findViewById(R.id.apps_customize_pane);
855 tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications));
856 } else {
857 setCurrentPage(0);
858 invalidatePageData();
859 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700860 }
861 @Override
862 public void dumpState() {
863 // TODO: Dump information related to current list of Applications, Widgets, etc.
864 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
865 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
866 }
867 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chung1ed747a2011-05-03 16:18:34 -0700868 List<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700869 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -0700870 for (Object i: list) {
871 if (i instanceof AppWidgetProviderInfo) {
872 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
873 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
874 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
875 + " initialLayout=" + info.initialLayout
876 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
877 } else if (i instanceof ResolveInfo) {
878 ResolveInfo info = (ResolveInfo) i;
879 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
880 + info.icon);
881 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700882 }
883 }
884 @Override
885 public void surrender() {
886 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
887 // should stop this now.
888 }
889}