blob: 12fe9714cc27cc651e85a06dafc6a56d8afd013e [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;
36import android.graphics.Rect;
37import android.graphics.drawable.Drawable;
Winson Chungb44b5242011-06-13 11:32:14 -070038import android.os.AsyncTask;
39import android.os.Process;
Winson Chung785d2eb2011-04-14 16:08:02 -070040import android.util.AttributeSet;
41import android.util.Log;
Winson Chung785d2eb2011-04-14 16:08:02 -070042import android.view.LayoutInflater;
43import android.view.View;
Winson Chung63257c12011-05-05 17:06:13 -070044import android.view.ViewGroup;
Winson Chung55b65502011-05-26 12:03:43 -070045import android.view.animation.AccelerateInterpolator;
Winson Chungfd3385f2011-06-15 19:51:24 -070046import android.widget.GridLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070047import android.widget.ImageView;
48import android.widget.TextView;
Winson Chung55b65502011-05-26 12:03:43 -070049import android.widget.Toast;
Winson Chung785d2eb2011-04-14 16:08:02 -070050
51import com.android.launcher.R;
Adam Cohenc0dcf592011-06-01 15:30:43 -070052import com.android.launcher2.DropTarget.DragObject;
53
54import java.util.ArrayList;
55import java.util.Collections;
56import java.util.Iterator;
57import java.util.List;
Winson Chung785d2eb2011-04-14 16:08:02 -070058
Winson Chungb44b5242011-06-13 11:32:14 -070059/**
60 * A simple callback interface which also provides the results of the task.
61 */
62interface AsyncTaskCallback {
63 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
64}
Winson Chung4e076542011-06-23 13:04:10 -070065
Winson Chungb44b5242011-06-13 11:32:14 -070066/**
67 * The data needed to perform either of the custom AsyncTasks.
68 */
69class AsyncTaskPageData {
Winson Chung875de7e2011-06-28 14:25:17 -070070 enum Type {
71 LoadWidgetPreviewData,
72 LoadHolographicIconsData
73 }
74
Winson Chungb44b5242011-06-13 11:32:14 -070075 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
76 AsyncTaskCallback postR) {
77 page = p;
78 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070079 sourceImages = si;
80 generatedImages = new ArrayList<Bitmap>();
Winson Chungb44b5242011-06-13 11:32:14 -070081 cellWidth = cellHeight = -1;
82 doInBackgroundCallback = bgR;
83 postExecuteCallback = postR;
84 }
Winson Chungd2945262011-06-24 15:22:14 -070085 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, int ccx, AsyncTaskCallback bgR,
Winson Chungb44b5242011-06-13 11:32:14 -070086 AsyncTaskCallback postR) {
87 page = p;
88 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070089 generatedImages = new ArrayList<Bitmap>();
Winson Chungb44b5242011-06-13 11:32:14 -070090 cellWidth = cw;
91 cellHeight = ch;
Winson Chungd2945262011-06-24 15:22:14 -070092 cellCountX = ccx;
Winson Chungb44b5242011-06-13 11:32:14 -070093 doInBackgroundCallback = bgR;
94 postExecuteCallback = postR;
95 }
96 int page;
97 ArrayList<Object> items;
Winson Chung4e076542011-06-23 13:04:10 -070098 ArrayList<Bitmap> sourceImages;
99 ArrayList<Bitmap> generatedImages;
Winson Chungb44b5242011-06-13 11:32:14 -0700100 int cellWidth;
101 int cellHeight;
Winson Chungd2945262011-06-24 15:22:14 -0700102 int cellCountX;
Winson Chungb44b5242011-06-13 11:32:14 -0700103 AsyncTaskCallback doInBackgroundCallback;
104 AsyncTaskCallback postExecuteCallback;
105}
Winson Chung4e076542011-06-23 13:04:10 -0700106
Winson Chungb44b5242011-06-13 11:32:14 -0700107/**
108 * A generic template for an async task used in AppsCustomize.
109 */
110class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
Winson Chung875de7e2011-06-28 14:25:17 -0700111 AppsCustomizeAsyncTask(int p, AppsCustomizePagedView.ContentType t, AsyncTaskPageData.Type ty) {
Winson Chungb44b5242011-06-13 11:32:14 -0700112 page = p;
113 pageContentType = t;
114 threadPriority = Process.THREAD_PRIORITY_DEFAULT;
Winson Chung875de7e2011-06-28 14:25:17 -0700115 dataType = ty;
Winson Chungb44b5242011-06-13 11:32:14 -0700116 }
117 @Override
118 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
119 if (params.length != 1) return null;
120 // Load each of the widget previews in the background
121 params[0].doInBackgroundCallback.run(this, params[0]);
122 return params[0];
123 }
124 @Override
125 protected void onPostExecute(AsyncTaskPageData result) {
126 // All the widget previews are loaded, so we can just callback to inflate the page
127 result.postExecuteCallback.run(this, result);
128 }
129
130 void setThreadPriority(int p) {
131 threadPriority = p;
132 }
133 void syncThreadPriority() {
134 Process.setThreadPriority(threadPriority);
135 }
136
137 // The page that this async task is associated with
Winson Chung875de7e2011-06-28 14:25:17 -0700138 AsyncTaskPageData.Type dataType;
Winson Chungb44b5242011-06-13 11:32:14 -0700139 int page;
140 AppsCustomizePagedView.ContentType pageContentType;
141 int threadPriority;
142}
Winson Chungb44b5242011-06-13 11:32:14 -0700143
144/**
145 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
146 */
Winson Chung785d2eb2011-04-14 16:08:02 -0700147public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
148 AllAppsView, View.OnClickListener, DragSource {
149 static final String LOG_TAG = "AppsCustomizePagedView";
150
151 /**
152 * The different content types that this paged view can show.
153 */
154 public enum ContentType {
155 Applications,
Winson Chung6a26e5b2011-05-26 14:36:06 -0700156 Widgets
Winson Chung785d2eb2011-04-14 16:08:02 -0700157 }
158
159 // Refs
160 private Launcher mLauncher;
161 private DragController mDragController;
162 private final LayoutInflater mLayoutInflater;
163 private final PackageManager mPackageManager;
164
165 // Content
166 private ContentType mContentType;
167 private ArrayList<ApplicationInfo> mApps;
Winson Chungd2945262011-06-24 15:22:14 -0700168 private ArrayList<Object> mWidgets;
169 private ArrayList<Object> mShortcuts;
Winson Chung1ed747a2011-05-03 16:18:34 -0700170
171 // Caching
Winson Chungb44b5242011-06-13 11:32:14 -0700172 private Canvas mCanvas;
Winson Chung1ed747a2011-05-03 16:18:34 -0700173 private Drawable mDefaultWidgetBackground;
Winson Chung4dbea792011-05-05 14:21:32 -0700174 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -0700175
176 // Dimens
177 private int mContentWidth;
Winson Chungd2945262011-06-24 15:22:14 -0700178 private int mAppIconSize;
Winson Chung4b576be2011-04-27 17:40:20 -0700179 private int mMaxWidgetSpan, mMinWidgetSpan;
Winson Chung4b576be2011-04-27 17:40:20 -0700180 private int mWidgetCountX, mWidgetCountY;
Winson Chungd2945262011-06-24 15:22:14 -0700181 private int mWidgetWidthGap, mWidgetHeightGap;
182 private int mShortcutCountX, mShortcutCountY;
183 private int mShortcutWidthGap, mShortcutHeightGap;
Winson Chung1ed747a2011-05-03 16:18:34 -0700184 private final int mWidgetPreviewIconPaddedDimension;
185 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -0700186 private PagedViewCellLayout mWidgetSpacingLayout;
187
Winson Chungb44b5242011-06-13 11:32:14 -0700188 // Previews & outlines
189 ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
190 private HolographicOutlineHelper mHolographicOutlineHelper;
Winson Chung4b576be2011-04-27 17:40:20 -0700191
Winson Chung785d2eb2011-04-14 16:08:02 -0700192 public AppsCustomizePagedView(Context context, AttributeSet attrs) {
193 super(context, attrs);
194 mLayoutInflater = LayoutInflater.from(context);
195 mPackageManager = context.getPackageManager();
196 mContentType = ContentType.Applications;
197 mApps = new ArrayList<ApplicationInfo>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700198 mWidgets = new ArrayList<Object>();
Winson Chungd2945262011-06-24 15:22:14 -0700199 mShortcuts = new ArrayList<Object>();
Winson Chung4dbea792011-05-05 14:21:32 -0700200 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
Winson Chungb44b5242011-06-13 11:32:14 -0700201 mHolographicOutlineHelper = new HolographicOutlineHelper();
202 mCanvas = new Canvas();
203 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700204
205 // Save the default widget preview background
206 Resources resources = context.getResources();
Winson Chung967289b2011-06-30 18:09:30 -0700207 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
Winson Chungd2945262011-06-24 15:22:14 -0700208 mAppIconSize = getResources().getDimensionPixelSize(R.dimen.app_icon_size);
Winson Chung785d2eb2011-04-14 16:08:02 -0700209
210 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, 0, 0);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700211 // TODO-APPS_CUSTOMIZE: remove these unnecessary attrs after
Winson Chung785d2eb2011-04-14 16:08:02 -0700212 mCellCountX = a.getInt(R.styleable.PagedView_cellCountX, 6);
213 mCellCountY = a.getInt(R.styleable.PagedView_cellCountY, 4);
214 a.recycle();
Winson Chung4b576be2011-04-27 17:40:20 -0700215 a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700216 mWidgetWidthGap =
217 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
218 mWidgetHeightGap =
219 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700220 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
221 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
222 a.recycle();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700223 mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
Winson Chung4b576be2011-04-27 17:40:20 -0700224
225 // The max widget span is the length N, such that NxN is the largest bounds that the widget
226 // preview can be before applying the widget scaling
227 mMinWidgetSpan = 1;
228 mMaxWidgetSpan = 3;
Winson Chung1ed747a2011-05-03 16:18:34 -0700229
230 // The padding on the non-matched dimension for the default widget preview icons
231 // (top + bottom)
Winson Chung1ed747a2011-05-03 16:18:34 -0700232 mWidgetPreviewIconPaddedDimension =
Winson Chungd2945262011-06-24 15:22:14 -0700233 (int) (mAppIconSize * (1 + (2 * sWidgetPreviewIconPaddingPercentage)));
Winson Chung785d2eb2011-04-14 16:08:02 -0700234 }
235
236 @Override
237 protected void init() {
238 super.init();
239 mCenterPagesVertically = false;
240
241 Context context = getContext();
242 Resources r = context.getResources();
243 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
244 }
245
Winson Chungf0ea4d32011-06-06 14:27:16 -0700246 @Override
247 protected void onWallpaperTap(android.view.MotionEvent ev) {
248 mLauncher.showWorkspace(true);
249 }
250
251 /**
252 * This differs from isDataReady as this is the test done if isDataReady is not set.
253 */
254 private boolean testDataReady() {
Winson Chungfd3385f2011-06-15 19:51:24 -0700255 // We only do this test once, and we default to the Applications page, so we only really
256 // have to wait for there to be apps.
257 return !mApps.isEmpty();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700258 }
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));
Winson Chungd2945262011-06-24 15:22:14 -0700283 mShortcutCountX = Math.max(1, (int) Math.round(mCellCountX / 2f));
284 mShortcutCountY = Math.max(1, (int) Math.round(mCellCountY / 2f));
285
Winson Chungdb1138b2011-06-30 14:39:35 -0700286 // Force a measure to update recalculate the gaps
287 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
288 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
289 mWidgetSpacingLayout.measure(widthSpec, heightSpec);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700290 mContentWidth = mWidgetSpacingLayout.getContentWidth();
291
Winson Chungf0ea4d32011-06-06 14:27:16 -0700292 invalidatePageData();
293 }
294
295 @Override
296 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
297 int width = MeasureSpec.getSize(widthMeasureSpec);
298 int height = MeasureSpec.getSize(heightMeasureSpec);
299 if (!isDataReady()) {
300 if (testDataReady()) {
301 setDataIsReady();
302 setMeasuredDimension(width, height);
303 onDataReady(width, height);
304 }
305 }
306
307 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
308 }
309
Winson Chung34efdaf2011-05-24 14:19:56 -0700310 /** Removes and returns the ResolveInfo with the specified ComponentName */
311 private ResolveInfo removeResolveInfoWithComponentName(List<ResolveInfo> list,
312 ComponentName cn) {
313 Iterator<ResolveInfo> iter = list.iterator();
314 while (iter.hasNext()) {
315 ResolveInfo rinfo = iter.next();
316 ActivityInfo info = rinfo.activityInfo;
317 ComponentName c = new ComponentName(info.packageName, info.name);
318 if (c.equals(cn)) {
319 iter.remove();
320 return rinfo;
321 }
322 }
323 return null;
324 }
325
Winson Chung785d2eb2011-04-14 16:08:02 -0700326 public void onPackagesUpdated() {
Winson Chung1ed747a2011-05-03 16:18:34 -0700327 // Get the list of widgets and shortcuts
Winson Chung875de7e2011-06-28 14:25:17 -0700328 boolean wasEmpty = mWidgets.isEmpty() && mShortcuts.isEmpty();
Winson Chung1ed747a2011-05-03 16:18:34 -0700329 mWidgets.clear();
Winson Chungd2945262011-06-24 15:22:14 -0700330 mShortcuts.clear();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700331 List<AppWidgetProviderInfo> widgets =
332 AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
333 Collections.sort(widgets,
Winson Chung1ed747a2011-05-03 16:18:34 -0700334 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
Winson Chungf0ea4d32011-06-06 14:27:16 -0700335 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
336 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
337 Collections.sort(shortcuts,
338 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
339 mWidgets.addAll(widgets);
Winson Chungd2945262011-06-24 15:22:14 -0700340 mShortcuts.addAll(shortcuts);
Winson Chung785d2eb2011-04-14 16:08:02 -0700341
Winson Chung875de7e2011-06-28 14:25:17 -0700342 if (wasEmpty) {
343 // The next layout pass will trigger data-ready if both widgets and apps are set, so request
344 // a layout to do this test and invalidate the page data when ready.
345 if (testDataReady()) requestLayout();
346 } else {
347 invalidatePageData();
348 }
Winson Chung4b576be2011-04-27 17:40:20 -0700349 }
350
351 @Override
352 public void onClick(View v) {
353 if (v instanceof PagedViewIcon) {
354 // Animate some feedback to the click
355 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
356 animateClickFeedback(v, new Runnable() {
357 @Override
358 public void run() {
359 mLauncher.startActivitySafely(appInfo.intent, appInfo);
360 }
361 });
362 } else if (v instanceof PagedViewWidget) {
Winson Chungd2e87b32011-06-02 10:53:07 -0700363 // Let the user know that they have to long press to add a widget
364 Toast.makeText(getContext(), R.string.long_press_widget_to_add,
365 Toast.LENGTH_SHORT).show();
Winson Chung46af2e82011-05-09 16:00:53 -0700366
Winson Chungd2e87b32011-06-02 10:53:07 -0700367 // Create a little animation to show that the widget can move
368 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
369 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
370 AnimatorSet bounce = new AnimatorSet();
371 ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
372 tyuAnim.setDuration(125);
373 ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
374 tydAnim.setDuration(100);
375 bounce.play(tyuAnim).before(tydAnim);
376 bounce.setInterpolator(new AccelerateInterpolator());
377 bounce.start();
Winson Chung4b576be2011-04-27 17:40:20 -0700378 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700379 }
380
381 /*
382 * PagedViewWithDraggableItems implementation
383 */
384 @Override
385 protected void determineDraggingStart(android.view.MotionEvent ev) {
386 // Disable dragging by pulling an app down for now.
387 }
Winson Chung4b576be2011-04-27 17:40:20 -0700388 private void beginDraggingApplication(View v) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700389 // Make a copy of the ApplicationInfo
390 ApplicationInfo appInfo = new ApplicationInfo((ApplicationInfo) v.getTag());
391
Winson Chung785d2eb2011-04-14 16:08:02 -0700392 // Compose the drag image (top compound drawable, index is 1)
393 final TextView tv = (TextView) v;
394 final Drawable icon = tv.getCompoundDrawables()[1];
395 Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
396 Bitmap.Config.ARGB_8888);
Winson Chungb44b5242011-06-13 11:32:14 -0700397 mCanvas.setBitmap(b);
398 mCanvas.save();
399 mCanvas.translate((v.getWidth() - icon.getIntrinsicWidth()) / 2, v.getPaddingTop());
400 icon.draw(mCanvas);
401 mCanvas.restore();
Winson Chung785d2eb2011-04-14 16:08:02 -0700402
403 // Compose the visible rect of the drag image
404 Rect dragRect = null;
405 if (v instanceof TextView) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700406 int top = v.getPaddingTop();
Winson Chungd2945262011-06-24 15:22:14 -0700407 int left = (b.getWidth() - mAppIconSize) / 2;
408 int right = left + mAppIconSize;
409 int bottom = top + mAppIconSize;
Winson Chung785d2eb2011-04-14 16:08:02 -0700410 dragRect = new Rect(left, top, right, bottom);
411 }
412
413 // Start the drag
414 mLauncher.lockScreenOrientation();
415 mLauncher.getWorkspace().onDragStartedWithItemSpans(1, 1, b);
416 mDragController.startDrag(v, b, this, appInfo, DragController.DRAG_ACTION_COPY, dragRect);
417 b.recycle();
Winson Chung4b576be2011-04-27 17:40:20 -0700418 }
419 private void beginDraggingWidget(View v) {
420 // Get the widget preview as the drag representation
421 ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
Winson Chung1ed747a2011-05-03 16:18:34 -0700422 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700423
424 // Compose the drag image
Winson Chung1ed747a2011-05-03 16:18:34 -0700425 Bitmap b;
Winson Chung4b576be2011-04-27 17:40:20 -0700426 Drawable preview = image.getDrawable();
427 int w = preview.getIntrinsicWidth();
428 int h = preview.getIntrinsicHeight();
Winson Chung1ed747a2011-05-03 16:18:34 -0700429 if (createItemInfo instanceof PendingAddWidgetInfo) {
430 PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo;
431 int[] spanXY = CellLayout.rectToCell(getResources(),
432 createWidgetInfo.minWidth, createWidgetInfo.minHeight, null);
433 createItemInfo.spanX = spanXY[0];
434 createItemInfo.spanY = spanXY[1];
435
436 b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
437 renderDrawableToBitmap(preview, b, 0, 0, w, h, 1, 1);
438 } else {
439 // Workaround for the fact that we don't keep the original ResolveInfo associated with
440 // the shortcut around. To get the icon, we just render the preview image (which has
441 // the shortcut icon) to a new drag bitmap that clips the non-icon space.
442 b = Bitmap.createBitmap(mWidgetPreviewIconPaddedDimension,
443 mWidgetPreviewIconPaddedDimension, Bitmap.Config.ARGB_8888);
Winson Chungb44b5242011-06-13 11:32:14 -0700444 mCanvas.setBitmap(b);
445 mCanvas.save();
446 preview.draw(mCanvas);
447 mCanvas.restore();
Winson Chung1ed747a2011-05-03 16:18:34 -0700448 createItemInfo.spanX = createItemInfo.spanY = 1;
449 }
Winson Chung4b576be2011-04-27 17:40:20 -0700450
451 // Start the drag
Winson Chung4b576be2011-04-27 17:40:20 -0700452 mLauncher.lockScreenOrientation();
Winson Chung1ed747a2011-05-03 16:18:34 -0700453 mLauncher.getWorkspace().onDragStartedWithItemSpans(createItemInfo.spanX,
454 createItemInfo.spanY, b);
455 mDragController.startDrag(image, b, this, createItemInfo,
Winson Chung4b576be2011-04-27 17:40:20 -0700456 DragController.DRAG_ACTION_COPY, null);
457 b.recycle();
458 }
459 @Override
460 protected boolean beginDragging(View v) {
461 if (!super.beginDragging(v)) return false;
462
Winson Chungc07918d2011-07-01 15:35:26 -0700463 // Go into spring loaded mode (must happen before we startDrag())
464 int currentPageIndex = mLauncher.getWorkspace().getCurrentPage();
465 CellLayout currentPage = (CellLayout) mLauncher.getWorkspace().getChildAt(currentPageIndex);
466 mLauncher.enterSpringLoadedDragMode(currentPage);
Winson Chungfc79c802011-05-02 13:35:34 -0700467
Winson Chung4b576be2011-04-27 17:40:20 -0700468 if (v instanceof PagedViewIcon) {
469 beginDraggingApplication(v);
470 } else if (v instanceof PagedViewWidget) {
471 beginDraggingWidget(v);
472 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700473 return true;
474 }
Winson Chung557d6ed2011-07-08 15:34:52 -0700475 private void endDragging(View target, boolean success) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700476 mLauncher.getWorkspace().onDragStopped(success);
Winson Chung557d6ed2011-07-08 15:34:52 -0700477 if (!success || target != mLauncher.getWorkspace()) {
478 // Exit spring loaded mode if we have not successfully dropped or have not handled the
479 // drop in Workspace
480 mLauncher.exitSpringLoadedDragMode();
481 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700482 mLauncher.unlockScreenOrientation();
Winson Chungb26f3d62011-06-02 10:49:29 -0700483
Winson Chung785d2eb2011-04-14 16:08:02 -0700484 }
485
486 /*
487 * DragSource implementation
488 */
489 @Override
490 public void onDragViewVisible() {}
491 @Override
Adam Cohenc0dcf592011-06-01 15:30:43 -0700492 public void onDropCompleted(View target, DragObject d, boolean success) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700493 endDragging(target, success);
Winson Chungfc79c802011-05-02 13:35:34 -0700494
495 // Display an error message if the drag failed due to there not being enough space on the
496 // target layout we were dropping on.
497 if (!success) {
498 boolean showOutOfSpaceMessage = false;
499 if (target instanceof Workspace) {
500 int currentScreen = mLauncher.getCurrentWorkspaceScreen();
501 Workspace workspace = (Workspace) target;
502 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
Adam Cohenc0dcf592011-06-01 15:30:43 -0700503 ItemInfo itemInfo = (ItemInfo) d.dragInfo;
Winson Chungfc79c802011-05-02 13:35:34 -0700504 if (layout != null) {
505 layout.calculateSpans(itemInfo);
506 showOutOfSpaceMessage =
507 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
508 }
509 }
510 // TODO-APPS_CUSTOMIZE: We need to handle this for folders as well later.
511 if (showOutOfSpaceMessage) {
512 mLauncher.showOutOfSpaceMessage();
513 }
514 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700515 }
516
517 public void setContentType(ContentType type) {
518 mContentType = type;
519 setCurrentPage(0);
520 invalidatePageData();
521 }
522
Winson Chungb44b5242011-06-13 11:32:14 -0700523 public boolean isContentType(ContentType type) {
524 return (mContentType == type);
525 }
526
Winson Chung785d2eb2011-04-14 16:08:02 -0700527 /*
528 * Apps PagedView implementation
529 */
Winson Chung63257c12011-05-05 17:06:13 -0700530 private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
531 int childCount = layout.getChildCount();
532 for (int i = 0; i < childCount; ++i) {
533 layout.getChildAt(i).setVisibility(visibility);
534 }
535 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700536 private void setupPage(PagedViewCellLayout layout) {
537 layout.setCellCount(mCellCountX, mCellCountY);
538 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
539 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
540 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
541
Winson Chung63257c12011-05-05 17:06:13 -0700542 // Note: We force a measure here to get around the fact that when we do layout calculations
543 // immediately after syncing, we don't have a proper width. That said, we already know the
544 // expected page width, so we can actually optimize by hiding all the TextView-based
545 // children that are expensive to measure, and let that happen naturally later.
546 setVisibilityOnChildren(layout, View.GONE);
Winson Chungdb1138b2011-06-30 14:39:35 -0700547 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -0700548 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -0700549 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -0700550 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -0700551 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700552 }
553 public void syncAppsPages() {
554 // Ensure that we have the right number of pages
555 Context context = getContext();
556 int numPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
557 for (int i = 0; i < numPages; ++i) {
558 PagedViewCellLayout layout = new PagedViewCellLayout(context);
559 setupPage(layout);
560 addView(layout);
561 }
562 }
563 public void syncAppsPageItems(int page) {
564 // ensure that we have the right number of items on the pages
565 int numPages = getPageCount();
566 int numCells = mCellCountX * mCellCountY;
567 int startIndex = page * numCells;
568 int endIndex = Math.min(startIndex + numCells, mApps.size());
569 PagedViewCellLayout layout = (PagedViewCellLayout) getChildAt(page);
Winson Chung875de7e2011-06-28 14:25:17 -0700570
Winson Chung785d2eb2011-04-14 16:08:02 -0700571 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,
Winson Chungd2945262011-06-24 15:22:14 -0700621 int cellWidth, int cellHeight, int cellCountX) {
Winson Chungb44b5242011-06-13 11:32:14 -0700622 // 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;
Winson Chung875de7e2011-06-28 14:25:17 -0700627 if ((taskPage == page) ||
628 taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
Winson Chung4e076542011-06-23 13:04:10 -0700629 taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
Winson Chungb44b5242011-06-13 11:32:14 -0700630 task.cancel(false);
631 iter.remove();
632 } else {
633 task.setThreadPriority(getThreadPriorityForPage(taskPage));
634 }
635 }
636
637 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
Winson Chungd2945262011-06-24 15:22:14 -0700638 cellCountX, new AsyncTaskCallback() {
Winson Chungb44b5242011-06-13 11:32:14 -0700639 @Override
640 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
641 // Ensure that this task starts running at the correct priority
642 task.syncThreadPriority();
643
644 // Load each of the widget/shortcut previews
645 ArrayList<Object> items = data.items;
Winson Chung4e076542011-06-23 13:04:10 -0700646 ArrayList<Bitmap> images = data.generatedImages;
Winson Chungb44b5242011-06-13 11:32:14 -0700647 int count = items.size();
648 int cellWidth = data.cellWidth;
649 int cellHeight = data.cellHeight;
650 for (int i = 0; i < count && !task.isCancelled(); ++i) {
651 // Before work on each item, ensure that this task is running at the correct
652 // priority
653 task.syncThreadPriority();
654
655 Object rawInfo = items.get(i);
656 if (rawInfo instanceof AppWidgetProviderInfo) {
657 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
658 int[] cellSpans = CellLayout.rectToCell(getResources(),
659 info.minWidth, info.minHeight, null);
Winson Chung4e076542011-06-23 13:04:10 -0700660 images.add(getWidgetPreview(info, cellSpans[0],cellSpans[1],
Winson Chungb44b5242011-06-13 11:32:14 -0700661 cellWidth, cellHeight));
662 } else if (rawInfo instanceof ResolveInfo) {
663 // Fill in the shortcuts information
664 ResolveInfo info = (ResolveInfo) rawInfo;
Winson Chung4e076542011-06-23 13:04:10 -0700665 images.add(getShortcutPreview(info, cellWidth, cellHeight));
Winson Chungb44b5242011-06-13 11:32:14 -0700666 }
667 }
668 }
669 },
670 new AsyncTaskCallback() {
671 @Override
672 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
673 mRunningTasks.remove(task);
Winson Chung875de7e2011-06-28 14:25:17 -0700674 if (task.isCancelled()) return;
Winson Chungb44b5242011-06-13 11:32:14 -0700675 if (task.page > getPageCount()) return;
676 if (task.pageContentType != mContentType) return;
677 onSyncWidgetPageItems(data);
678 }
679 });
680
681 // Ensure that the task is appropriately prioritized and runs in parallel
Winson Chung875de7e2011-06-28 14:25:17 -0700682 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page, mContentType,
683 AsyncTaskPageData.Type.LoadWidgetPreviewData);
Winson Chungb44b5242011-06-13 11:32:14 -0700684 t.setThreadPriority(getThreadPriorityForPage(page));
685 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
686 mRunningTasks.add(t);
687 }
688 /**
689 * Creates and executes a new AsyncTask to load the outlines for a page of content.
690 */
691 private void prepareGenerateHoloOutlinesTask(int page, ArrayList<Object> items,
692 ArrayList<Bitmap> images) {
Winson Chung875de7e2011-06-28 14:25:17 -0700693 // Prune old tasks for this page
694 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
695 while (iter.hasNext()) {
696 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
697 int taskPage = task.page;
698 if ((taskPage == page) &&
699 (task.dataType == AsyncTaskPageData.Type.LoadHolographicIconsData)) {
700 task.cancel(false);
701 iter.remove();
702 }
703 }
704
Winson Chungb44b5242011-06-13 11:32:14 -0700705 AsyncTaskPageData pageData = new AsyncTaskPageData(page, items, images,
706 new AsyncTaskCallback() {
707 @Override
708 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
709 // Ensure that this task starts running at the correct priority
710 task.syncThreadPriority();
711
Winson Chung4e076542011-06-23 13:04:10 -0700712 ArrayList<Bitmap> images = data.generatedImages;
713 ArrayList<Bitmap> srcImages = data.sourceImages;
Winson Chungb44b5242011-06-13 11:32:14 -0700714 int count = srcImages.size();
715 Canvas c = new Canvas();
716 for (int i = 0; i < count && !task.isCancelled(); ++i) {
717 // Before work on each item, ensure that this task is running at the correct
718 // priority
719 task.syncThreadPriority();
720
721 Bitmap b = srcImages.get(i);
722 Bitmap outline = Bitmap.createBitmap(b.getWidth(), b.getHeight(),
723 Bitmap.Config.ARGB_8888);
724
725 c.setBitmap(outline);
726 c.save();
727 c.drawBitmap(b, 0, 0, null);
728 c.restore();
729
730 images.add(outline);
731 }
732 }
733 },
734 new AsyncTaskCallback() {
735 @Override
736 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
737 mRunningTasks.remove(task);
Winson Chung875de7e2011-06-28 14:25:17 -0700738 if (task.isCancelled()) return;
Winson Chungb44b5242011-06-13 11:32:14 -0700739 if (task.page > getPageCount()) return;
740 if (task.pageContentType != mContentType) return;
741 onHolographicPageItemsLoaded(data);
742 }
743 });
744
745 // Ensure that the outline task always runs in the background, serially
Winson Chung4e076542011-06-23 13:04:10 -0700746 AppsCustomizeAsyncTask t =
Winson Chung875de7e2011-06-28 14:25:17 -0700747 new AppsCustomizeAsyncTask(page, mContentType,
748 AsyncTaskPageData.Type.LoadHolographicIconsData);
Winson Chungb44b5242011-06-13 11:32:14 -0700749 t.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
750 t.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, pageData);
751 mRunningTasks.add(t);
752 }
753
Winson Chung785d2eb2011-04-14 16:08:02 -0700754 /*
755 * Widgets PagedView implementation
756 */
Winson Chung4e6a9762011-05-09 11:56:34 -0700757 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -0700758 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
759 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -0700760
761 // Note: We force a measure here to get around the fact that when we do layout calculations
762 // immediately after syncing, we don't have a proper width. That said, we already know the
763 // expected page width, so we can actually optimize by hiding all the TextView-based
764 // children that are expensive to measure, and let that happen naturally later.
765 setVisibilityOnChildren(layout, View.GONE);
766 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
767 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -0700768 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -0700769 layout.measure(widthSpec, heightSpec);
770 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -0700771 }
Michael Jurkabe69cc82011-07-07 16:05:33 -0700772 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
Winson Chung785d2eb2011-04-14 16:08:02 -0700773 float scaleX, float scaleY) {
Winson Chung201bc822011-06-20 15:41:53 -0700774 if (bitmap != null) {
Winson Chungb44b5242011-06-13 11:32:14 -0700775 Canvas c = new Canvas(bitmap);
Winson Chung201bc822011-06-20 15:41:53 -0700776 c.scale(scaleX, scaleY);
777 Rect oldBounds = d.copyBounds();
778 d.setBounds(x, y, x + w, y + h);
779 d.draw(c);
780 d.setBounds(oldBounds); // Restore the bounds
Winson Chung201bc822011-06-20 15:41:53 -0700781 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700782 }
Winson Chungd2945262011-06-24 15:22:14 -0700783 private Bitmap getShortcutPreview(ResolveInfo info, int cellWidth, int cellHeight) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700784 // Render the icon
Winson Chungd2945262011-06-24 15:22:14 -0700785 Bitmap preview = Bitmap.createBitmap(cellWidth, mAppIconSize, Config.ARGB_8888);
Winson Chung4dbea792011-05-05 14:21:32 -0700786 Drawable icon = mIconCache.getFullResIcon(info, mPackageManager);
Winson Chungd2945262011-06-24 15:22:14 -0700787 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize, 1f, 1f);
Winson Chungb44b5242011-06-13 11:32:14 -0700788 return preview;
Winson Chung1ed747a2011-05-03 16:18:34 -0700789 }
Winson Chung4e076542011-06-23 13:04:10 -0700790 private Bitmap getWidgetPreview(AppWidgetProviderInfo info,
Winson Chungb44b5242011-06-13 11:32:14 -0700791 int cellHSpan, int cellVSpan, int cellWidth, int cellHeight) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700792
Winson Chung4b576be2011-04-27 17:40:20 -0700793 // Calculate the size of the drawable
794 cellHSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellHSpan));
795 cellVSpan = Math.max(mMinWidgetSpan, Math.min(mMaxWidgetSpan, cellVSpan));
796 int expectedWidth = mWidgetSpacingLayout.estimateCellWidth(cellHSpan);
797 int expectedHeight = mWidgetSpacingLayout.estimateCellHeight(cellVSpan);
798
799 // Scale down the bitmap to fit the space
800 float widgetPreviewScale = (float) cellWidth / expectedWidth;
801 expectedWidth = (int) (widgetPreviewScale * expectedWidth);
802 expectedHeight = (int) (widgetPreviewScale * expectedHeight);
803
804 // Load the preview image if possible
805 String packageName = info.provider.getPackageName();
806 Drawable drawable = null;
Winson Chungb44b5242011-06-13 11:32:14 -0700807 Bitmap preview = null;
Winson Chung4b576be2011-04-27 17:40:20 -0700808 if (info.previewImage != 0) {
809 drawable = mPackageManager.getDrawable(packageName, info.previewImage, null);
810 if (drawable == null) {
811 Log.w(LOG_TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon)
812 + " for provider: " + info.provider);
813 } else {
814 // Scale down the preview to the dimensions we want
815 int imageWidth = drawable.getIntrinsicWidth();
816 int imageHeight = drawable.getIntrinsicHeight();
817 float aspect = (float) imageWidth / imageHeight;
818 int newWidth = imageWidth;
819 int newHeight = imageHeight;
820 if (aspect > 1f) {
821 newWidth = expectedWidth;
822 newHeight = (int) (imageHeight * ((float) expectedWidth / imageWidth));
823 } else {
824 newHeight = expectedHeight;
825 newWidth = (int) (imageWidth * ((float) expectedHeight / imageHeight));
826 }
827
Winson Chungb44b5242011-06-13 11:32:14 -0700828 preview = Bitmap.createBitmap(newWidth, newHeight, Config.ARGB_8888);
Winson Chung4b576be2011-04-27 17:40:20 -0700829 renderDrawableToBitmap(drawable, preview, 0, 0, newWidth, newHeight, 1f, 1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700830 }
831 }
832
833 // Generate a preview image if we couldn't load one
834 if (drawable == null) {
Winson Chung1ed747a2011-05-03 16:18:34 -0700835 Resources resources = mLauncher.getResources();
Winson Chung273c1022011-07-11 13:40:52 -0700836 int bitmapWidth;
837 int bitmapHeight;
Winson Chung1ed747a2011-05-03 16:18:34 -0700838
Winson Chung273c1022011-07-11 13:40:52 -0700839 // Specify the dimensions of the bitmap (since we are using a default preview bg with
840 // the full icon, we only imply the aspect ratio of the widget)
841 if (cellHSpan == cellVSpan) {
842 bitmapWidth = bitmapHeight = cellWidth;
843 expectedWidth = expectedHeight = mWidgetPreviewIconPaddedDimension;
844 } else if (cellHSpan >= cellVSpan) {
845 bitmapWidth = expectedWidth = cellWidth;
846 bitmapHeight = expectedHeight = mWidgetPreviewIconPaddedDimension;
Winson Chung1ed747a2011-05-03 16:18:34 -0700847 } else {
848 // Note that in vertical widgets, we might not have enough space due to the text
849 // label, so be conservative and use the width as a height bound
Winson Chung273c1022011-07-11 13:40:52 -0700850 bitmapWidth = expectedWidth = mWidgetPreviewIconPaddedDimension;
851 bitmapHeight = expectedHeight = cellWidth;
Winson Chung1ed747a2011-05-03 16:18:34 -0700852 }
Winson Chung4b576be2011-04-27 17:40:20 -0700853
Winson Chung273c1022011-07-11 13:40:52 -0700854 preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Config.ARGB_8888);
Winson Chung1ed747a2011-05-03 16:18:34 -0700855 renderDrawableToBitmap(mDefaultWidgetBackground, preview, 0, 0, expectedWidth,
856 expectedHeight, 1f,1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700857
858 // Draw the icon in the top left corner
859 try {
860 Drawable icon = null;
861 if (info.icon > 0) icon = mPackageManager.getDrawable(packageName, info.icon, null);
862 if (icon == null) icon = resources.getDrawable(R.drawable.ic_launcher_application);
863
Winson Chungd2945262011-06-24 15:22:14 -0700864 int offset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
865 renderDrawableToBitmap(icon, preview, offset, offset,
866 mAppIconSize, mAppIconSize, 1f, 1f);
Winson Chung4b576be2011-04-27 17:40:20 -0700867 } catch (Resources.NotFoundException e) {}
Winson Chung4b576be2011-04-27 17:40:20 -0700868 }
Winson Chungb44b5242011-06-13 11:32:14 -0700869 return preview;
Winson Chung785d2eb2011-04-14 16:08:02 -0700870 }
871 public void syncWidgetPages() {
872 // Ensure that we have the right number of pages
873 Context context = getContext();
Winson Chungd2945262011-06-24 15:22:14 -0700874 int[] countX = { mWidgetCountX, mShortcutCountX };
875 int[] countY = { mWidgetCountY, mShortcutCountY };
876 Object[] collection = { mWidgets, mShortcuts };
877 for (int i = 0; i < 2; ++i) {
878 ArrayList<Object> list = (ArrayList<Object>) collection[i];
879 int numItemsPerPage = countX[i] * countY[i];
880 int numItemPages = (int) Math.ceil(list.size() / (float) numItemsPerPage);
881 for (int j = 0; j < numItemPages; ++j) {
882 PagedViewGridLayout layout = new PagedViewGridLayout(context, countX[i],
883 countY[i]);
884 setupPage(layout);
885 addView(layout);
886 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700887 }
888 }
889 public void syncWidgetPageItems(int page) {
Winson Chungd2945262011-06-24 15:22:14 -0700890 int[] countX = { mWidgetCountX, mShortcutCountX };
891 int[] countY = { mWidgetCountY, mShortcutCountY };
892 int[] widthGap = { mWidgetWidthGap, mWidgetWidthGap };
893 int[] heightGap = { mWidgetHeightGap, mWidgetHeightGap };
894 int[] numItemsPerPage = { mWidgetCountX * mWidgetCountY,
895 mShortcutCountX * mShortcutCountY };
896 Object[] collection = { mWidgets, mShortcuts };
897 int contentWidth = mWidgetSpacingLayout.getContentWidth();
898 int contentHeight = mWidgetSpacingLayout.getContentHeight();
899 int numWidgetPages = (int) Math.ceil(mWidgets.size() / (float) numItemsPerPage[0]);
900 int[] offsets = { page * numItemsPerPage[0], (page - numWidgetPages) * numItemsPerPage[1] };
901 int index = (page < numWidgetPages ? 0 : 1);
Winson Chungb44b5242011-06-13 11:32:14 -0700902
Winson Chungd2945262011-06-24 15:22:14 -0700903 // Calculate the dimensions of each cell we are giving to each widget
904 ArrayList<Object> list = (ArrayList<Object>) collection[index];
905 ArrayList<Object> items = new ArrayList<Object>();
906 int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
907 - ((countX[index] - 1) * widthGap[index])) / countX[index]);
908 int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
909 - ((countY[index] - 1) * heightGap[index])) / countY[index]);
910
911 int offset = offsets[index];
912 for (int i = offset; i < Math.min(offset + numItemsPerPage[index], list.size()); ++i) {
913 items.add(list.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -0700914 }
915
Winson Chungd2945262011-06-24 15:22:14 -0700916 prepareLoadWidgetPreviewsTask(page, items, cellWidth, cellHeight, countX[index]);
Winson Chungb44b5242011-06-13 11:32:14 -0700917 }
918 private void onSyncWidgetPageItems(AsyncTaskPageData data) {
919 int page = data.page;
Winson Chung4e6a9762011-05-09 11:56:34 -0700920 PagedViewGridLayout layout = (PagedViewGridLayout) getChildAt(page);
Winson Chung4b576be2011-04-27 17:40:20 -0700921 layout.removeAllViews();
Winson Chung785d2eb2011-04-14 16:08:02 -0700922
Winson Chungb44b5242011-06-13 11:32:14 -0700923 ArrayList<Object> items = data.items;
924 int count = items.size();
925 int cellWidth = data.cellWidth;
926 int cellHeight = data.cellHeight;
Winson Chungd2945262011-06-24 15:22:14 -0700927 int cellCountX = data.cellCountX;
Winson Chungb44b5242011-06-13 11:32:14 -0700928 for (int i = 0; i < count; ++i) {
929 Object rawInfo = items.get(i);
Winson Chung1ed747a2011-05-03 16:18:34 -0700930 PendingAddItemInfo createItemInfo = null;
Winson Chung4b576be2011-04-27 17:40:20 -0700931 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
932 R.layout.apps_customize_widget, layout, false);
Winson Chung1ed747a2011-05-03 16:18:34 -0700933 if (rawInfo instanceof AppWidgetProviderInfo) {
934 // Fill in the widget information
935 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
936 createItemInfo = new PendingAddWidgetInfo(info, null, null);
Winson Chungb44b5242011-06-13 11:32:14 -0700937 int[] cellSpans = CellLayout.rectToCell(getResources(),
938 info.minWidth, info.minHeight, null);
Winson Chung4e076542011-06-23 13:04:10 -0700939 FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
Winson Chung9f4e0fd2011-06-02 18:59:36 -0700940 widget.applyFromAppWidgetProviderInfo(info, preview, -1, cellSpans,
Winson Chungb44b5242011-06-13 11:32:14 -0700941 mHolographicOutlineHelper);
Winson Chung1ed747a2011-05-03 16:18:34 -0700942 widget.setTag(createItemInfo);
943 } else if (rawInfo instanceof ResolveInfo) {
944 // Fill in the shortcuts information
945 ResolveInfo info = (ResolveInfo) rawInfo;
946 createItemInfo = new PendingAddItemInfo();
947 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
948 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
949 info.activityInfo.name);
Winson Chung4e076542011-06-23 13:04:10 -0700950 FastBitmapDrawable preview = new FastBitmapDrawable(data.generatedImages.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -0700951 widget.applyFromResolveInfo(mPackageManager, info, preview,
952 mHolographicOutlineHelper);
Winson Chung1ed747a2011-05-03 16:18:34 -0700953 widget.setTag(createItemInfo);
954 }
Winson Chung4b576be2011-04-27 17:40:20 -0700955 widget.setOnClickListener(this);
956 widget.setOnLongClickListener(this);
957 widget.setOnTouchListener(this);
958
959 // Layout each widget
Winson Chungd2945262011-06-24 15:22:14 -0700960 int ix = i % cellCountX;
961 int iy = i / cellCountX;
Winson Chungfd3385f2011-06-15 19:51:24 -0700962 GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
963 new GridLayout.Group(iy, 1, GridLayout.LEFT),
964 new GridLayout.Group(ix, 1, GridLayout.TOP));
965 lp.width = cellWidth;
966 lp.height = cellHeight;
967 if (ix > 0) lp.leftMargin = mWidgetWidthGap;
968 if (iy > 0) lp.topMargin = mWidgetHeightGap;
Winson Chung4e6a9762011-05-09 11:56:34 -0700969 layout.addView(widget, lp);
Winson Chung785d2eb2011-04-14 16:08:02 -0700970 }
Winson Chungb44b5242011-06-13 11:32:14 -0700971
972 invalidate();
973 forceUpdateAdjacentPagesAlpha();
Winson Chung4e076542011-06-23 13:04:10 -0700974 prepareGenerateHoloOutlinesTask(data.page, data.items, data.generatedImages);
Winson Chungb44b5242011-06-13 11:32:14 -0700975 }
976 private void onHolographicPageItemsLoaded(AsyncTaskPageData data) {
977 // Invalidate early to short-circuit children invalidates
978 invalidate();
979
980 int page = data.page;
981 ViewGroup layout = (ViewGroup) getChildAt(page);
982 if (layout instanceof PagedViewCellLayout) {
983 PagedViewCellLayout cl = (PagedViewCellLayout) layout;
984 int count = cl.getPageChildCount();
Winson Chung875de7e2011-06-28 14:25:17 -0700985 if (count != data.generatedImages.size()) return;
Winson Chungb44b5242011-06-13 11:32:14 -0700986 for (int i = 0; i < count; ++i) {
987 PagedViewIcon icon = (PagedViewIcon) cl.getChildOnPageAt(i);
Winson Chung4e076542011-06-23 13:04:10 -0700988 icon.setHolographicOutline(data.generatedImages.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -0700989 }
990 } else {
991 int count = layout.getChildCount();
Winson Chung875de7e2011-06-28 14:25:17 -0700992 if (count != data.generatedImages.size()) return;
Winson Chungb44b5242011-06-13 11:32:14 -0700993 for (int i = 0; i < count; ++i) {
994 View v = layout.getChildAt(i);
Winson Chung4e076542011-06-23 13:04:10 -0700995 ((PagedViewWidget) v).setHolographicOutline(data.generatedImages.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -0700996 }
997 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700998 }
Winson Chung46af2e82011-05-09 16:00:53 -0700999
Winson Chung785d2eb2011-04-14 16:08:02 -07001000 @Override
1001 public void syncPages() {
1002 removeAllViews();
Winson Chung875de7e2011-06-28 14:25:17 -07001003
1004 // Remove all background asyc tasks if we are loading content anew
1005 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1006 while (iter.hasNext()) {
1007 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1008 task.cancel(false);
1009 iter.remove();
1010 }
1011
Winson Chung785d2eb2011-04-14 16:08:02 -07001012 switch (mContentType) {
1013 case Applications:
1014 syncAppsPages();
1015 break;
1016 case Widgets:
1017 syncWidgetPages();
1018 break;
1019 }
1020 }
1021 @Override
1022 public void syncPageItems(int page) {
1023 switch (mContentType) {
1024 case Applications:
1025 syncAppsPageItems(page);
1026 break;
1027 case Widgets:
1028 syncWidgetPageItems(page);
1029 break;
1030 }
1031 }
1032
1033 /**
1034 * Used by the parent to get the content width to set the tab bar to
1035 * @return
1036 */
1037 public int getPageContentWidth() {
1038 return mContentWidth;
1039 }
1040
Winson Chungb26f3d62011-06-02 10:49:29 -07001041 @Override
1042 protected void onPageBeginMoving() {
1043 /* TO BE ENABLED LATER
1044 setChildrenDrawnWithCacheEnabled(true);
1045 for (int i = 0; i < getChildCount(); ++i) {
1046 View v = getChildAt(i);
1047 if (v instanceof PagedViewCellLayout) {
1048 ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(true);
1049 }
1050 }
1051 */
1052 super.onPageBeginMoving();
1053 }
1054
1055 @Override
1056 protected void onPageEndMoving() {
1057 /* TO BE ENABLED LATER
1058 for (int i = 0; i < getChildCount(); ++i) {
1059 View v = getChildAt(i);
1060 if (v instanceof PagedViewCellLayout) {
1061 ((PagedViewCellLayout) v).setChildrenDrawingCacheEnabled(false);
1062 }
1063 }
1064 setChildrenDrawnWithCacheEnabled(false);
1065 */
1066 super.onPageEndMoving();
1067 }
1068
Winson Chung785d2eb2011-04-14 16:08:02 -07001069 /*
1070 * AllAppsView implementation
1071 */
1072 @Override
1073 public void setup(Launcher launcher, DragController dragController) {
1074 mLauncher = launcher;
1075 mDragController = dragController;
1076 }
1077 @Override
1078 public void zoom(float zoom, boolean animate) {
1079 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1080 }
1081 @Override
1082 public boolean isVisible() {
1083 return (getVisibility() == VISIBLE);
1084 }
1085 @Override
1086 public boolean isAnimating() {
1087 return false;
1088 }
1089 @Override
1090 public void setApps(ArrayList<ApplicationInfo> list) {
1091 mApps = list;
1092 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
Winson Chungf0ea4d32011-06-06 14:27:16 -07001093
Winson Chung875de7e2011-06-28 14:25:17 -07001094 // The next layout pass will trigger data-ready if both widgets and apps are set, so
1095 // request a layout to do this test and invalidate the page data when ready.
Winson Chungf0ea4d32011-06-06 14:27:16 -07001096 if (testDataReady()) requestLayout();
Winson Chung785d2eb2011-04-14 16:08:02 -07001097 }
1098 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1099 // We add it in place, in alphabetical order
1100 int count = list.size();
1101 for (int i = 0; i < count; ++i) {
1102 ApplicationInfo info = list.get(i);
1103 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1104 if (index < 0) {
1105 mApps.add(-(index + 1), info);
1106 }
1107 }
1108 }
1109 @Override
1110 public void addApps(ArrayList<ApplicationInfo> list) {
1111 addAppsWithoutInvalidate(list);
1112 invalidatePageData();
1113 }
1114 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1115 ComponentName removeComponent = item.intent.getComponent();
1116 int length = list.size();
1117 for (int i = 0; i < length; ++i) {
1118 ApplicationInfo info = list.get(i);
1119 if (info.intent.getComponent().equals(removeComponent)) {
1120 return i;
1121 }
1122 }
1123 return -1;
1124 }
1125 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1126 // loop through all the apps and remove apps that have the same component
1127 int length = list.size();
1128 for (int i = 0; i < length; ++i) {
1129 ApplicationInfo info = list.get(i);
1130 int removeIndex = findAppByComponent(mApps, info);
1131 if (removeIndex > -1) {
1132 mApps.remove(removeIndex);
Winson Chung785d2eb2011-04-14 16:08:02 -07001133 }
1134 }
1135 }
1136 @Override
1137 public void removeApps(ArrayList<ApplicationInfo> list) {
1138 removeAppsWithoutInvalidate(list);
1139 invalidatePageData();
1140 }
1141 @Override
1142 public void updateApps(ArrayList<ApplicationInfo> list) {
1143 // We remove and re-add the updated applications list because it's properties may have
1144 // changed (ie. the title), and this will ensure that the items will be in their proper
1145 // place in the list.
1146 removeAppsWithoutInvalidate(list);
1147 addAppsWithoutInvalidate(list);
1148 invalidatePageData();
1149 }
Michael Jurka35aa14d2011-07-07 17:01:08 -07001150
Winson Chung785d2eb2011-04-14 16:08:02 -07001151 @Override
1152 public void reset() {
Winson Chungfc79c802011-05-02 13:35:34 -07001153 if (mContentType != ContentType.Applications) {
1154 // Reset to the first page of the Apps pane
1155 AppsCustomizeTabHost tabs = (AppsCustomizeTabHost)
1156 mLauncher.findViewById(R.id.apps_customize_pane);
1157 tabs.setCurrentTabByTag(tabs.getTabTagForContentType(ContentType.Applications));
Michael Jurka35aa14d2011-07-07 17:01:08 -07001158 } else if (getCurrentPage() != 0) {
Winson Chungfc79c802011-05-02 13:35:34 -07001159 setCurrentPage(0);
1160 invalidatePageData();
1161 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001162 }
1163 @Override
1164 public void dumpState() {
1165 // TODO: Dump information related to current list of Applications, Widgets, etc.
1166 ApplicationInfo.dumpApplicationInfoList(LOG_TAG, "mApps", mApps);
1167 dumpAppWidgetProviderInfoList(LOG_TAG, "mWidgets", mWidgets);
Winson Chungd2945262011-06-24 15:22:14 -07001168 dumpAppWidgetProviderInfoList(LOG_TAG, "mShortcuts", mShortcuts);
Winson Chung785d2eb2011-04-14 16:08:02 -07001169 }
1170 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chungd2945262011-06-24 15:22:14 -07001171 ArrayList<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001172 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -07001173 for (Object i: list) {
1174 if (i instanceof AppWidgetProviderInfo) {
1175 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1176 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
1177 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1178 + " initialLayout=" + info.initialLayout
1179 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1180 } else if (i instanceof ResolveInfo) {
1181 ResolveInfo info = (ResolveInfo) i;
1182 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1183 + info.icon);
1184 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001185 }
1186 }
1187 @Override
1188 public void surrender() {
1189 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1190 // should stop this now.
1191 }
Winson Chung007c6982011-06-14 13:27:53 -07001192
Winson Chungb44b5242011-06-13 11:32:14 -07001193 /*
1194 * We load an extra page on each side to prevent flashes from scrolling and loading of the
1195 * widget previews in the background with the AsyncTasks.
1196 */
1197 protected int getAssociatedLowerPageBound(int page) {
1198 return Math.max(0, page - 2);
1199 }
1200 protected int getAssociatedUpperPageBound(int page) {
1201 final int count = getChildCount();
1202 return Math.min(page + 2, count - 1);
1203 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07001204
1205 @Override
1206 protected String getCurrentPageDescription() {
1207 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1208 int stringId = R.string.default_scroll_format;
1209 switch (mContentType) {
1210 case Applications:
1211 stringId = R.string.apps_customize_apps_scroll_format;
1212 break;
1213 case Widgets:
1214 stringId = R.string.apps_customize_widgets_scroll_format;
1215 break;
1216 }
1217 return String.format(mContext.getString(stringId), page + 1, getChildCount());
1218 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001219}