blob: 1d7b34d689ab098fc4831eefb084d224196c316d [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
Winson Chung55b65502011-05-26 12:03:43 -070019import android.animation.AnimatorSet;
Winson Chung4b576be2011-04-27 17:40:20 -070020import android.animation.ObjectAnimator;
Winson Chungd2e87b32011-06-02 10:53:07 -070021import android.animation.ValueAnimator;
Winson Chung785d2eb2011-04-14 16:08:02 -070022import android.appwidget.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
Winson Chung46af2e82011-05-09 16:00:53 -070027import android.content.pm.ActivityInfo;
Winson Chung785d2eb2011-04-14 16:08:02 -070028import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
Winson Chungf0ea4d32011-06-06 14:27:16 -070030import android.content.res.Configuration;
Winson Chung785d2eb2011-04-14 16:08:02 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.graphics.Bitmap;
Winson Chungf0ea4d32011-06-06 14:27:16 -070034import android.graphics.Bitmap.Config;
Winson Chung785d2eb2011-04-14 16:08:02 -070035import android.graphics.Canvas;
Winson Chungb44b5242011-06-13 11:32:14 -070036import android.graphics.Color;
37import android.graphics.Paint;
38import android.graphics.PorterDuff.Mode;
Winson Chung785d2eb2011-04-14 16:08:02 -070039import android.graphics.Rect;
40import android.graphics.drawable.Drawable;
Winson Chungb44b5242011-06-13 11:32:14 -070041import android.os.AsyncTask;
42import android.os.Process;
Winson Chung785d2eb2011-04-14 16:08:02 -070043import android.util.AttributeSet;
44import android.util.Log;
Winson Chung785d2eb2011-04-14 16:08:02 -070045import android.view.LayoutInflater;
46import android.view.View;
Winson Chung63257c12011-05-05 17:06:13 -070047import android.view.ViewGroup;
Winson Chung55b65502011-05-26 12:03:43 -070048import android.view.animation.AccelerateInterpolator;
Winson Chung785d2eb2011-04-14 16:08:02 -070049import android.widget.ImageView;
50import android.widget.TextView;
Winson Chung55b65502011-05-26 12:03:43 -070051import android.widget.Toast;
Winson Chung785d2eb2011-04-14 16:08:02 -070052
53import com.android.launcher.R;
Adam Cohenc0dcf592011-06-01 15:30:43 -070054import com.android.launcher2.DropTarget.DragObject;
55
56import java.util.ArrayList;
57import java.util.Collections;
58import java.util.Iterator;
59import java.util.List;
Winson Chung785d2eb2011-04-14 16:08:02 -070060
Winson Chungb44b5242011-06-13 11:32:14 -070061/**
62 * A simple callback interface which also provides the results of the task.
63 */
64interface AsyncTaskCallback {
65 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
66}
67/**
68 * The data needed to perform either of the custom AsyncTasks.
69 */
70class AsyncTaskPageData {
71 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
72 AsyncTaskCallback postR) {
73 page = p;
74 items = l;
75 srcImages = si;
76 images = new ArrayList<Bitmap>();
77 cellWidth = cellHeight = -1;
78 doInBackgroundCallback = bgR;
79 postExecuteCallback = postR;
80 }
81 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
82 AsyncTaskCallback postR) {
83 page = p;
84 items = l;
85 images = new ArrayList<Bitmap>();
86 cellWidth = cw;
87 cellHeight = ch;
88 doInBackgroundCallback = bgR;
89 postExecuteCallback = postR;
90 }
91 int page;
92 ArrayList<Object> items;
93 ArrayList<Bitmap> srcImages;
94 ArrayList<Bitmap> images;
95 int cellWidth;
96 int cellHeight;
97 AsyncTaskCallback doInBackgroundCallback;
98 AsyncTaskCallback postExecuteCallback;
99}
100/**
101 * A generic template for an async task used in AppsCustomize.
102 */
103class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
104 AppsCustomizeAsyncTask(int p, AppsCustomizePagedView.ContentType t) {
105 page = p;
106 pageContentType = t;
107 threadPriority = Process.THREAD_PRIORITY_DEFAULT;
108 }
109 @Override
110 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
111 if (params.length != 1) return null;
112 // Load each of the widget previews in the background
113 params[0].doInBackgroundCallback.run(this, params[0]);
114 return params[0];
115 }
116 @Override
117 protected void onPostExecute(AsyncTaskPageData result) {
118 // All the widget previews are loaded, so we can just callback to inflate the page
119 result.postExecuteCallback.run(this, result);
120 }
121
122 void setThreadPriority(int p) {
123 threadPriority = p;
124 }
125 void syncThreadPriority() {
126 Process.setThreadPriority(threadPriority);
127 }
128
129 // The page that this async task is associated with
130 int page;
131 AppsCustomizePagedView.ContentType pageContentType;
132 int threadPriority;
133}
134/**
135 * An AsyncTask that loads widget previews from package manager in the background.
136 */
137class LoadWidgetPreviewsTask extends AppsCustomizeAsyncTask {
138 LoadWidgetPreviewsTask(int p, AppsCustomizePagedView.ContentType t) {
139 super(p, t);
140 }
141}
142/**
143 * An AsyncTask that generates holgoraphic outlines for a specified set of bitmaps.
144 */
145class GenerateHoloOutlinesTask extends AppsCustomizeAsyncTask {
146 GenerateHoloOutlinesTask(int p, AppsCustomizePagedView.ContentType t) {
147 super(p, t);
148 }
149}
150
151/**
152 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
153 */
Winson Chung785d2eb2011-04-14 16:08:02 -0700154public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
155 AllAppsView, View.OnClickListener, DragSource {
156 static final String LOG_TAG = "AppsCustomizePagedView";
157
158 /**
159 * The different content types that this paged view can show.
160 */
161 public enum ContentType {
162 Applications,
Winson Chung6a26e5b2011-05-26 14:36:06 -0700163 Widgets
Winson Chung785d2eb2011-04-14 16:08:02 -0700164 }
165
166 // Refs
167 private Launcher mLauncher;
168 private DragController mDragController;
169 private final LayoutInflater mLayoutInflater;
170 private final PackageManager mPackageManager;
171
172 // Content
173 private ContentType mContentType;
174 private ArrayList<ApplicationInfo> mApps;
Winson Chung1ed747a2011-05-03 16:18:34 -0700175 private List<Object> mWidgets;
176
177 // Caching
Winson Chungb44b5242011-06-13 11:32:14 -0700178 private Canvas mCanvas;
Winson Chung1ed747a2011-05-03 16:18:34 -0700179 private Drawable mDefaultWidgetBackground;
Winson Chung4dbea792011-05-05 14:21:32 -0700180 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -0700181
182 // Dimens
183 private int mContentWidth;
Winson Chung4b576be2011-04-27 17:40:20 -0700184 private int mMaxWidgetSpan, mMinWidgetSpan;
Winson Chungf0ea4d32011-06-06 14:27:16 -0700185 private int mWidgetWidthGap, mWidgetHeightGap;
Winson Chung4b576be2011-04-27 17:40:20 -0700186 private int mWidgetCountX, mWidgetCountY;
Winson Chung1ed747a2011-05-03 16:18:34 -0700187 private final int mWidgetPreviewIconPaddedDimension;
188 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -0700189 private PagedViewCellLayout mWidgetSpacingLayout;
190
Winson Chungb44b5242011-06-13 11:32:14 -0700191 // Previews & outlines
192 ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
193 private HolographicOutlineHelper mHolographicOutlineHelper;
Winson Chung4b576be2011-04-27 17:40:20 -0700194
Winson Chung785d2eb2011-04-14 16:08:02 -0700195 public AppsCustomizePagedView(Context context, AttributeSet attrs) {
196 super(context, attrs);
197 mLayoutInflater = LayoutInflater.from(context);
198 mPackageManager = context.getPackageManager();
199 mContentType = ContentType.Applications;
200 mApps = new ArrayList<ApplicationInfo>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700201 mWidgets = new ArrayList<Object>();
Winson Chung4dbea792011-05-05 14:21:32 -0700202 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
Winson Chungb44b5242011-06-13 11:32:14 -0700203 mHolographicOutlineHelper = new HolographicOutlineHelper();
204 mCanvas = new Canvas();
205 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700206
207 // Save the default widget preview background
208 Resources resources = context.getResources();
209 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview);
Winson Chung785d2eb2011-04-14 16:08:02 -0700210
211 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700212 // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after
Winson Chung785d2eb2011-04-14 16:08:02 -0700213 mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6);
214 mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4);
215 a.recycle();
Winson Chung4b576be2011-04-27 17:40:20 -0700216 a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700217 mWidgetWidthGap =
218 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
219 mWidgetHeightGap =
220 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700221 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
222 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
223 a.recycle();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700224 mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
Winson Chung4b576be2011-04-27 17:40:20 -0700225
226 // The max widget span is the length N, such that NxN is the largest bounds that the widget
227 // preview can be before applying the widget scaling
228 mMinWidgetSpan = 1;
229 mMaxWidgetSpan = 3;
Winson Chung1ed747a2011-05-03 16:18:34 -0700230
231 // The padding on the non-matched dimension for the default widget preview icons
232 // (top + bottom)
233 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
234 mWidgetPreviewIconPaddedDimension =
235 (int) (iconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
Winson Chung785d2eb2011-04-14 16:08:02 -0700236 }
237
238 @Override
239 protected void init() {
240 super.init();
241 mCenterPagesVertically = false;
242
243 Context context = getContext();
244 Resources r = context.getResources();
245 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
246 }
247
Winson Chungf0ea4d32011-06-06 14:27:16 -0700248 @Override
249 protected void onWallpaperTap(android.view.MotionEvent ev) {
250 mLauncher.showWorkspace(true);
251 }
252
253 /**
254 * This differs from isDataReady as this is the test done if isDataReady is not set.
255 */
256 private boolean testDataReady() {
257 return !mApps.isEmpty() && !mWidgets.isEmpty();
258 }
259
260 protected void onDataReady(int width, int height) {
261 // Note that we transpose the counts in portrait so that we get a similar layout
262 boolean isLandscape = getResources().getConfiguration().orientation ==
263 Configuration.ORIENTATION_LANDSCAPE;
264 int maxCellCountX = Integer.MAX_VALUE;
265 int maxCellCountY = Integer.MAX_VALUE;
266 if (LauncherApplication.isScreenLarge()) {
267 maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
268 LauncherModel.getCellCountY());
269 maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
270 LauncherModel.getCellCountX());
271 }
272
273 // Now that the data is ready, we can calculate the content width, the number of cells to
274 // use for each page
275 mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
276 mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
277 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
278 mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
279 mCellCountX = mWidgetSpacingLayout.getCellCountX();
280 mCellCountY = mWidgetSpacingLayout.getCellCountY();
281 mWidgetCountX = Math.max(1, (int) Math.round(mCellCountX / 2f));
282 mWidgetCountY = Math.max(1, (int) Math.round(mCellCountY / 3f));
283 mContentWidth = mWidgetSpacingLayout.getContentWidth();
284
Winson Chungf0ea4d32011-06-06 14:27:16 -0700285 invalidatePageData();
286 }
287
288 @Override
289 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
290 int width = MeasureSpec.getSize(widthMeasureSpec);
291 int height = MeasureSpec.getSize(heightMeasureSpec);
292 if (!isDataReady()) {
293 if (testDataReady()) {
294 setDataIsReady();
295 setMeasuredDimension(width, height);
296 onDataReady(width, height);
297 }
298 }
299
300 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
301 }
302
Winson Chung34efdaf2011-05-24 14:19:56 -0700303 /** Removes and returns the ResolveInfo with the specified ComponentName */
304 private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list,
305 ComponentName cn) {
306 Iterator<ResolveInfo> iter = list.iterator();
307 while (iter.hasNext()) {
308 ResolveInfo rinfo = iter.next();
309 ActivityInfo info = rinfo.activityInfo;
310 ComponentName c = new ComponentName(info.packageName, info.name);
311 if (c.equals(cn)) {
312 iter.remove();
313 return rinfo;
314 }
315 }
316 return null;
317 }
318
Winson Chung785d2eb2011-04-14 16:08:02 -0700319 public void onPackagesUpdated() {
Winson Chung1ed747a2011-05-03 16:18:34 -0700320 // Get the list of widgets and shortcuts
321 mWidgets.clear();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700322 List<AppWidgetProviderInfo> widgets =
323 AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
324 Collections.sort(widgets,
Winson Chung1ed747a2011-05-03 16:18:34 -0700325 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
Winson Chungf0ea4d32011-06-06 14:27:16 -0700326 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
327 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
328 Collections.sort(shortcuts,
329 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
330 mWidgets.addAll(widgets);
331 mWidgets.addAll(shortcuts);
Winson Chung785d2eb2011-04-14 16:08:02 -0700332
Winson Chungf0ea4d32011-06-06 14:27:16 -0700333 // The next layout pass will trigger data-ready if both widgets and apps are set, so request
334 // a layout to do this test and invalidate the page data when ready.
335 if (testDataReady()) requestLayout();
Winson Chung4b576be2011-04-27 17:40:20 -0700336 }
337
338 @Override
339 public void onClick(View v) {
340 if (v instanceof PagedViewIcon) {
341 // Animate some feedback to the click
342 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
343 animateClickFeedback(v, new Runnable() {
344 @Override
345 public void run() {
346 mLauncher.startActivitySafely(appInfo.intent, appInfo);
347 }
348 });
349 } else if (v instanceof PagedViewWidget) {
Winson Chungd2e87b32011-06-02 10:53:07 -0700350 // Let the user know that they have to long press to add a widget
351 Toast.makeText(getContext(), R.string.long_press_widget_to_add,
352 Toast.LENGTH_SHORT).show();
Winson Chung46af2e82011-05-09 16:00:53 -0700353
Winson Chungd2e87b32011-06-02 10:53:07 -0700354 // Create a little animation to show that the widget can move
355 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
356 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
357 AnimatorSet bounce = new AnimatorSet();
358 ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
359 tyuAnim.setDuration(125);
360 ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
361 tydAnim.setDuration(100);
362 bounce.play(tyuAnim).before(tydAnim);
363 bounce.setInterpolator(new AccelerateInterpolator());
364 bounce.start();
Winson Chung4b576be2011-04-27 17:40:20 -0700365 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700366 }
367
368 /*
369 * PagedViewWithDraggableItems implementation
370 */
371 @Override
372 protected void determineDraggingStart(android.view.MotionEvent ev) {
373 // Disable dragging by pulling an app down for now.
374 }
Winson Chung4b576be2011-04-27 17:40:20 -0700375 private void beginDraggingApplication(View v) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700376 // Make a copy of the ApplicationInfo
377 ApplicationInfo appInfo = new ApplicationInfo((ApplicationInfo) v.getTag());
378
Winson Chung785d2eb2011-04-14 16:08:02 -0700379 // Compose the drag image (top compound drawable, index is 1)
380 final TextView tv = (TextView) v;
381 final Drawable icon = tv.getCompoundDrawables()[1];
382 Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
383 Bitmap.Config.ARGB_8888);
Winson Chungb44b5242011-06-13 11:32:14 -0700384 mCanvas.setBitmap(b);
385 mCanvas.save();
386 mCanvas.translate((v.getWidth() - icon.getIntrinsicWidth()) / 2, v.getPaddingTop());
387 icon.draw(mCanvas);
388 mCanvas.restore();
Winson Chung785d2eb2011-04-14 16:08:02 -0700389
390 // Compose the visible rect of the drag image
391 Rect dragRect = null;
392 if (v instanceof TextView) {
393 int iconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
394 int top = v.getPaddingTop();
395 int left = (b.getWidth() - iconSize) / 2;
396 int right = left + iconSize;
397 int bottom = top + iconSize;
398 dragRect = new Rect(left, top, right, bottom);
399 }
400
401 // Start the drag
402 mLauncher.lockScreenOrientation();
403 mLauncher.getWorkspace().onDragStartedWithItemSpans(1, 1, b);
404 mDragController.startDrag(v, b, this, appInfo, DragController.DRAG_ACTION_COPY, dragRect);
405 b.recycle();
Winson Chung4b576be2011-04-27 17:40:20 -0700406 }
407 private void beginDraggingWidget(View v) {
408 // Get the widget preview as the drag representation
409 ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
Winson Chung1ed747a2011-05-03 16:18:34 -0700410 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700411
412 // Compose the drag image
Winson Chung1ed747a2011-05-03 16:18:34 -0700413 Bitmap b;
Winson Chung4b576be2011-04-27 17:40:20 -0700414 Drawable preview = image.getDrawable();
415 int w = preview.getIntrinsicWidth();
416 int h = preview.getIntrinsicHeight();
Winson Chung1ed747a2011-05-03 16:18:34 -0700417 if (createItemInfo instanceof PendingAddWidgetInfo) {
418 PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo;
419 int[] spanXY = CellLayout.rectToCell(getResources(),
420 createWidgetInfo.minWidth, createWidgetInfo.minHeight, null);
421 createItemInfo.spanX = spanXY[0];
422 createItemInfo.spanY = spanXY[1];
423
424 b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
425 renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1);
426 } else {
427 // Workaround for the fact that we don't keep the original ResolveInfo associated with
428 // the shortcut around. To get the icon, we just render the preview image (which has
429 // the shortcut icon) to a new drag bitmap that clips the non-icon space.
430 b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
431 mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
Winson Chungb44b5242011-06-13 11:32:14 -0700432 mCanvas.setBitmap(b);
433 mCanvas.save();
434 preview.draw(mCanvas);
435 mCanvas.restore();
Winson Chung1ed747a2011-05-03 16:18:34 -0700436 createItemInfo.spanX = createItemInfo.spanY = 1;
437 }
Winson Chung4b576be2011-04-27 17:40:20 -0700438
439 // Start the drag
Winson Chung4b576be2011-04-27 17:40:20 -0700440 mLauncher.lockScreenOrientation();
Winson Chung1ed747a2011-05-03 16:18:34 -0700441 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
442 createItemInfo.spanY, b);
443 mDragController.startDrag(image, b, this, createItemInfo,
Winson Chung4b576be2011-04-27 17:40:20 -0700444 DragController.DRAG_ACTION_COPY, null);
445 b.recycle();
446 }
447 @Override
448 protected boolean beginDragging(View v) {
449 if (!super.beginDragging(v)) return false;
450
Winson Chungfc79c802011-05-02 13:35:34 -0700451
Winson Chung4b576be2011-04-27 17:40:20 -0700452 if (v instanceof PagedViewIcon) {
453 beginDraggingApplication(v);
454 } else if (v instanceof PagedViewWidget) {
455 beginDraggingWidget(v);
456 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700457
Winson Chungb26f3d62011-06-02 10:49:29 -0700458 // Go into spring loaded mode
459 int currentPageIndex = mLauncher.getWorkspace().getCurrentPage();
460 CellLayout currentPage = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPageIndex);
461 mLauncher.enterSpringLoadedDragMode(currentPage);
Winson Chung785d2eb2011-04-14 16:08:02 -0700462 return true;
463 }
464 private void endDragging(boolean success) {
465 post(new Runnable() {
466 // Once the drag operation has fully completed, hence the post, we want to disable the
467 // deleteZone and the appInfoButton in all apps, and re-enable the instance which
468 // live in the workspace
469 public void run() {
470 // if onDestroy was called on Launcher, we might have already deleted the
471 // all apps delete zone / info button, so check if they are null
472 DeleteZone allAppsDeleteZone =
473 (DeleteZone) mLauncher.findViewById(R.id.all_apps_delete_zone);
474 ApplicationInfoDropTarget allAppsInfoButton =
475 (ApplicationInfoDropTarget) mLauncher.findViewById(R.id.all_apps_info_target);
476
477 if (allAppsDeleteZone != null) allAppsDeleteZone.setDragAndDropEnabled(false);
478 if (allAppsInfoButton != null) allAppsInfoButton.setDragAndDropEnabled(false);
479 }
480 });
Winson Chungb26f3d62011-06-02 10:49:29 -0700481 mLauncher.exitSpringLoadedDragMode();
Winson Chung785d2eb2011-04-14 16:08:02 -0700482 mLauncher.getWorkspace().onDragStopped(success);
483 mLauncher.unlockScreenOrientation();
Winson Chungb26f3d62011-06-02 10:49:29 -0700484
Winson Chung785d2eb2011-04-14 16:08:02 -0700485 }
486
487 /*
488 * DragSource implementation
489 */
490 @Override
491 public void onDragViewVisible() {}
492 @Override
Adam Cohenc0dcf592011-06-01 15:30:43 -0700493 public void onDropCompleted(View target, DragObject d, boolean success) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700494 endDragging(success);
Winson Chungfc79c802011-05-02 13:35:34 -0700495
496 // Display an error message if the drag failed due to there not being enough space on the
497 // target layout we were dropping on.
498 if (!success) {
499 boolean showOutOfSpaceMessage = false;
500 if (target instanceof Workspace) {
501 int currentScreen = mLauncher.getCurrentWorkspaceScreen();
502 Workspace workspace = (Workspace) target;
503 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
Adam Cohenc0dcf592011-06-01 15:30:43 -0700504 ItemInfo itemInfo = (ItemInfo) d.dragInfo;
Winson Chungfc79c802011-05-02 13:35:34 -0700505 if (layout != null) {
506 layout.calculateSpans(itemInfo);
507 showOutOfSpaceMessage =
508 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
509 }
510 }
511 // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later.
512 if (showOutOfSpaceMessage) {
513 mLauncher.showOutOfSpaceMessage();
514 }
515 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700516 }
517
518 public void setContentType(ContentType type) {
519 mContentType = type;
520 setCurrentPage(0);
521 invalidatePageData();
522 }
523
Winson Chungb44b5242011-06-13 11:32:14 -0700524 public boolean isContentType(ContentType type) {
525 return (mContentType == type);
526 }
527
Winson Chung785d2eb2011-04-14 16:08:02 -0700528 /*
529 * Apps PagedView implementation
530 */
Winson Chung63257c12011-05-05 17:06:13 -0700531 private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
532 int childCount = layout.getChildCount();
533 for (int i = 0; i < childCount; ++i) {
534 layout.getChildAt(i).setVisibility(visibility);
535 }
536 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700537 private void setupPage(PagedViewCellLayout layout) {
538 layout.setCellCount(mCellCountX, mCellCountY);
539 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
540 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
541 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
542
Winson Chung63257c12011-05-05 17:06:13 -0700543 // Note: We force a measure here to get around the fact that when we do layout calculations
544 // immediately after syncing, we don't have a proper width. That said, we already know the
545 // expected page width, so we can actually optimize by hiding all the TextView-based
546 // children that are expensive to measure, and let that happen naturally later.
547 setVisibilityOnChildren(layout, View.GONE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700548 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
549 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -0700550 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -0700551 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -0700552 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700553 }
554 public void syncAppsPages() {
555 // Ensure that we have the right number of pages
556 Context context = getContext();
557 int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
558 for (int i = 0; i < numPages; ++i) {
559 PagedViewCellLayout layout = new PagedViewCellLayout(context);
560 setupPage(layout);
561 addView(layout);
562 }
563 }
564 public void syncAppsPageItems(int page) {
565 // ensure that we have the right number of items on the pages
566 int numPages = getPageCount();
567 int numCells = mCellCountX * mCellCountY;
568 int startIndex = page * numCells;
569 int endIndex = Math.min(startIndex + numCells, mApps.size());
570 PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page);
571 layout.removeAllViewsOnPage();
Winson Chungb44b5242011-06-13 11:32:14 -0700572 ArrayList<Object> items = new ArrayList<Object>();
573 ArrayList<Bitmap> images = new ArrayList<Bitmap>();
Winson Chung785d2eb2011-04-14 16:08:02 -0700574 for (int i = startIndex; i < endIndex; ++i) {
575 ApplicationInfo info = mApps.get(i);
576 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
577 R.layout.apps_customize_application, layout, false);
Winson Chungb44b5242011-06-13 11:32:14 -0700578 icon.applyFromApplicationInfo(info, true, mHolographicOutlineHelper);
Winson Chung785d2eb2011-04-14 16:08:02 -0700579 icon.setOnClickListener(this);
580 icon.setOnLongClickListener(this);
581 icon.setOnTouchListener(this);
582
583 int index = i - startIndex;
584 int x = index % mCellCountX;
585 int y = index / mCellCountX;
Winson Chung6a70e9f2011-05-17 16:24:49 -0700586 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
Winson Chungb44b5242011-06-13 11:32:14 -0700587
588 items.add(info);
589 images.add(info.iconBitmap);
Winson Chung785d2eb2011-04-14 16:08:02 -0700590 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700591
592 // Create the hardware layers
593 layout.allowHardwareLayerCreation();
594 layout.createHardwareLayers();
Winson Chungb44b5242011-06-13 11:32:14 -0700595
596 prepareGenerateHoloOutlinesTask(page, items, images);
Winson Chung785d2eb2011-04-14 16:08:02 -0700597 }
Winson Chungb44b5242011-06-13 11:32:14 -0700598
599 /**
600 * Return the appropriate thread priority for loading for a given page (we give the current
601 * page much higher priority)
602 */
603 private int getThreadPriorityForPage(int page) {
604 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
605 int pageDiff = Math.abs(page - mCurrentPage);
606 if (pageDiff <= 0) {
607 // return Process.THREAD_PRIORITY_DEFAULT;
608 return Process.THREAD_PRIORITY_MORE_FAVORABLE;
609 } else if (pageDiff <= 1) {
610 // return Process.THREAD_PRIORITY_BACKGROUND;
611 return Process.THREAD_PRIORITY_DEFAULT;
612 } else {
613 // return Process.THREAD_PRIORITY_LOWEST;
614 return Process.THREAD_PRIORITY_DEFAULT;
615 }
616 }
617 /**
618 * Creates and executes a new AsyncTask to load a page of widget previews.
619 */
620 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
621 int cellWidth, int cellHeight) {
622 // Prune all tasks that are no longer needed
623 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
624 while (iter.hasNext()) {
625 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
626 int taskPage = task.page;
627 if (taskPage < (mCurrentPage - 2) || taskPage > (mCurrentPage + 2)) {
628 task.cancel(false);
629 iter.remove();
630 } else {
631 task.setThreadPriority(getThreadPriorityForPage(taskPage));
632 }
633 }
634
635 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
636 new AsyncTaskCallback() {
637 @Override
638 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
639 // Ensure that this task starts running at the correct priority
640 task.syncThreadPriority();
641
642 // Load each of the widget/shortcut previews
643 ArrayList<Object> items = data.items;
644 ArrayList<Bitmap> images = data.images;
645 int count = items.size();
646 int cellWidth = data.cellWidth;
647 int cellHeight = data.cellHeight;
648 for (int i = 0; i < count && !task.isCancelled(); ++i) {
649 // Before work on each item, ensure that this task is running at the correct
650 // priority
651 task.syncThreadPriority();
652
653 Object rawInfo = items.get(i);
654 if (rawInfo instanceof AppWidgetProviderInfo) {
655 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
656 int[] cellSpans = CellLayout.rectToCell(getResources(),
657 info.minWidth, info.minHeight, null);
658 images.add(getWidgetPreviewInBackground(info, cellSpans[0],cellSpans[1],
659 cellWidth, cellHeight));
660 } else if (rawInfo instanceof ResolveInfo) {
661 // Fill in the shortcuts information
662 ResolveInfo info = (ResolveInfo) rawInfo;
663 images.add(getShortcutPreviewInBackground(info, cellWidth, cellHeight));
664 }
665 }
666 }
667 },
668 new AsyncTaskCallback() {
669 @Override
670 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
671 mRunningTasks.remove(task);
672 if (task.page > getPageCount()) return;
673 if (task.pageContentType != mContentType) return;
674 onSyncWidgetPageItems(data);
675 }
676 });
677
678 // Ensure that the task is appropriately prioritized and runs in parallel
679 LoadWidgetPreviewsTask t = new LoadWidgetPreviewsTask(page, mContentType);
680 t.setThreadPriority(getThreadPriorityForPage(page));
681 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
682 mRunningTasks.add(t);
683 }
684 /**
685 * Creates and executes a new AsyncTask to load the outlines for a page of content.
686 */
687 private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items,
688 ArrayList<Bitmap> images) {
689 AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images,
690 new AsyncTaskCallback() {
691 @Override
692 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
693 // Ensure that this task starts running at the correct priority
694 task.syncThreadPriority();
695
696 ArrayList<Bitmap> images = data.images;
697 ArrayList<Bitmap> srcImages = data.srcImages;
698 int count = srcImages.size();
699 Canvas c = new Canvas();
700 for (int i = 0; i < count && !task.isCancelled(); ++i) {
701 // Before work on each item, ensure that this task is running at the correct
702 // priority
703 task.syncThreadPriority();
704
705 Bitmap b = srcImages.get(i);
706 Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
707 Bitmap.Config.ARGB_8888);
708
709 c.setBitmap(outline);
710 c.save();
711 c.drawBitmap(b, 0, 0, null);
712 c.restore();
713
714 images.add(outline);
715 }
716 }
717 },
718 new AsyncTaskCallback() {
719 @Override
720 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
721 mRunningTasks.remove(task);
722 if (task.page > getPageCount()) return;
723 if (task.pageContentType != mContentType) return;
724 onHolographicPageItemsLoaded(data);
725 }
726 });
727
728 // Ensure that the outline task always runs in the background, serially
729 GenerateHoloOutlinesTask t =
730 new GenerateHoloOutlinesTask(page, mContentType);
731 t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
732 t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData);
733 mRunningTasks.add(t);
734 }
735
Winson Chung785d2eb2011-04-14 16:08:02 -0700736 /*
737 * Widgets PagedView implementation
738 */
Winson Chung4e6a9762011-05-09 11:56:34 -0700739 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700740 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
741 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -0700742
743 // Note: We force a measure here to get around the fact that when we do layout calculations
744 // immediately after syncing, we don't have a proper width. That said, we already know the
745 // expected page width, so we can actually optimize by hiding all the TextView-based
746 // children that are expensive to measure, and let that happen naturally later.
747 setVisibilityOnChildren(layout, View.GONE);
748 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
749 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -0700750 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -0700751 layout.measure(widthSpec, heightSpec);
752 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700753 }
Winson Chungb44b5242011-06-13 11:32:14 -0700754 private synchronized void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
Winson Chung785d2eb2011-04-14 16:08:02 -0700755 float scaleX, float scaleY) {
Winson Chung201bc822011-06-20 15:41:53 -0700756 if (bitmap != null) {
Winson Chungb44b5242011-06-13 11:32:14 -0700757 Canvas c = new Canvas(bitmap);
Winson Chung201bc822011-06-20 15:41:53 -0700758 c.scale(scaleX, scaleY);
759 Rect oldBounds = d.copyBounds();
760 d.setBounds(x, y, x + w, y + h);
761 d.draw(c);
762 d.setBounds(oldBounds); // Restore the bounds
Winson Chung201bc822011-06-20 15:41:53 -0700763 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700764 }
Winson Chungb44b5242011-06-13 11:32:14 -0700765 private Bitmap getShortcutPreviewInBackground(ResolveInfo info, int cellWidth,
766 int cellHeight) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700767 Resources resources = mLauncher.getResources();
768 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
769 // We only need to make it wide enough so as not allow the preview to be scaled
770 int expectedWidth = cellWidth;
771 int expectedHeight = mWidgetPreviewIconPaddedDimension;
Winson Chung1ed747a2011-05-03 16:18:34 -0700772
773 // Render the icon
774 Bitmap preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888);
Winson Chung4dbea792011-05-05 14:21:32 -0700775 Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700776 renderDrawableToBitmap(icon, preview, 0, 0, iconSize, iconSize, 1f, 1f);
Winson Chungb44b5242011-06-13 11:32:14 -0700777 return preview;
Winson Chung1ed747a2011-05-03 16:18:34 -0700778 }
Winson Chungb44b5242011-06-13 11:32:14 -0700779 private Bitmap getWidgetPreviewInBackground(AppWidgetProviderInfo info,
780 int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700781
Winson Chung4b576be2011-04-27 17:40:20 -0700782 // Calculate the size of the drawable
783 cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan));
784 cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan));
785 int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
786 int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
787
788 // Scale down the bitmap to fit the space
789 float widgetPreviewScale = (float) cellWidth / expectedWidth;
790 expectedWidth = (int) (widgetPreviewScale * expectedWidth);
791 expectedHeight = (int) (widgetPreviewScale * expectedHeight);
792
793 // Load the preview image if possible
794 String packageName = info.provider.getPackageName();
795 Drawable drawable = null;
Winson Chungb44b5242011-06-13 11:32:14 -0700796 Bitmap preview = null;
Winson Chung4b576be2011-04-27 17:40:20 -0700797 if (info.previewImage != 0) {
798 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
799 if (drawable == null) {
800 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
801 + " for provider: " + info.provider);
802 } else {
803 // Scale down the preview to the dimensions we want
804 int imageWidth = drawable.getIntrinsicWidth();
805 int imageHeight = drawable.getIntrinsicHeight();
806 float aspect = (float) imageWidth / imageHeight;
807 int newWidth = imageWidth;
808 int newHeight = imageHeight;
809 if (aspect > 1f) {
810 newWidth = expectedWidth;
811 newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth));
812 } else {
813 newHeight = expectedHeight;
814 newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight));
815 }
816
Winson Chungb44b5242011-06-13 11:32:14 -0700817 preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
Winson Chung4b576be2011-04-27 17:40:20 -0700818 renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700819 }
820 }
821
822 // Generate a preview image if we couldn't load one
823 if (drawable == null) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700824 Resources resources = mLauncher.getResources();
825 int iconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
826
827 // Specify the dimensions of the bitmap
828 if (info.minWidth >= info.minHeight) {
829 expectedWidth = cellWidth;
830 expectedHeight = mWidgetPreviewIconPaddedDimension;
831 } else {
832 // Note that in vertical widgets, we might not have enough space due to the text
833 // label, so be conservative and use the width as a height bound
834 expectedWidth = mWidgetPreviewIconPaddedDimension;
835 expectedHeight = cellWidth;
836 }
Winson Chung4b576be2011-04-27 17:40:20 -0700837
Winson Chungb44b5242011-06-13 11:32:14 -0700838 preview = Bitmap.createBitmap(expectedWidth, expectedHeight, Config.ARGB_8888);
Winson Chung1ed747a2011-05-03 16:18:34 -0700839 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth,
840 expectedHeight, 1f,1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700841
842 // Draw the icon in the top left corner
843 try {
844 Drawable icon = null;
845 if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
846 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
847
Winson Chung1ed747a2011-05-03 16:18:34 -0700848 int offset = (int) (iconSize * sWidgetPreviewIconPaddingPercentage);
Winson Chung4b576be2011-04-27 17:40:20 -0700849 renderDrawableToBitmap(icon, preview, offset, offset, iconSize, iconSize, 1f, 1f);
850 } catch (Resources.NotFoundException e) {}
Winson Chung4b576be2011-04-27 17:40:20 -0700851 }
Winson Chungb44b5242011-06-13 11:32:14 -0700852 return preview;
Winson Chung785d2eb2011-04-14 16:08:02 -0700853 }
854 public void syncWidgetPages() {
855 // Ensure that we have the right number of pages
856 Context context = getContext();
Winson Chung4b576be2011-04-27 17:40:20 -0700857 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY;
858 int numPages = (int) Math.ceil(mWidgets.size() / (float) numWidgetsPerPage);
Winson Chung785d2eb2011-04-14 16:08:02 -0700859 for (int i = 0; i < numPages; ++i) {
Winson Chung4e6a9762011-05-09 11:56:34 -0700860 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
861 mWidgetCountY);
Winson Chung785d2eb2011-04-14 16:08:02 -0700862 setupPage(layout);
863 addView(layout);
864 }
865 }
866 public void syncWidgetPageItems(int page) {
Winson Chungb44b5242011-06-13 11:32:14 -0700867 // Calculate the dimensions of each cell we are giving to each widget
868 ArrayList<Object> widgets = new ArrayList<Object>();
869 int cellWidth = ((mWidgetSpacingLayout.getContentWidth()
870 - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
871 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
872 int cellHeight = ((mWidgetSpacingLayout.getContentHeight()
873 - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
874 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
875
876 int numWidgetsPerPage = mWidgetCountX * mWidgetCountY;
877 int offset = page * numWidgetsPerPage;
878 for (int i = offset; i < Math.min(offset + numWidgetsPerPage, mWidgets.size()); ++i) {
879 widgets.add(mWidgets.get(i));
880 }
881
882 prepareLoadWidgetPreviewsTask(page, widgets, cellWidth, cellHeight);
883 }
884 private void onSyncWidgetPageItems(AsyncTaskPageData data) {
885 int page = data.page;
Winson Chung4e6a9762011-05-09 11:56:34 -0700886 PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(page);
Winson Chung4b576be2011-04-27 17:40:20 -0700887 layout.removeAllViews();
Winson Chung785d2eb2011-04-14 16:08:02 -0700888
Winson Chungb44b5242011-06-13 11:32:14 -0700889 ArrayList<Object> items = data.items;
890 int count = items.size();
891 int cellWidth = data.cellWidth;
892 int cellHeight = data.cellHeight;
893 for (int i = 0; i < count; ++i) {
894 Object rawInfo = items.get(i);
Winson Chung1ed747a2011-05-03 16:18:34 -0700895 PendingAddItemInfo createItemInfo = null;
Winson Chung4b576be2011-04-27 17:40:20 -0700896 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
897 R.layout.apps_customize_widget, layout, false);
Winson Chung1ed747a2011-05-03 16:18:34 -0700898 if (rawInfo instanceof AppWidgetProviderInfo) {
899 // Fill in the widget information
900 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
901 createItemInfo = new PendingAddWidgetInfo(info, null, null);
Winson Chungb44b5242011-06-13 11:32:14 -0700902 int[] cellSpans = CellLayout.rectToCell(getResources(),
903 info.minWidth, info.minHeight, null);
904 FastBitmapDrawable preview = new FastBitmapDrawable(data.images.get(i));
Winson Chung9f4e0fd2011-06-02 18:59:36 -0700905 widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans,
Winson Chungb44b5242011-06-13 11:32:14 -0700906 mHolographicOutlineHelper);
Winson Chung1ed747a2011-05-03 16:18:34 -0700907 widget.setTag(createItemInfo);
908 } else if (rawInfo instanceof ResolveInfo) {
909 // Fill in the shortcuts information
910 ResolveInfo info = (ResolveInfo) rawInfo;
911 createItemInfo = new PendingAddItemInfo();
912 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
913 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
914 info.activityInfo.name);
Winson Chungb44b5242011-06-13 11:32:14 -0700915 FastBitmapDrawable preview = new FastBitmapDrawable(data.images.get(i));
916 widget.applyFromResolveInfo(mPackageManager, info, preview,
917 mHolographicOutlineHelper);
Winson Chung1ed747a2011-05-03 16:18:34 -0700918 widget.setTag(createItemInfo);
919 }
Winson Chung4b576be2011-04-27 17:40:20 -0700920 widget.setOnClickListener(this);
921 widget.setOnLongClickListener(this);
922 widget.setOnTouchListener(this);
923
924 // Layout each widget
Winson Chung4b576be2011-04-27 17:40:20 -0700925 int ix = i % mWidgetCountX;
926 int iy = i / mWidgetCountX;
Winson Chung4e6a9762011-05-09 11:56:34 -0700927 PagedViewGridLayout.LayoutParams lp = new PagedViewGridLayout.LayoutParams(cellWidth,
928 cellHeight);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700929 lp.leftMargin = (ix * cellWidth) + (ix * mWidgetWidthGap);
930 lp.topMargin = (iy * cellHeight) + (iy * mWidgetHeightGap);
Winson Chung4e6a9762011-05-09 11:56:34 -0700931 layout.addView(widget, lp);
Winson Chung785d2eb2011-04-14 16:08:02 -0700932 }
Winson Chungb44b5242011-06-13 11:32:14 -0700933
934 invalidate();
935 forceUpdateAdjacentPagesAlpha();
936 prepareGenerateHoloOutlinesTask(data.page, data.items, data.images);
937 }
938 private void onHolographicPageItemsLoaded(AsyncTaskPageData data) {
939 // Invalidate early to short-circuit children invalidates
940 invalidate();
941
942 int page = data.page;
943 ViewGroup layout = (ViewGroup) getChildAt(page);
944 if (layout instanceof PagedViewCellLayout) {
945 PagedViewCellLayout cl = (PagedViewCellLayout) layout;
946 int count = cl.getPageChildCount();
947 for (int i = 0; i < count; ++i) {
948 PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i);
949 icon.setHolographicOutline(data.images.get(i));
950 }
951 } else {
952 int count = layout.getChildCount();
953 for (int i = 0; i < count; ++i) {
954 View v = layout.getChildAt(i);
955 ((PagedViewWidget) v).setHolographicOutline(data.images.get(i));
956 }
957 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700958 }
Winson Chung46af2e82011-05-09 16:00:53 -0700959
Winson Chung785d2eb2011-04-14 16:08:02 -0700960 @Override
961 public void syncPages() {
962 removeAllViews();
963 switch (mContentType) {
964 case Applications:
965 syncAppsPages();
966 break;
967 case Widgets:
968 syncWidgetPages();
969 break;
970 }
971 }
972 @Override
973 public void syncPageItems(int page) {
974 switch (mContentType) {
975 case Applications:
976 syncAppsPageItems(page);
977 break;
978 case Widgets:
979 syncWidgetPageItems(page);
980 break;
981 }
982 }
983
984 /**
985 * Used by the parent to get the content width to set the tab bar to
986 * @return
987 */
988 public int getPageContentWidth() {
989 return mContentWidth;
990 }
991
Winson Chungb26f3d62011-06-02 10:49:29 -0700992 @Override
993 protected void onPageBeginMoving() {
994 /* TO BE ENABLED LATER
995 setChildrenDrawnWithCacheEnabled(true);
996 for (int i = 0; i < getChildCount(); ++i) {
997 View v = getChildAt(i);
998 if (v instanceof PagedViewCellLayout) {
999 ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(true);
1000 }
1001 }
1002 */
1003 super.onPageBeginMoving();
1004 }
1005
1006 @Override
1007 protected void onPageEndMoving() {
1008 /* TO BE ENABLED LATER
1009 for (int i = 0; i < getChildCount(); ++i) {
1010 View v = getChildAt(i);
1011 if (v instanceof PagedViewCellLayout) {
1012 ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(false);
1013 }
1014 }
1015 setChildrenDrawnWithCacheEnabled(false);
1016 */
1017 super.onPageEndMoving();
1018 }
1019
Winson Chung785d2eb2011-04-14 16:08:02 -07001020 /*
1021 * AllAppsView implementation
1022 */
1023 @Override
1024 public void setup(Launcher launcher, DragController dragController) {
1025 mLauncher = launcher;
1026 mDragController = dragController;
1027 }
1028 @Override
1029 public void zoom(float zoom, boolean animate) {
1030 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1031 }
1032 @Override
1033 public boolean isVisible() {
1034 return (getVisibility() == VISIBLE);
1035 }
1036 @Override
1037 public boolean isAnimating() {
1038 return false;
1039 }
1040 @Override
1041 public void setApps(ArrayList<ApplicationInfo> list) {
1042 mApps = list;
1043 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
Winson Chungf0ea4d32011-06-06 14:27:16 -07001044
1045 // The next layout pass will trigger data-ready if both widgets and apps are set, so request
1046 // a layout to do this test and invalidate the page data when ready.
1047 if (testDataReady()) requestLayout();
Winson Chung785d2eb2011-04-14 16:08:02 -07001048 }
1049 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1050 // We add it in place, in alphabetical order
1051 int count = list.size();
1052 for (int i = 0; i < count; ++i) {
1053 ApplicationInfo info = list.get(i);
1054 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1055 if (index < 0) {
1056 mApps.add(-(index + 1), info);
1057 }
1058 }
1059 }
1060 @Override
1061 public void addApps(ArrayList<ApplicationInfo> list) {
1062 addAppsWithoutInvalidate(list);
1063 invalidatePageData();
1064 }
1065 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1066 ComponentName removeComponent = item.intent.getComponent();
1067 int length = list.size();
1068 for (int i = 0; i < length; ++i) {
1069 ApplicationInfo info = list.get(i);
1070 if (info.intent.getComponent().equals(removeComponent)) {
1071 return i;
1072 }
1073 }
1074 return -1;
1075 }
1076 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1077 // loop through all the apps and remove apps that have the same component
1078 int length = list.size();
1079 for (int i = 0; i < length; ++i) {
1080 ApplicationInfo info = list.get(i);
1081 int removeIndex = findAppByComponent(mApps, info);
1082 if (removeIndex > -1) {
1083 mApps.remove(removeIndex);
Winson Chung785d2eb2011-04-14 16:08:02 -07001084 }
1085 }
1086 }
1087 @Override
1088 public void removeApps(ArrayList<ApplicationInfo> list) {
1089 removeAppsWithoutInvalidate(list);
1090 invalidatePageData();
1091 }
1092 @Override
1093 public void updateApps(ArrayList<ApplicationInfo> list) {
1094 // We remove and re-add the updated applications list because it's properties may have
1095 // changed (ie. the title), and this will ensure that the items will be in their proper
1096 // place in the list.
1097 removeAppsWithoutInvalidate(list);
1098 addAppsWithoutInvalidate(list);
1099 invalidatePageData();
1100 }
1101 @Override
1102 public void reset() {
Winson Chungfc79c802011-05-02 13:35:34 -07001103 if (mContentType != ContentType.Applications) {
1104 // Reset to the first page of the Apps pane
1105 AppsCustomizeTabHost tabs = (AppsCustomizeTabHost)
1106 mLauncher.findViewById(R.id.apps_customize_pane);
1107 tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications));
1108 } else {
1109 setCurrentPage(0);
1110 invalidatePageData();
1111 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001112 }
1113 @Override
1114 public void dumpState() {
1115 // TODO: Dump information related to current list of Applications, Widgets, etc.
1116 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
1117 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
1118 }
1119 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chung1ed747a2011-05-03 16:18:34 -07001120 List<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001121 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -07001122 for (Object i: list) {
1123 if (i instanceof AppWidgetProviderInfo) {
1124 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1125 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
1126 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1127 + " initialLayout=" + info.initialLayout
1128 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1129 } else if (i instanceof ResolveInfo) {
1130 ResolveInfo info = (ResolveInfo) i;
1131 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1132 + info.icon);
1133 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001134 }
1135 }
1136 @Override
1137 public void surrender() {
1138 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1139 // should stop this now.
1140 }
Winson Chung007c6982011-06-14 13:27:53 -07001141
1142 @Override
1143 protected int getPageWidthForScrollingIndicator() {
1144 return getPageContentWidth();
1145 }
Winson Chungb44b5242011-06-13 11:32:14 -07001146
1147 /*
1148 * We load an extra page on each side to prevent flashes from scrolling and loading of the
1149 * widget previews in the background with the AsyncTasks.
1150 */
1151 protected int getAssociatedLowerPageBound(int page) {
1152 return Math.max(0, page - 2);
1153 }
1154 protected int getAssociatedUpperPageBound(int page) {
1155 final int count = getChildCount();
1156 return Math.min(page + 2, count - 1);
1157 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001158}