blob: 80fc62fce61a5c674a380f325a28e7bf4f1b1e66 [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 Chungd2e87b32011-06-02 10:53:07 -070020import android.animation.ValueAnimator;
Adam Cohened66b2b2012-01-23 17:28:51 -080021import android.appwidget.AppWidgetHostView;
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;
27import android.content.pm.PackageManager;
28import android.content.pm.ResolveInfo;
Winson Chungf0ea4d32011-06-06 14:27:16 -070029import android.content.res.Configuration;
Winson Chung785d2eb2011-04-14 16:08:02 -070030import android.content.res.Resources;
31import android.content.res.TypedArray;
32import android.graphics.Bitmap;
Adam Cohen4e844012011-11-09 13:48:04 -080033import android.graphics.Bitmap.Config;
Winson Chung785d2eb2011-04-14 16:08:02 -070034import android.graphics.Canvas;
Michael Jurkadac85912012-05-18 15:04:49 -070035import android.graphics.ColorMatrix;
36import android.graphics.ColorMatrixColorFilter;
Winson Chung72d59842012-02-22 13:51:36 -080037import android.graphics.Matrix;
Peter Ng8db70002011-10-25 15:40:08 -070038import android.graphics.Paint;
Michael Jurkadac85912012-05-18 15:04:49 -070039import android.graphics.PorterDuff;
Winson Chung785d2eb2011-04-14 16:08:02 -070040import android.graphics.Rect;
Winson Chung72d59842012-02-22 13:51:36 -080041import android.graphics.RectF;
Michael Jurkadac85912012-05-18 15:04:49 -070042import android.graphics.Shader;
Michael Jurkadac85912012-05-18 15:04:49 -070043import android.graphics.drawable.BitmapDrawable;
Winson Chung785d2eb2011-04-14 16:08:02 -070044import android.graphics.drawable.Drawable;
Winson Chungb44b5242011-06-13 11:32:14 -070045import android.os.AsyncTask;
46import android.os.Process;
Winson Chung785d2eb2011-04-14 16:08:02 -070047import android.util.AttributeSet;
48import android.util.Log;
Winson Chung72d8b392011-07-29 13:56:44 -070049import android.view.Gravity;
Winson Chungc6f10b92011-11-14 11:39:07 -080050import android.view.KeyEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070051import android.view.LayoutInflater;
Winson Chungde1af762011-07-21 16:44:07 -070052import android.view.MotionEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070053import android.view.View;
Winson Chung63257c12011-05-05 17:06:13 -070054import android.view.ViewGroup;
Winson Chung55b65502011-05-26 12:03:43 -070055import android.view.animation.AccelerateInterpolator;
Adam Cohen2591f6a2011-10-25 14:36:40 -070056import android.view.animation.DecelerateInterpolator;
Winson Chungfd3385f2011-06-15 19:51:24 -070057import android.widget.GridLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070058import android.widget.ImageView;
Winson Chung55b65502011-05-26 12:03:43 -070059import android.widget.Toast;
Winson Chung785d2eb2011-04-14 16:08:02 -070060
61import com.android.launcher.R;
Adam Cohenc0dcf592011-06-01 15:30:43 -070062import com.android.launcher2.DropTarget.DragObject;
63
Michael Jurka9bc8eba2012-05-21 20:36:44 -070064import java.lang.ref.WeakReference;
Adam Cohenc0dcf592011-06-01 15:30:43 -070065import java.util.ArrayList;
66import java.util.Collections;
67import java.util.Iterator;
68import java.util.List;
Winson Chung785d2eb2011-04-14 16:08:02 -070069
Winson Chungb44b5242011-06-13 11:32:14 -070070/**
71 * A simple callback interface which also provides the results of the task.
72 */
73interface AsyncTaskCallback {
74 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
75}
Winson Chung4e076542011-06-23 13:04:10 -070076
Winson Chungb44b5242011-06-13 11:32:14 -070077/**
78 * The data needed to perform either of the custom AsyncTasks.
79 */
80class AsyncTaskPageData {
Winson Chung875de7e2011-06-28 14:25:17 -070081 enum Type {
Michael Jurka82369a12012-01-12 08:08:38 -080082 LoadWidgetPreviewData
Winson Chung875de7e2011-06-28 14:25:17 -070083 }
84
Winson Chungb44b5242011-06-13 11:32:14 -070085 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
86 AsyncTaskCallback postR) {
87 page = p;
88 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070089 sourceImages = si;
90 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -070091 maxImageWidth = maxImageHeight = -1;
Winson Chungb44b5242011-06-13 11:32:14 -070092 doInBackgroundCallback = bgR;
93 postExecuteCallback = postR;
94 }
Michael Jurka038f9d82011-11-03 13:50:45 -070095 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
Winson Chungb44b5242011-06-13 11:32:14 -070096 AsyncTaskCallback postR) {
97 page = p;
98 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070099 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -0700100 maxImageWidth = cw;
101 maxImageHeight = ch;
Winson Chungb44b5242011-06-13 11:32:14 -0700102 doInBackgroundCallback = bgR;
103 postExecuteCallback = postR;
104 }
Winson Chung09945932011-09-20 14:22:40 -0700105 void cleanup(boolean cancelled) {
106 // Clean up any references to source/generated bitmaps
107 if (sourceImages != null) {
108 if (cancelled) {
109 for (Bitmap b : sourceImages) {
110 b.recycle();
111 }
112 }
113 sourceImages.clear();
114 }
115 if (generatedImages != null) {
116 if (cancelled) {
117 for (Bitmap b : generatedImages) {
118 b.recycle();
119 }
120 }
121 generatedImages.clear();
122 }
123 }
Winson Chungb44b5242011-06-13 11:32:14 -0700124 int page;
125 ArrayList<Object> items;
Winson Chung4e076542011-06-23 13:04:10 -0700126 ArrayList<Bitmap> sourceImages;
127 ArrayList<Bitmap> generatedImages;
Michael Jurka038f9d82011-11-03 13:50:45 -0700128 int maxImageWidth;
129 int maxImageHeight;
Winson Chungb44b5242011-06-13 11:32:14 -0700130 AsyncTaskCallback doInBackgroundCallback;
131 AsyncTaskCallback postExecuteCallback;
132}
Winson Chung4e076542011-06-23 13:04:10 -0700133
Winson Chungb44b5242011-06-13 11:32:14 -0700134/**
135 * A generic template for an async task used in AppsCustomize.
136 */
137class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700138 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
Winson Chungb44b5242011-06-13 11:32:14 -0700139 page = p;
Winson Chungb44b5242011-06-13 11:32:14 -0700140 threadPriority = Process.THREAD_PRIORITY_DEFAULT;
Winson Chung875de7e2011-06-28 14:25:17 -0700141 dataType = ty;
Winson Chungb44b5242011-06-13 11:32:14 -0700142 }
143 @Override
144 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
145 if (params.length != 1) return null;
146 // Load each of the widget previews in the background
147 params[0].doInBackgroundCallback.run(this, params[0]);
148 return params[0];
149 }
150 @Override
151 protected void onPostExecute(AsyncTaskPageData result) {
152 // All the widget previews are loaded, so we can just callback to inflate the page
153 result.postExecuteCallback.run(this, result);
154 }
155
156 void setThreadPriority(int p) {
157 threadPriority = p;
158 }
159 void syncThreadPriority() {
160 Process.setThreadPriority(threadPriority);
161 }
162
163 // The page that this async task is associated with
Winson Chung875de7e2011-06-28 14:25:17 -0700164 AsyncTaskPageData.Type dataType;
Winson Chungb44b5242011-06-13 11:32:14 -0700165 int page;
Winson Chungb44b5242011-06-13 11:32:14 -0700166 int threadPriority;
167}
Winson Chungb44b5242011-06-13 11:32:14 -0700168
Michael Jurkadac85912012-05-18 15:04:49 -0700169abstract class WeakReferenceThreadLocal<T> {
170 private ThreadLocal<WeakReference<T>> mThreadLocal;
171 public WeakReferenceThreadLocal() {
172 mThreadLocal = new ThreadLocal<WeakReference<T>>();
173 }
174
175 abstract T initialValue();
176
177 public void set(T t) {
178 mThreadLocal.set(new WeakReference<T>(t));
179 }
180
181 public T get() {
182 WeakReference<T> reference = mThreadLocal.get();
183 T obj;
184 if (reference == null) {
185 obj = initialValue();
186 mThreadLocal.set(new WeakReference<T>(obj));
187 return obj;
188 } else {
189 obj = reference.get();
190 if (obj == null) {
191 obj = initialValue();
192 mThreadLocal.set(new WeakReference<T>(obj));
193 }
194 return obj;
195 }
196 }
197}
198
199class CanvasCache extends WeakReferenceThreadLocal<Canvas> {
200 @Override
201 protected Canvas initialValue() {
202 return new Canvas();
203 }
204}
205
206class PaintCache extends WeakReferenceThreadLocal<Paint> {
207 @Override
208 protected Paint initialValue() {
209 return null;
210 }
211}
212
213class BitmapCache extends WeakReferenceThreadLocal<Bitmap> {
214 @Override
215 protected Bitmap initialValue() {
216 return null;
217 }
218}
219
220class RectCache extends WeakReferenceThreadLocal<Rect> {
221 @Override
222 protected Rect initialValue() {
223 return new Rect();
224 }
225}
226
Winson Chungb44b5242011-06-13 11:32:14 -0700227/**
228 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
229 */
Winson Chung785d2eb2011-04-14 16:08:02 -0700230public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
Winson Chungcd810732012-06-18 16:45:43 -0700231 View.OnClickListener, View.OnKeyListener, DragSource,
Michael Jurka39e5d172012-03-12 18:36:12 -0700232 PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener,
233 LauncherTransitionable {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700234 static final String TAG = "AppsCustomizePagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -0700235
236 /**
237 * The different content types that this paged view can show.
238 */
239 public enum ContentType {
240 Applications,
Winson Chung6a26e5b2011-05-26 14:36:06 -0700241 Widgets
Winson Chung785d2eb2011-04-14 16:08:02 -0700242 }
243
244 // Refs
245 private Launcher mLauncher;
246 private DragController mDragController;
247 private final LayoutInflater mLayoutInflater;
248 private final PackageManager mPackageManager;
249
Winson Chung5afbf7b2011-07-25 11:53:08 -0700250 // Save and Restore
251 private int mSaveInstanceStateItemIndex = -1;
Winson Chunge4e50662012-01-23 14:45:13 -0800252 private PagedViewIcon mPressedIcon;
Winson Chung5afbf7b2011-07-25 11:53:08 -0700253
Winson Chung785d2eb2011-04-14 16:08:02 -0700254 // Content
Winson Chung785d2eb2011-04-14 16:08:02 -0700255 private ArrayList<ApplicationInfo> mApps;
Winson Chungd2945262011-06-24 15:22:14 -0700256 private ArrayList<Object> mWidgets;
Winson Chung1ed747a2011-05-03 16:18:34 -0700257
Winson Chung7d7541e2011-09-16 20:14:36 -0700258 // Cling
Winson Chung3f4e1422011-11-17 14:58:51 -0800259 private boolean mHasShownAllAppsCling;
Winson Chung7d7541e2011-09-16 20:14:36 -0700260 private int mClingFocusedX;
261 private int mClingFocusedY;
262
Winson Chung1ed747a2011-05-03 16:18:34 -0700263 // Caching
Winson Chungb44b5242011-06-13 11:32:14 -0700264 private Canvas mCanvas;
Winson Chung4dbea792011-05-05 14:21:32 -0700265 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -0700266
267 // Dimens
268 private int mContentWidth;
Winson Chungd2945262011-06-24 15:22:14 -0700269 private int mAppIconSize;
Winson Chung6032e7e2011-11-08 15:47:17 -0800270 private int mMaxAppCellCountX, mMaxAppCellCountY;
Winson Chung4b576be2011-04-27 17:40:20 -0700271 private int mWidgetCountX, mWidgetCountY;
Winson Chungd2945262011-06-24 15:22:14 -0700272 private int mWidgetWidthGap, mWidgetHeightGap;
Winson Chung1ed747a2011-05-03 16:18:34 -0700273 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -0700274 private PagedViewCellLayout mWidgetSpacingLayout;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700275 private int mNumAppsPages;
276 private int mNumWidgetPages;
Winson Chung785d2eb2011-04-14 16:08:02 -0700277
Adam Cohen22f823d2011-09-01 17:22:18 -0700278 // Relating to the scroll and overscroll effects
279 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
Adam Cohencff6af82011-09-13 14:51:53 -0700280 private static float CAMERA_DISTANCE = 6500;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700281 private static float TRANSITION_SCALE_FACTOR = 0.74f;
Adam Cohencff6af82011-09-13 14:51:53 -0700282 private static float TRANSITION_PIVOT = 0.65f;
283 private static float TRANSITION_MAX_ROTATION = 22;
284 private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700285 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
Adam Cohen2591f6a2011-10-25 14:36:40 -0700286 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
Adam Cohen22f823d2011-09-01 17:22:18 -0700287
Winson Chungb44b5242011-06-13 11:32:14 -0700288 // Previews & outlines
289 ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
Winson Chung68e4c642011-11-10 15:48:25 -0800290 private static final int sPageSleepDelay = 200;
Winson Chung4b576be2011-04-27 17:40:20 -0700291
Adam Cohened66b2b2012-01-23 17:28:51 -0800292 private Runnable mInflateWidgetRunnable = null;
293 private Runnable mBindWidgetRunnable = null;
294 static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
Adam Cohen21a170b2012-05-30 15:17:06 -0700295 static final int WIDGET_PRELOAD_PENDING = 0;
296 static final int WIDGET_BOUND = 1;
297 static final int WIDGET_INFLATED = 2;
Adam Cohened66b2b2012-01-23 17:28:51 -0800298 int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
299 int mWidgetLoadingId = -1;
Adam Cohen1b36dc32012-02-13 19:27:37 -0800300 PendingAddWidgetInfo mCreateWidgetInfo = null;
Adam Cohen7a326642012-02-22 12:03:22 -0800301 private boolean mDraggingWidget = false;
Adam Cohened66b2b2012-01-23 17:28:51 -0800302
Winson Chungcb9ab4f2012-07-02 11:47:27 -0700303 private Toast mWidgetInstructionToast;
304
Michael Jurka39e5d172012-03-12 18:36:12 -0700305 // Deferral of loading widget previews during launcher transitions
306 private boolean mInTransition;
307 private ArrayList<AsyncTaskPageData> mDeferredSyncWidgetPageItems =
308 new ArrayList<AsyncTaskPageData>();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700309 private ArrayList<Runnable> mDeferredPrepareLoadWidgetPreviewsTasks =
310 new ArrayList<Runnable>();
Michael Jurka39e5d172012-03-12 18:36:12 -0700311
Michael Jurkadac85912012-05-18 15:04:49 -0700312 // Used for drawing shortcut previews
313 BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
314 PaintCache mCachedShortcutPreviewPaint = new PaintCache();
315 CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
316
317 // Used for drawing widget previews
318 CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
319 RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
320 RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
321 PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
322
Winson Chung785d2eb2011-04-14 16:08:02 -0700323 public AppsCustomizePagedView(Context context, AttributeSet attrs) {
324 super(context, attrs);
325 mLayoutInflater = LayoutInflater.from(context);
326 mPackageManager = context.getPackageManager();
Winson Chung785d2eb2011-04-14 16:08:02 -0700327 mApps = new ArrayList<ApplicationInfo>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700328 mWidgets = new ArrayList<Object>();
Winson Chung4dbea792011-05-05 14:21:32 -0700329 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
Winson Chungb44b5242011-06-13 11:32:14 -0700330 mCanvas = new Canvas();
331 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700332
333 // Save the default widget preview background
334 Resources resources = context.getResources();
Winson Chung70fc4382011-08-08 15:31:33 -0700335 mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
Winson Chung785d2eb2011-04-14 16:08:02 -0700336
Winson Chung6032e7e2011-11-08 15:47:17 -0800337 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
338 mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1);
339 mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700340 mWidgetWidthGap =
341 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
342 mWidgetHeightGap =
343 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700344 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
345 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
Winson Chung7d7541e2011-09-16 20:14:36 -0700346 mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0);
347 mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700348 a.recycle();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700349 mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
Winson Chung4b576be2011-04-27 17:40:20 -0700350
Winson Chung1ed747a2011-05-03 16:18:34 -0700351 // The padding on the non-matched dimension for the default widget preview icons
352 // (top + bottom)
Adam Cohen2591f6a2011-10-25 14:36:40 -0700353 mFadeInAdjacentScreens = false;
Svetoslav Ganov08055f62012-05-15 11:06:36 -0700354
355 // Unless otherwise specified this view is important for accessibility.
356 if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
357 setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
358 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700359 }
360
361 @Override
362 protected void init() {
363 super.init();
Winson Chung6a877402011-10-26 14:51:44 -0700364 mCenterPagesVertically = false;
Winson Chung785d2eb2011-04-14 16:08:02 -0700365
366 Context context = getContext();
367 Resources r = context.getResources();
368 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
369 }
370
Winson Chungf0ea4d32011-06-06 14:27:16 -0700371 @Override
Michael Jurkad771c962011-08-09 15:00:48 -0700372 protected void onUnhandledTap(MotionEvent ev) {
373 if (LauncherApplication.isScreenLarge()) {
Winson Chungde1af762011-07-21 16:44:07 -0700374 // Dismiss AppsCustomize if we tap
375 mLauncher.showWorkspace(true);
376 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700377 }
378
Winson Chung5afbf7b2011-07-25 11:53:08 -0700379 /** Returns the item index of the center item on this page so that we can restore to this
380 * item index when we rotate. */
381 private int getMiddleComponentIndexOnCurrentPage() {
382 int i = -1;
383 if (getPageCount() > 0) {
384 int currentPage = getCurrentPage();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700385 if (currentPage < mNumAppsPages) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700386 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
Winson Chung5afbf7b2011-07-25 11:53:08 -0700387 PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
388 int numItemsPerPage = mCellCountX * mCellCountY;
389 int childCount = childrenLayout.getChildCount();
390 if (childCount > 0) {
391 i = (currentPage * numItemsPerPage) + (childCount / 2);
Adam Cohen0cd3b642011-10-14 14:58:00 -0700392 }
393 } else {
394 int numApps = mApps.size();
Adam Cohen22f823d2011-09-01 17:22:18 -0700395 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
Winson Chung5afbf7b2011-07-25 11:53:08 -0700396 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
397 int childCount = layout.getChildCount();
398 if (childCount > 0) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700399 i = numApps +
400 ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
401 }
Winson Chung5afbf7b2011-07-25 11:53:08 -0700402 }
403 }
404 return i;
405 }
406
407 /** Get the index of the item to restore to if we need to restore the current page. */
408 int getSaveInstanceStateIndex() {
409 if (mSaveInstanceStateItemIndex == -1) {
410 mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
411 }
412 return mSaveInstanceStateItemIndex;
413 }
414
415 /** Returns the page in the current orientation which is expected to contain the specified
416 * item index. */
417 int getPageForComponent(int index) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700418 if (index < 0) return 0;
419
420 if (index < mApps.size()) {
Winson Chung5afbf7b2011-07-25 11:53:08 -0700421 int numItemsPerPage = mCellCountX * mCellCountY;
422 return (index / numItemsPerPage);
Adam Cohen0cd3b642011-10-14 14:58:00 -0700423 } else {
Winson Chung5afbf7b2011-07-25 11:53:08 -0700424 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700425 return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
426 }
Winson Chung5afbf7b2011-07-25 11:53:08 -0700427 }
428
Winson Chung5afbf7b2011-07-25 11:53:08 -0700429 /** Restores the page for an item at the specified index */
430 void restorePageForIndex(int index) {
431 if (index < 0) return;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700432 mSaveInstanceStateItemIndex = index;
Winson Chung5afbf7b2011-07-25 11:53:08 -0700433 }
434
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700435 private void updatePageCounts() {
436 mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
437 (float) (mWidgetCountX * mWidgetCountY));
438 mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
439 }
440
Winson Chungf0ea4d32011-06-06 14:27:16 -0700441 protected void onDataReady(int width, int height) {
442 // Note that we transpose the counts in portrait so that we get a similar layout
443 boolean isLandscape = getResources().getConfiguration().orientation ==
444 Configuration.ORIENTATION_LANDSCAPE;
445 int maxCellCountX = Integer.MAX_VALUE;
446 int maxCellCountY = Integer.MAX_VALUE;
447 if (LauncherApplication.isScreenLarge()) {
448 maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
449 LauncherModel.getCellCountY());
450 maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
451 LauncherModel.getCellCountX());
452 }
Winson Chung6032e7e2011-11-08 15:47:17 -0800453 if (mMaxAppCellCountX > -1) {
454 maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX);
455 }
456 if (mMaxAppCellCountY > -1) {
457 maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY);
458 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700459
460 // Now that the data is ready, we can calculate the content width, the number of cells to
461 // use for each page
462 mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
463 mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
464 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
465 mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
466 mCellCountX = mWidgetSpacingLayout.getCellCountX();
467 mCellCountY = mWidgetSpacingLayout.getCellCountY();
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700468 updatePageCounts();
Winson Chung5a808352011-06-27 19:08:49 -0700469
Winson Chungdb1138b2011-06-30 14:39:35 -0700470 // Force a measure to update recalculate the gaps
471 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
472 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
473 mWidgetSpacingLayout.measure(widthSpec, heightSpec);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700474 mContentWidth = mWidgetSpacingLayout.getContentWidth();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700475
Michael Jurkae326f182011-11-21 14:05:46 -0800476 AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost();
477 final boolean hostIsTransitioning = host.isTransitioning();
478
Adam Cohen0cd3b642011-10-14 14:58:00 -0700479 // Restore the page
480 int page = getPageForComponent(mSaveInstanceStateItemIndex);
Michael Jurkae326f182011-11-21 14:05:46 -0800481 invalidatePageData(Math.max(0, page), hostIsTransitioning);
Winson Chung7d7541e2011-09-16 20:14:36 -0700482
Winson Chung3f4e1422011-11-17 14:58:51 -0800483 // Show All Apps cling if we are finished transitioning, otherwise, we will try again when
484 // the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be
485 // returned while animating)
Michael Jurkae326f182011-11-21 14:05:46 -0800486 if (!hostIsTransitioning) {
Winson Chung3f4e1422011-11-17 14:58:51 -0800487 post(new Runnable() {
488 @Override
489 public void run() {
490 showAllAppsCling();
491 }
492 });
493 }
494 }
Winson Chung7d7541e2011-09-16 20:14:36 -0700495
Winson Chung3f4e1422011-11-17 14:58:51 -0800496 void showAllAppsCling() {
Winson Chung9802ac92012-06-08 16:01:58 -0700497 if (!mHasShownAllAppsCling && isDataReady()) {
Winson Chung3f4e1422011-11-17 14:58:51 -0800498 mHasShownAllAppsCling = true;
499 // Calculate the position for the cling punch through
500 int[] offset = new int[2];
501 int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
502 mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
503 // PagedViews are centered horizontally but top aligned
504 pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 +
505 offset[0];
506 pos[1] += offset[1];
507 mLauncher.showFirstRunAllAppsCling(pos);
508 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700509 }
510
511 @Override
512 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
513 int width = MeasureSpec.getSize(widthMeasureSpec);
514 int height = MeasureSpec.getSize(heightMeasureSpec);
515 if (!isDataReady()) {
Winson Chung9802ac92012-06-08 16:01:58 -0700516 if (!mApps.isEmpty() && !mWidgets.isEmpty()) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700517 setDataIsReady();
518 setMeasuredDimension(width, height);
519 onDataReady(width, height);
520 }
521 }
522
523 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
524 }
525
Winson Chung785d2eb2011-04-14 16:08:02 -0700526 public void onPackagesUpdated() {
Winson Chung1ed747a2011-05-03 16:18:34 -0700527 // Get the list of widgets and shortcuts
528 mWidgets.clear();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700529 List<AppWidgetProviderInfo> widgets =
530 AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700531 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
532 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
Michael Jurkadbc1f652011-11-10 17:02:56 -0800533 for (AppWidgetProviderInfo widget : widgets) {
534 if (widget.minWidth > 0 && widget.minHeight > 0) {
Winson Chunga5c96362012-04-12 14:04:41 -0700535 // Ensure that all widgets we show can be added on a workspace of this size
Adam Cohen2f093b62012-04-30 18:59:53 -0700536 int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
537 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
Winson Chunga5c96362012-04-12 14:04:41 -0700538 int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
539 int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
Adam Cohen336d4912012-04-13 17:57:11 -0700540 if (minSpanX <= LauncherModel.getCellCountX() &&
541 minSpanY <= LauncherModel.getCellCountY()) {
Winson Chunga5c96362012-04-12 14:04:41 -0700542 mWidgets.add(widget);
Winson Chungfd39d8e2012-06-05 10:12:48 -0700543 } else {
544 Log.e(TAG, "Widget " + widget.provider + " can not fit on this device (" +
545 widget.minWidth + ", " + widget.minHeight + ")");
Winson Chunga5c96362012-04-12 14:04:41 -0700546 }
Michael Jurkadbc1f652011-11-10 17:02:56 -0800547 } else {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700548 Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
Michael Jurkadbc1f652011-11-10 17:02:56 -0800549 widget.minWidth + ", " + widget.minHeight + ")");
550 }
551 }
Winson Chung6a3fd3f2011-08-02 14:03:26 -0700552 mWidgets.addAll(shortcuts);
553 Collections.sort(mWidgets,
554 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700555 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -0700556 invalidateOnDataChange();
Winson Chung4b576be2011-04-27 17:40:20 -0700557 }
558
559 @Override
560 public void onClick(View v) {
Adam Cohenfc53cd22011-07-20 15:45:11 -0700561 // When we have exited all apps or are in transition, disregard clicks
562 if (!mLauncher.isAllAppsCustomizeOpen() ||
563 mLauncher.getWorkspace().isSwitchingState()) return;
564
Winson Chung4b576be2011-04-27 17:40:20 -0700565 if (v instanceof PagedViewIcon) {
566 // Animate some feedback to the click
567 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
Winson Chung3b187b82012-01-30 15:11:08 -0800568
569 // Lock the drawable state to pressed until we return to Launcher
570 if (mPressedIcon != null) {
571 mPressedIcon.lockDrawableState();
572 }
Winson Chungc7450e32012-04-17 17:34:08 -0700573
Winson Chung18f41f82012-05-09 13:28:10 -0700574 // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
575 // to be consistent. So re-enable the flag here, and we will re-disable it as necessary
576 // when Launcher resumes and we are still in AllApps.
577 mLauncher.updateWallpaperVisibility(true);
Winson Chungc7450e32012-04-17 17:34:08 -0700578 mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
579
Winson Chung4b576be2011-04-27 17:40:20 -0700580 } else if (v instanceof PagedViewWidget) {
Winson Chungd2e87b32011-06-02 10:53:07 -0700581 // Let the user know that they have to long press to add a widget
Winson Chungcb9ab4f2012-07-02 11:47:27 -0700582 if (mWidgetInstructionToast != null) {
583 mWidgetInstructionToast.cancel();
584 }
585 mWidgetInstructionToast = Toast.makeText(getContext(),R.string.long_press_widget_to_add,
586 Toast.LENGTH_SHORT);
587 mWidgetInstructionToast.show();
Winson Chung46af2e82011-05-09 16:00:53 -0700588
Winson Chungd2e87b32011-06-02 10:53:07 -0700589 // Create a little animation to show that the widget can move
590 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
591 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
Michael Jurka2ecf9952012-06-18 12:52:28 -0700592 AnimatorSet bounce = LauncherAnimUtils.createAnimatorSet();
593 ValueAnimator tyuAnim = LauncherAnimUtils.ofFloat(p, "translationY", offsetY);
Winson Chungd2e87b32011-06-02 10:53:07 -0700594 tyuAnim.setDuration(125);
Michael Jurka2ecf9952012-06-18 12:52:28 -0700595 ValueAnimator tydAnim = LauncherAnimUtils.ofFloat(p, "translationY", 0f);
Winson Chungd2e87b32011-06-02 10:53:07 -0700596 tydAnim.setDuration(100);
597 bounce.play(tyuAnim).before(tydAnim);
598 bounce.setInterpolator(new AccelerateInterpolator());
599 bounce.start();
Winson Chung4b576be2011-04-27 17:40:20 -0700600 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700601 }
602
Winson Chungc6f10b92011-11-14 11:39:07 -0800603 public boolean onKey(View v, int keyCode, KeyEvent event) {
604 return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event);
605 }
606
Winson Chung785d2eb2011-04-14 16:08:02 -0700607 /*
608 * PagedViewWithDraggableItems implementation
609 */
610 @Override
611 protected void determineDraggingStart(android.view.MotionEvent ev) {
612 // Disable dragging by pulling an app down for now.
613 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700614
Winson Chung4b576be2011-04-27 17:40:20 -0700615 private void beginDraggingApplication(View v) {
Adam Cohenac8c8762011-07-13 11:15:27 -0700616 mLauncher.getWorkspace().onDragStartedWithItem(v);
617 mLauncher.getWorkspace().beginDragShared(v, this);
Winson Chung4b576be2011-04-27 17:40:20 -0700618 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700619
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700620 private void preloadWidget(final PendingAddWidgetInfo info) {
Adam Cohened66b2b2012-01-23 17:28:51 -0800621 final AppWidgetProviderInfo pInfo = info.info;
622 if (pInfo.configure != null) {
623 return;
624 }
625
Adam Cohen21a170b2012-05-30 15:17:06 -0700626 mWidgetCleanupState = WIDGET_PRELOAD_PENDING;
Adam Cohened66b2b2012-01-23 17:28:51 -0800627 mBindWidgetRunnable = new Runnable() {
628 @Override
629 public void run() {
630 mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
Michael Jurka8b805b12012-04-18 14:23:14 -0700631 if (AppWidgetManager.getInstance(mLauncher)
632 .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
633 mWidgetCleanupState = WIDGET_BOUND;
634 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800635 }
636 };
637 post(mBindWidgetRunnable);
638
639 mInflateWidgetRunnable = new Runnable() {
640 @Override
641 public void run() {
Michael Jurka8b805b12012-04-18 14:23:14 -0700642 AppWidgetHostView hostView = mLauncher.
643 getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800644 info.boundWidget = hostView;
645 mWidgetCleanupState = WIDGET_INFLATED;
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800646 hostView.setVisibility(INVISIBLE);
Adam Cohen1f362702012-04-04 14:58:12 -0700647 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
648 info.spanY, info, false);
649
650 // We want the first widget layout to be the correct size. This will be important
651 // for width size reporting to the AppWidgetManager.
652 DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
653 unScaledSize[1]);
654 lp.x = lp.y = 0;
655 lp.customPosition = true;
656 hostView.setLayoutParams(lp);
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800657 mLauncher.getDragLayer().addView(hostView);
Adam Cohened66b2b2012-01-23 17:28:51 -0800658 }
659 };
660 post(mInflateWidgetRunnable);
661 }
662
663 @Override
664 public void onShortPress(View v) {
665 // We are anticipating a long press, and we use this time to load bind and instantiate
666 // the widget. This will need to be cleaned up if it turns out no long press occurs.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700667 if (mCreateWidgetInfo != null) {
668 // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
669 cleanupWidgetPreloading(false);
670 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800671 mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700672 preloadWidget(mCreateWidgetInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800673 }
674
Adam Cohen0e56cc92012-05-11 15:57:05 -0700675 private void cleanupWidgetPreloading(boolean widgetWasAdded) {
676 if (!widgetWasAdded) {
677 // If the widget was not added, we may need to do further cleanup.
678 PendingAddWidgetInfo info = mCreateWidgetInfo;
679 mCreateWidgetInfo = null;
Adam Cohen21a170b2012-05-30 15:17:06 -0700680
681 if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700682 // We never did any preloading, so just remove pending callbacks to do so
683 removeCallbacks(mBindWidgetRunnable);
684 removeCallbacks(mInflateWidgetRunnable);
685 } else if (mWidgetCleanupState == WIDGET_BOUND) {
686 // Delete the widget id which was allocated
687 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700688 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
689 }
690
691 // We never got around to inflating the widget, so remove the callback to do so.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700692 removeCallbacks(mInflateWidgetRunnable);
693 } else if (mWidgetCleanupState == WIDGET_INFLATED) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700694 // Delete the widget id which was allocated
695 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700696 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
697 }
698
Adam Cohen0e56cc92012-05-11 15:57:05 -0700699 // The widget was inflated and added to the DragLayer -- remove it.
700 AppWidgetHostView widget = info.boundWidget;
701 mLauncher.getDragLayer().removeView(widget);
702 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800703 }
704 mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
705 mWidgetLoadingId = -1;
Adam Cohen0e56cc92012-05-11 15:57:05 -0700706 mCreateWidgetInfo = null;
707 PagedViewWidget.resetShortPressTarget();
Adam Cohened66b2b2012-01-23 17:28:51 -0800708 }
709
Adam Cohen7a326642012-02-22 12:03:22 -0800710 @Override
711 public void cleanUpShortPress(View v) {
712 if (!mDraggingWidget) {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700713 cleanupWidgetPreloading(false);
Adam Cohen7a326642012-02-22 12:03:22 -0800714 }
715 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800716
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700717 private boolean beginDraggingWidget(View v) {
Adam Cohen7a326642012-02-22 12:03:22 -0800718 mDraggingWidget = true;
Winson Chung4b576be2011-04-27 17:40:20 -0700719 // Get the widget preview as the drag representation
720 ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
Winson Chung1ed747a2011-05-03 16:18:34 -0700721 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700722
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700723 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
724 // we abort the drag.
725 if (image.getDrawable() == null) {
726 mDraggingWidget = false;
727 return false;
728 }
729
Winson Chung4b576be2011-04-27 17:40:20 -0700730 // Compose the drag image
Winson Chung1120e032011-11-22 16:11:31 -0800731 Bitmap preview;
732 Bitmap outline;
Winson Chung72d59842012-02-22 13:51:36 -0800733 float scale = 1f;
Winson Chung1ed747a2011-05-03 16:18:34 -0700734 if (createItemInfo instanceof PendingAddWidgetInfo) {
Adam Cohen92478922012-05-17 13:43:29 -0700735 // This can happen in some weird cases involving multi-touch. We can't start dragging
736 // the widget if this is null, so we break out.
737 if (mCreateWidgetInfo == null) {
738 return false;
739 }
740
Adam Cohen1b36dc32012-02-13 19:27:37 -0800741 PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
742 createItemInfo = createWidgetInfo;
Adam Cohen1f362702012-04-04 14:58:12 -0700743 int spanX = createItemInfo.spanX;
744 int spanY = createItemInfo.spanY;
745 int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
746 createWidgetInfo, true);
Winson Chung1ed747a2011-05-03 16:18:34 -0700747
Winson Chung72d59842012-02-22 13:51:36 -0800748 FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
749 float minScale = 1.25f;
Michael Jurkadac85912012-05-18 15:04:49 -0700750 int maxWidth, maxHeight;
751 maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
752 maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
Winson Chung1120e032011-11-22 16:11:31 -0800753 preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
Michael Jurkadac85912012-05-18 15:04:49 -0700754 createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);
Winson Chung72d59842012-02-22 13:51:36 -0800755
756 // Determine the image view drawable scale relative to the preview
757 float[] mv = new float[9];
758 Matrix m = new Matrix();
759 m.setRectToRect(
760 new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
761 new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
762 (float) previewDrawable.getIntrinsicHeight()),
763 Matrix.ScaleToFit.START);
764 m.getValues(mv);
765 scale = (float) mv[0];
Winson Chung1ed747a2011-05-03 16:18:34 -0700766 } else {
Michael Jurkadac85912012-05-18 15:04:49 -0700767 PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
768 Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
769 preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
770 icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
771
Winson Chung1120e032011-11-22 16:11:31 -0800772 mCanvas.setBitmap(preview);
Michael Jurka4ca39222012-05-15 17:18:34 -0700773 mCanvas.save();
Michael Jurkadac85912012-05-18 15:04:49 -0700774 renderDrawableToBitmap(icon, preview, 0, 0,
775 icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
Michael Jurka4ca39222012-05-15 17:18:34 -0700776 mCanvas.restore();
Adam Cohenaaf473c2011-08-03 12:02:47 -0700777 mCanvas.setBitmap(null);
Winson Chung1ed747a2011-05-03 16:18:34 -0700778 createItemInfo.spanX = createItemInfo.spanY = 1;
779 }
Winson Chung4b576be2011-04-27 17:40:20 -0700780
Michael Jurka8c3339b2012-06-14 16:18:21 -0700781 // Don't clip alpha values for the drag outline if we're using the default widget preview
782 boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo &&
783 (((PendingAddWidgetInfo) createItemInfo).previewImage == 0));
Peter Ng8db70002011-10-25 15:40:08 -0700784
Winson Chung1120e032011-11-22 16:11:31 -0800785 // Save the preview for the outline generation, then dim the preview
786 outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
787 false);
Winson Chung1120e032011-11-22 16:11:31 -0800788
Winson Chung4b576be2011-04-27 17:40:20 -0700789 // Start the drag
Winson Chung641d71d2012-04-26 15:58:01 -0700790 mLauncher.lockScreenOrientation();
Michael Jurka8c3339b2012-06-14 16:18:21 -0700791 mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, clipAlpha);
Winson Chung1120e032011-11-22 16:11:31 -0800792 mDragController.startDrag(image, preview, this, createItemInfo,
Winson Chung72d59842012-02-22 13:51:36 -0800793 DragController.DRAG_ACTION_COPY, null, scale);
Winson Chung1120e032011-11-22 16:11:31 -0800794 outline.recycle();
795 preview.recycle();
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700796 return true;
Winson Chung4b576be2011-04-27 17:40:20 -0700797 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800798
Winson Chung4b576be2011-04-27 17:40:20 -0700799 @Override
Adam Cohened66b2b2012-01-23 17:28:51 -0800800 protected boolean beginDragging(final View v) {
Winson Chung4b576be2011-04-27 17:40:20 -0700801 if (!super.beginDragging(v)) return false;
802
803 if (v instanceof PagedViewIcon) {
804 beginDraggingApplication(v);
805 } else if (v instanceof PagedViewWidget) {
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700806 if (!beginDraggingWidget(v)) {
807 return false;
808 }
Winson Chung4b576be2011-04-27 17:40:20 -0700809 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800810
811 // We delay entering spring-loaded mode slightly to make sure the UI
812 // thready is free of any work.
813 postDelayed(new Runnable() {
814 @Override
815 public void run() {
Adam Cohen1b36dc32012-02-13 19:27:37 -0800816 // We don't enter spring-loaded mode if the drag has been cancelled
817 if (mLauncher.getDragController().isDragging()) {
818 // Dismiss the cling
819 mLauncher.dismissAllAppsCling(null);
Adam Cohened66b2b2012-01-23 17:28:51 -0800820
Adam Cohen1b36dc32012-02-13 19:27:37 -0800821 // Reset the alpha on the dragged icon before we drag
822 resetDrawableState();
Adam Cohened66b2b2012-01-23 17:28:51 -0800823
Adam Cohen1b36dc32012-02-13 19:27:37 -0800824 // Go into spring loaded mode (must happen before we startDrag())
825 mLauncher.enterSpringLoadedDragMode();
826 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800827 }
Winson Chung72d59842012-02-22 13:51:36 -0800828 }, 150);
Adam Cohened66b2b2012-01-23 17:28:51 -0800829
Winson Chung785d2eb2011-04-14 16:08:02 -0700830 return true;
831 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800832
Winson Chunga48487a2012-03-20 16:19:37 -0700833 /**
834 * Clean up after dragging.
835 *
836 * @param target where the item was dragged to (can be null if the item was flung)
837 */
838 private void endDragging(View target, boolean isFlingToDelete, boolean success) {
Winson Chunga48487a2012-03-20 16:19:37 -0700839 if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
Adam Cohend4d7aa52011-07-19 21:47:37 -0700840 !(target instanceof DeleteDropTarget))) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700841 // Exit spring loaded mode if we have not successfully dropped or have not handled the
842 // drop in Workspace
843 mLauncher.exitSpringLoadedDragMode();
844 }
Winson Chung4b919f82012-05-01 10:44:08 -0700845 mLauncher.unlockScreenOrientation(false);
Winson Chung785d2eb2011-04-14 16:08:02 -0700846 }
847
Winson Chung785d2eb2011-04-14 16:08:02 -0700848 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700849 public View getContent() {
850 return null;
851 }
852
853 @Override
854 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700855 mInTransition = true;
856 if (toWorkspace) {
857 cancelAllTasks();
858 }
859 }
860
861 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700862 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700863 }
864
865 @Override
866 public void onLauncherTransitionStep(Launcher l, float t) {
867 }
868
869 @Override
870 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
871 mInTransition = false;
872 for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
873 onSyncWidgetPageItems(d);
874 }
875 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700876 for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) {
877 r.run();
878 }
879 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Michael Jurka5e368ff2012-05-14 23:13:15 -0700880 mForceDrawAllChildrenNextFrame = !toWorkspace;
Michael Jurka39e5d172012-03-12 18:36:12 -0700881 }
882
883 @Override
Winson Chunga48487a2012-03-20 16:19:37 -0700884 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
885 boolean success) {
886 // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
887 if (isFlingToDelete) return;
888
889 endDragging(target, false, success);
Winson Chungfc79c802011-05-02 13:35:34 -0700890
891 // Display an error message if the drag failed due to there not being enough space on the
892 // target layout we were dropping on.
893 if (!success) {
894 boolean showOutOfSpaceMessage = false;
895 if (target instanceof Workspace) {
896 int currentScreen = mLauncher.getCurrentWorkspaceScreen();
897 Workspace workspace = (Workspace) target;
898 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
Adam Cohenc0dcf592011-06-01 15:30:43 -0700899 ItemInfo itemInfo = (ItemInfo) d.dragInfo;
Winson Chungfc79c802011-05-02 13:35:34 -0700900 if (layout != null) {
901 layout.calculateSpans(itemInfo);
902 showOutOfSpaceMessage =
903 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
904 }
905 }
Winson Chungfc79c802011-05-02 13:35:34 -0700906 if (showOutOfSpaceMessage) {
Winson Chung93eef082012-03-23 15:59:27 -0700907 mLauncher.showOutOfSpaceMessage(false);
Winson Chungfc79c802011-05-02 13:35:34 -0700908 }
Adam Cohen7a326642012-02-22 12:03:22 -0800909
Winson Chung7bd1bbb2012-02-13 18:29:29 -0800910 d.deferDragViewCleanupPostAnimation = false;
Winson Chungfc79c802011-05-02 13:35:34 -0700911 }
Adam Cohen0e56cc92012-05-11 15:57:05 -0700912 cleanupWidgetPreloading(success);
Adam Cohen7a326642012-02-22 12:03:22 -0800913 mDraggingWidget = false;
Winson Chung785d2eb2011-04-14 16:08:02 -0700914 }
915
Winson Chunga48487a2012-03-20 16:19:37 -0700916 @Override
917 public void onFlingToDeleteCompleted() {
918 // We just dismiss the drag when we fling, so cleanup here
919 endDragging(null, true, true);
Adam Cohen0e56cc92012-05-11 15:57:05 -0700920 cleanupWidgetPreloading(false);
Winson Chunga48487a2012-03-20 16:19:37 -0700921 mDraggingWidget = false;
922 }
923
924 @Override
Winson Chung043f2af2012-03-01 16:09:54 -0800925 public boolean supportsFlingToDelete() {
Winson Chunga48487a2012-03-20 16:19:37 -0700926 return true;
Winson Chung043f2af2012-03-01 16:09:54 -0800927 }
928
Winson Chung7f0acdd2011-09-19 18:34:19 -0700929 @Override
930 protected void onDetachedFromWindow() {
931 super.onDetachedFromWindow();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700932 cancelAllTasks();
933 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700934
Michael Jurkae326f182011-11-21 14:05:46 -0800935 public void clearAllWidgetPages() {
936 cancelAllTasks();
937 int count = getChildCount();
938 for (int i = 0; i < count; i++) {
939 View v = getPageAt(i);
940 if (v instanceof PagedViewGridLayout) {
941 ((PagedViewGridLayout) v).removeAllViewsOnPage();
942 mDirtyPageContent.set(i, true);
943 }
944 }
945 }
946
Adam Cohen0cd3b642011-10-14 14:58:00 -0700947 private void cancelAllTasks() {
Winson Chung7f0acdd2011-09-19 18:34:19 -0700948 // Clean up all the async tasks
949 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
950 while (iter.hasNext()) {
951 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
952 task.cancel(false);
953 iter.remove();
Michael Jurka39e5d172012-03-12 18:36:12 -0700954 mDirtyPageContent.set(task.page, true);
Winson Chung7ce99852012-05-24 17:34:08 -0700955
956 // We've already preallocated the views for the data to load into, so clear them as well
957 View v = getPageAt(task.page);
958 if (v instanceof PagedViewGridLayout) {
959 ((PagedViewGridLayout) v).removeAllViewsOnPage();
960 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700961 }
Winson Chung83687b12012-04-25 16:01:01 -0700962 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700963 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Winson Chung7f0acdd2011-09-19 18:34:19 -0700964 }
965
Winson Chung785d2eb2011-04-14 16:08:02 -0700966 public void setContentType(ContentType type) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700967 if (type == ContentType.Widgets) {
968 invalidatePageData(mNumAppsPages, true);
969 } else if (type == ContentType.Applications) {
970 invalidatePageData(0, true);
971 }
Winson Chungb44b5242011-06-13 11:32:14 -0700972 }
973
Adam Cohen0cd3b642011-10-14 14:58:00 -0700974 protected void snapToPage(int whichPage, int delta, int duration) {
975 super.snapToPage(whichPage, delta, duration);
976 updateCurrentTab(whichPage);
Winson Chung68e4c642011-11-10 15:48:25 -0800977
978 // Update the thread priorities given the direction lookahead
979 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
980 while (iter.hasNext()) {
981 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -0700982 int pageIndex = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -0800983 if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
984 (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
985 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
986 } else {
987 task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
988 }
989 }
Adam Cohen0cd3b642011-10-14 14:58:00 -0700990 }
991
992 private void updateCurrentTab(int currentPage) {
993 AppsCustomizeTabHost tabHost = getTabHost();
Winson Chungc6f10b92011-11-14 11:39:07 -0800994 if (tabHost != null) {
995 String tag = tabHost.getCurrentTabTag();
996 if (tag != null) {
997 if (currentPage >= mNumAppsPages &&
998 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
999 tabHost.setCurrentTabFromContent(ContentType.Widgets);
1000 } else if (currentPage < mNumAppsPages &&
1001 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1002 tabHost.setCurrentTabFromContent(ContentType.Applications);
1003 }
Winson Chung6a8103c2011-10-21 11:08:32 -07001004 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001005 }
1006 }
1007
Winson Chung785d2eb2011-04-14 16:08:02 -07001008 /*
1009 * Apps PagedView implementation
1010 */
Winson Chung63257c12011-05-05 17:06:13 -07001011 private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1012 int childCount = layout.getChildCount();
1013 for (int i = 0; i < childCount; ++i) {
1014 layout.getChildAt(i).setVisibility(visibility);
1015 }
1016 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001017 private void setupPage(PagedViewCellLayout layout) {
1018 layout.setCellCount(mCellCountX, mCellCountY);
1019 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1020 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1021 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1022
Winson Chung63257c12011-05-05 17:06:13 -07001023 // Note: We force a measure here to get around the fact that when we do layout calculations
1024 // immediately after syncing, we don't have a proper width. That said, we already know the
1025 // expected page width, so we can actually optimize by hiding all the TextView-based
1026 // children that are expensive to measure, and let that happen naturally later.
1027 setVisibilityOnChildren(layout, View.GONE);
Winson Chungdb1138b2011-06-30 14:39:35 -07001028 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001029 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -07001030 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -07001031 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -07001032 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -07001033 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001034
Winson Chungf314b0e2011-08-16 11:54:27 -07001035 public void syncAppsPageItems(int page, boolean immediate) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001036 // ensure that we have the right number of items on the pages
Winson Chung785d2eb2011-04-14 16:08:02 -07001037 int numCells = mCellCountX * mCellCountY;
1038 int startIndex = page * numCells;
1039 int endIndex = Math.min(startIndex + numCells, mApps.size());
Adam Cohen22f823d2011-09-01 17:22:18 -07001040 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
Winson Chung875de7e2011-06-28 14:25:17 -07001041
Winson Chung785d2eb2011-04-14 16:08:02 -07001042 layout.removeAllViewsOnPage();
Winson Chungb44b5242011-06-13 11:32:14 -07001043 ArrayList<Object> items = new ArrayList<Object>();
1044 ArrayList<Bitmap> images = new ArrayList<Bitmap>();
Winson Chung785d2eb2011-04-14 16:08:02 -07001045 for (int i = startIndex; i < endIndex; ++i) {
1046 ApplicationInfo info = mApps.get(i);
1047 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1048 R.layout.apps_customize_application, layout, false);
Winson Chunge4e50662012-01-23 14:45:13 -08001049 icon.applyFromApplicationInfo(info, true, this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001050 icon.setOnClickListener(this);
1051 icon.setOnLongClickListener(this);
1052 icon.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001053 icon.setOnKeyListener(this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001054
1055 int index = i - startIndex;
1056 int x = index % mCellCountX;
1057 int y = index / mCellCountX;
Winson Chung6a70e9f2011-05-17 16:24:49 -07001058 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
Winson Chungb44b5242011-06-13 11:32:14 -07001059
1060 items.add(info);
1061 images.add(info.iconBitmap);
Winson Chung785d2eb2011-04-14 16:08:02 -07001062 }
Winson Chungf0ea4d32011-06-06 14:27:16 -07001063
Winson Chungf0ea4d32011-06-06 14:27:16 -07001064 layout.createHardwareLayers();
Winson Chung785d2eb2011-04-14 16:08:02 -07001065 }
Winson Chungb44b5242011-06-13 11:32:14 -07001066
1067 /**
Winson Chung68e4c642011-11-10 15:48:25 -08001068 * A helper to return the priority for loading of the specified widget page.
1069 */
1070 private int getWidgetPageLoadPriority(int page) {
1071 // If we are snapping to another page, use that index as the target page index
1072 int toPage = mCurrentPage;
1073 if (mNextPage > -1) {
1074 toPage = mNextPage;
1075 }
1076
1077 // We use the distance from the target page as an initial guess of priority, but if there
1078 // are no pages of higher priority than the page specified, then bump up the priority of
1079 // the specified page.
1080 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1081 int minPageDiff = Integer.MAX_VALUE;
1082 while (iter.hasNext()) {
1083 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001084 minPageDiff = Math.abs(task.page - toPage);
Winson Chung68e4c642011-11-10 15:48:25 -08001085 }
1086
1087 int rawPageDiff = Math.abs(page - toPage);
1088 return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1089 }
1090 /**
Winson Chungb44b5242011-06-13 11:32:14 -07001091 * Return the appropriate thread priority for loading for a given page (we give the current
1092 * page much higher priority)
1093 */
1094 private int getThreadPriorityForPage(int page) {
1095 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
Winson Chung68e4c642011-11-10 15:48:25 -08001096 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001097 if (pageDiff <= 0) {
Winson Chung68e4c642011-11-10 15:48:25 -08001098 return Process.THREAD_PRIORITY_LESS_FAVORABLE;
Winson Chungb44b5242011-06-13 11:32:14 -07001099 } else if (pageDiff <= 1) {
Winson Chung68e4c642011-11-10 15:48:25 -08001100 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001101 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001102 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001103 }
1104 }
Winson Chungf314b0e2011-08-16 11:54:27 -07001105 private int getSleepForPage(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001106 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungf314b0e2011-08-16 11:54:27 -07001107 return Math.max(0, pageDiff * sPageSleepDelay);
1108 }
Winson Chungb44b5242011-06-13 11:32:14 -07001109 /**
1110 * Creates and executes a new AsyncTask to load a page of widget previews.
1111 */
1112 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
Winson Chungd2945262011-06-24 15:22:14 -07001113 int cellWidth, int cellHeight, int cellCountX) {
Winson Chung68e4c642011-11-10 15:48:25 -08001114
Winson Chungb44b5242011-06-13 11:32:14 -07001115 // Prune all tasks that are no longer needed
1116 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1117 while (iter.hasNext()) {
1118 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001119 int taskPage = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -08001120 if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1121 taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
Winson Chungb44b5242011-06-13 11:32:14 -07001122 task.cancel(false);
1123 iter.remove();
1124 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001125 task.setThreadPriority(getThreadPriorityForPage(taskPage));
Winson Chungb44b5242011-06-13 11:32:14 -07001126 }
1127 }
1128
Winson Chungf314b0e2011-08-16 11:54:27 -07001129 // We introduce a slight delay to order the loading of side pages so that we don't thrash
Michael Jurka39e5d172012-03-12 18:36:12 -07001130 final int sleepMs = getSleepForPage(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001131 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
Michael Jurka038f9d82011-11-03 13:50:45 -07001132 new AsyncTaskCallback() {
Winson Chungb44b5242011-06-13 11:32:14 -07001133 @Override
1134 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001135 try {
Winson Chung09945932011-09-20 14:22:40 -07001136 try {
1137 Thread.sleep(sleepMs);
1138 } catch (Exception e) {}
1139 loadWidgetPreviewsInBackground(task, data);
1140 } finally {
1141 if (task.isCancelled()) {
1142 data.cleanup(true);
1143 }
1144 }
Winson Chungb44b5242011-06-13 11:32:14 -07001145 }
1146 },
1147 new AsyncTaskCallback() {
1148 @Override
1149 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001150 mRunningTasks.remove(task);
1151 if (task.isCancelled()) return;
1152 // do cleanup inside onSyncWidgetPageItems
1153 onSyncWidgetPageItems(data);
Winson Chungb44b5242011-06-13 11:32:14 -07001154 }
Winson Chung09945932011-09-20 14:22:40 -07001155 });
Winson Chungb44b5242011-06-13 11:32:14 -07001156
1157 // Ensure that the task is appropriately prioritized and runs in parallel
Adam Cohen0cd3b642011-10-14 14:58:00 -07001158 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
Winson Chung875de7e2011-06-28 14:25:17 -07001159 AsyncTaskPageData.Type.LoadWidgetPreviewData);
Michael Jurka39e5d172012-03-12 18:36:12 -07001160 t.setThreadPriority(getThreadPriorityForPage(page));
Winson Chungb44b5242011-06-13 11:32:14 -07001161 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1162 mRunningTasks.add(t);
1163 }
Winson Chungb44b5242011-06-13 11:32:14 -07001164
Winson Chung785d2eb2011-04-14 16:08:02 -07001165 /*
1166 * Widgets PagedView implementation
1167 */
Winson Chung4e6a9762011-05-09 11:56:34 -07001168 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001169 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1170 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -07001171
1172 // Note: We force a measure here to get around the fact that when we do layout calculations
Winson Chungd52f3d82011-07-12 14:29:11 -07001173 // immediately after syncing, we don't have a proper width.
Winson Chung63257c12011-05-05 17:06:13 -07001174 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1175 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001176 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -07001177 layout.measure(widthSpec, heightSpec);
Winson Chung785d2eb2011-04-14 16:08:02 -07001178 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001179
Winson Chung5fc72b32011-10-11 17:53:58 -07001180 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurkadac85912012-05-18 15:04:49 -07001181 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
Winson Chung70fc4382011-08-08 15:31:33 -07001182 }
Michael Jurka92f3d462011-11-22 21:02:29 -08001183
Winson Chung5fc72b32011-10-11 17:53:58 -07001184 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
Michael Jurkadac85912012-05-18 15:04:49 -07001185 float scale) {
Winson Chung201bc822011-06-20 15:41:53 -07001186 if (bitmap != null) {
Winson Chungb44b5242011-06-13 11:32:14 -07001187 Canvas c = new Canvas(bitmap);
Winson Chung5fc72b32011-10-11 17:53:58 -07001188 c.scale(scale, scale);
Winson Chung201bc822011-06-20 15:41:53 -07001189 Rect oldBounds = d.copyBounds();
1190 d.setBounds(x, y, x + w, y + h);
1191 d.draw(c);
1192 d.setBounds(oldBounds); // Restore the bounds
Adam Cohenaaf473c2011-08-03 12:02:47 -07001193 c.setBitmap(null);
Winson Chung201bc822011-06-20 15:41:53 -07001194 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001195 }
Winson Chung5fc72b32011-10-11 17:53:58 -07001196
Michael Jurkadac85912012-05-18 15:04:49 -07001197 private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1198 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1199 final Canvas c = mCachedShortcutPreviewCanvas.get();
1200 if (tempBitmap == null ||
1201 tempBitmap.getWidth() != maxWidth ||
1202 tempBitmap.getHeight() != maxHeight) {
1203 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1204 mCachedShortcutPreviewBitmap.set(tempBitmap);
1205 } else {
1206 c.setBitmap(tempBitmap);
1207 c.drawColor(0, PorterDuff.Mode.CLEAR);
1208 c.setBitmap(null);
1209 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001210 // Render the icon
Winson Chung0b9fcf52011-10-31 13:05:15 -07001211 Drawable icon = mIconCache.getFullResIcon(info);
Michael Jurkadac85912012-05-18 15:04:49 -07001212
1213 int paddingTop =
1214 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1215 int paddingLeft =
1216 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1217 int paddingRight =
1218 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1219
1220 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
Michael Jurkadac85912012-05-18 15:04:49 -07001221
1222 renderDrawableToBitmap(
1223 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1224
1225 Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1226 c.setBitmap(preview);
1227 Paint p = mCachedShortcutPreviewPaint.get();
1228 if (p == null) {
1229 p = new Paint();
1230 ColorMatrix colorMatrix = new ColorMatrix();
1231 colorMatrix.setSaturation(0);
1232 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1233 p.setAlpha((int) (255 * 0.06f));
1234 //float density = 1f;
1235 //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1236 mCachedShortcutPreviewPaint.set(p);
1237 }
1238 c.drawBitmap(tempBitmap, 0, 0, p);
1239 c.setBitmap(null);
1240
1241 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1242
Winson Chungb44b5242011-06-13 11:32:14 -07001243 return preview;
Winson Chung1ed747a2011-05-03 16:18:34 -07001244 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001245
Michael Jurkadac85912012-05-18 15:04:49 -07001246 private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1247 int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1248 int maxHeight) {
Winson Chung4b576be2011-04-27 17:40:20 -07001249 // Load the preview image if possible
Michael Jurka038f9d82011-11-03 13:50:45 -07001250 String packageName = provider.getPackageName();
1251 if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1252 if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
Winson Chung4b576be2011-04-27 17:40:20 -07001253
Michael Jurka038f9d82011-11-03 13:50:45 -07001254 Drawable drawable = null;
1255 if (previewImage != 0) {
1256 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1257 if (drawable == null) {
Adam Cohen0e56cc92012-05-11 15:57:05 -07001258 Log.w(TAG, "Can't load widget preview drawable 0x" +
Michael Jurka038f9d82011-11-03 13:50:45 -07001259 Integer.toHexString(previewImage) + " for provider: " + provider);
Winson Chung4b576be2011-04-27 17:40:20 -07001260 }
1261 }
1262
Michael Jurka038f9d82011-11-03 13:50:45 -07001263 int bitmapWidth;
1264 int bitmapHeight;
Michael Jurkadac85912012-05-18 15:04:49 -07001265 Bitmap defaultPreview = null;
Michael Jurka038f9d82011-11-03 13:50:45 -07001266 boolean widgetPreviewExists = (drawable != null);
1267 if (widgetPreviewExists) {
1268 bitmapWidth = drawable.getIntrinsicWidth();
1269 bitmapHeight = drawable.getIntrinsicHeight();
Michael Jurka038f9d82011-11-03 13:50:45 -07001270 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001271 // Generate a preview image if we couldn't load one
Michael Jurkac7e52f52012-03-26 06:20:31 -07001272 if (cellHSpan < 1) cellHSpan = 1;
1273 if (cellVSpan < 1) cellVSpan = 1;
Michael Jurkadac85912012-05-18 15:04:49 -07001274
1275 BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1276 .getDrawable(R.drawable.widget_preview_tile);
1277 final int previewDrawableWidth = previewDrawable
1278 .getIntrinsicWidth();
1279 final int previewDrawableHeight = previewDrawable
1280 .getIntrinsicHeight();
1281 bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1282 bitmapHeight = previewDrawableHeight * cellVSpan;
1283
1284 defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1285 Config.ARGB_8888);
1286 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1287 c.setBitmap(defaultPreview);
1288 previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1289 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1290 Shader.TileMode.REPEAT);
1291 previewDrawable.draw(c);
1292 c.setBitmap(null);
1293
1294 // Draw the icon in the top left corner
1295 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1296 int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1297 float iconScale = Math.min((float) smallestSide
1298 / (mAppIconSize + 2 * minOffset), 1f);
1299
1300 try {
1301 Drawable icon = null;
1302 int hoffset =
1303 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1304 int yoffset =
1305 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1306 if (iconId > 0)
1307 icon = mIconCache.getFullResIcon(packageName, iconId);
Michael Jurkadac85912012-05-18 15:04:49 -07001308 if (icon != null) {
1309 renderDrawableToBitmap(icon, defaultPreview, hoffset,
1310 yoffset, (int) (mAppIconSize * iconScale),
1311 (int) (mAppIconSize * iconScale));
Winson Chung5fc72b32011-10-11 17:53:58 -07001312 }
Michael Jurkadac85912012-05-18 15:04:49 -07001313 } catch (Resources.NotFoundException e) {
Winson Chung1ed747a2011-05-03 16:18:34 -07001314 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001315 }
1316
Michael Jurkadac85912012-05-18 15:04:49 -07001317 // Scale to fit width only - let the widget preview be clipped in the
1318 // vertical dimension
Michael Jurka038f9d82011-11-03 13:50:45 -07001319 float scale = 1f;
1320 if (bitmapWidth > maxWidth) {
1321 scale = maxWidth / (float) bitmapWidth;
1322 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001323 if (scale != 1f) {
1324 bitmapWidth = (int) (scale * bitmapWidth);
1325 bitmapHeight = (int) (scale * bitmapHeight);
1326 }
1327
Michael Jurkadac85912012-05-18 15:04:49 -07001328 Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1329 Config.ARGB_8888);
Michael Jurka038f9d82011-11-03 13:50:45 -07001330
Michael Jurkadac85912012-05-18 15:04:49 -07001331 // Draw the scaled preview into the final bitmap
Michael Jurka038f9d82011-11-03 13:50:45 -07001332 if (widgetPreviewExists) {
Michael Jurkadac85912012-05-18 15:04:49 -07001333 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1334 bitmapHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001335 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001336 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1337 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1338 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1339 c.setBitmap(preview);
1340 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1341 dest.set(0, 0, preview.getWidth(), preview.getHeight());
1342
1343 Paint p = mCachedAppWidgetPreviewPaint.get();
1344 if (p == null) {
1345 p = new Paint();
1346 p.setFilterBitmap(true);
1347 mCachedAppWidgetPreviewPaint.set(p);
Peter Ng8db70002011-10-25 15:40:08 -07001348 }
Michael Jurkadac85912012-05-18 15:04:49 -07001349 c.drawBitmap(defaultPreview, src, dest, p);
1350 c.setBitmap(null);
Winson Chung4b576be2011-04-27 17:40:20 -07001351 }
Winson Chungb44b5242011-06-13 11:32:14 -07001352 return preview;
Winson Chung785d2eb2011-04-14 16:08:02 -07001353 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001354
Michael Jurka038f9d82011-11-03 13:50:45 -07001355 public void syncWidgetPageItems(final int page, final boolean immediate) {
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001356 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
Winson Chungb44b5242011-06-13 11:32:14 -07001357
Winson Chungd2945262011-06-24 15:22:14 -07001358 // Calculate the dimensions of each cell we are giving to each widget
Michael Jurka038f9d82011-11-03 13:50:45 -07001359 final ArrayList<Object> items = new ArrayList<Object>();
1360 int contentWidth = mWidgetSpacingLayout.getContentWidth();
1361 final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001362 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
Michael Jurka038f9d82011-11-03 13:50:45 -07001363 int contentHeight = mWidgetSpacingLayout.getContentHeight();
1364 final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001365 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
Winson Chungd2945262011-06-24 15:22:14 -07001366
Winson Chunge4a647f2011-09-30 14:41:25 -07001367 // Prepare the set of widgets to load previews for in the background
Michael Jurka39e5d172012-03-12 18:36:12 -07001368 int offset = (page - mNumAppsPages) * numItemsPerPage;
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001369 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1370 items.add(mWidgets.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -07001371 }
1372
Winson Chunge4a647f2011-09-30 14:41:25 -07001373 // Prepopulate the pages with the other widget info, and fill in the previews later
Michael Jurka39e5d172012-03-12 18:36:12 -07001374 final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chunge4a647f2011-09-30 14:41:25 -07001375 layout.setColumnCount(layout.getCellCountX());
1376 for (int i = 0; i < items.size(); ++i) {
1377 Object rawInfo = items.get(i);
1378 PendingAddItemInfo createItemInfo = null;
1379 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1380 R.layout.apps_customize_widget, layout, false);
1381 if (rawInfo instanceof AppWidgetProviderInfo) {
1382 // Fill in the widget information
1383 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1384 createItemInfo = new PendingAddWidgetInfo(info, null, null);
Adam Cohen1f362702012-04-04 14:58:12 -07001385
1386 // Determine the widget spans and min resize spans.
Adam Cohen2f093b62012-04-30 18:59:53 -07001387 int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001388 createItemInfo.spanX = spanXY[0];
1389 createItemInfo.spanY = spanXY[1];
Adam Cohen2f093b62012-04-30 18:59:53 -07001390 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001391 createItemInfo.minSpanX = minSpanXY[0];
1392 createItemInfo.minSpanY = minSpanXY[1];
1393
1394 widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
Winson Chunge4a647f2011-09-30 14:41:25 -07001395 widget.setTag(createItemInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -08001396 widget.setShortPressListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001397 } else if (rawInfo instanceof ResolveInfo) {
1398 // Fill in the shortcuts information
1399 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001400 createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
Winson Chunge4a647f2011-09-30 14:41:25 -07001401 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1402 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1403 info.activityInfo.name);
Michael Jurka82369a12012-01-12 08:08:38 -08001404 widget.applyFromResolveInfo(mPackageManager, info);
Winson Chunge4a647f2011-09-30 14:41:25 -07001405 widget.setTag(createItemInfo);
1406 }
1407 widget.setOnClickListener(this);
1408 widget.setOnLongClickListener(this);
1409 widget.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001410 widget.setOnKeyListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001411
1412 // Layout each widget
1413 int ix = i % mWidgetCountX;
1414 int iy = i / mWidgetCountX;
1415 GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1416 GridLayout.spec(iy, GridLayout.LEFT),
1417 GridLayout.spec(ix, GridLayout.TOP));
1418 lp.width = cellWidth;
1419 lp.height = cellHeight;
1420 lp.setGravity(Gravity.TOP | Gravity.LEFT);
1421 if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1422 if (iy > 0) lp.topMargin = mWidgetHeightGap;
1423 layout.addView(widget, lp);
1424 }
1425
Michael Jurka038f9d82011-11-03 13:50:45 -07001426 // wait until a call on onLayout to start loading, because
1427 // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1428 // TODO: can we do a measure/layout immediately?
1429 layout.setOnLayoutListener(new Runnable() {
1430 public void run() {
1431 // Load the widget previews
1432 int maxPreviewWidth = cellWidth;
1433 int maxPreviewHeight = cellHeight;
1434 if (layout.getChildCount() > 0) {
1435 PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1436 int[] maxSize = w.getPreviewSize();
1437 maxPreviewWidth = maxSize[0];
1438 maxPreviewHeight = maxSize[1];
1439 }
1440 if (immediate) {
1441 AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1442 maxPreviewWidth, maxPreviewHeight, null, null);
1443 loadWidgetPreviewsInBackground(null, data);
1444 onSyncWidgetPageItems(data);
1445 } else {
Michael Jurkaf6a96902012-06-06 11:48:13 -07001446 if (mInTransition) {
1447 mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
1448 } else {
1449 prepareLoadWidgetPreviewsTask(page, items,
1450 maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1451 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001452 }
1453 }
1454 });
Winson Chungf314b0e2011-08-16 11:54:27 -07001455 }
1456 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1457 AsyncTaskPageData data) {
Winson Chung68e4c642011-11-10 15:48:25 -08001458 // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1459 // previews synchronously
Winson Chungf314b0e2011-08-16 11:54:27 -07001460 if (task != null) {
1461 // Ensure that this task starts running at the correct priority
1462 task.syncThreadPriority();
1463 }
1464
1465 // Load each of the widget/shortcut previews
1466 ArrayList<Object> items = data.items;
1467 ArrayList<Bitmap> images = data.generatedImages;
1468 int count = items.size();
Winson Chungf314b0e2011-08-16 11:54:27 -07001469 for (int i = 0; i < count; ++i) {
1470 if (task != null) {
1471 // Ensure we haven't been cancelled yet
1472 if (task.isCancelled()) break;
1473 // Before work on each item, ensure that this task is running at the correct
1474 // priority
1475 task.syncThreadPriority();
1476 }
1477
1478 Object rawInfo = items.get(i);
1479 if (rawInfo instanceof AppWidgetProviderInfo) {
1480 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
Adam Cohen2f093b62012-04-30 18:59:53 -07001481 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
Winson Chung72d59842012-02-22 13:51:36 -08001482
1483 int maxWidth = Math.min(data.maxImageWidth,
1484 mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1485 int maxHeight = Math.min(data.maxImageHeight,
1486 mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
Michael Jurka038f9d82011-11-03 13:50:45 -07001487 Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
Winson Chung72d59842012-02-22 13:51:36 -08001488 cellSpans[0], cellSpans[1], maxWidth, maxHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001489 images.add(b);
Winson Chungf314b0e2011-08-16 11:54:27 -07001490 } else if (rawInfo instanceof ResolveInfo) {
1491 // Fill in the shortcuts information
1492 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001493 images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
Winson Chungf314b0e2011-08-16 11:54:27 -07001494 }
1495 }
Winson Chungb44b5242011-06-13 11:32:14 -07001496 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001497
Winson Chungb44b5242011-06-13 11:32:14 -07001498 private void onSyncWidgetPageItems(AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001499 if (mInTransition) {
1500 mDeferredSyncWidgetPageItems.add(data);
1501 return;
Winson Chung785d2eb2011-04-14 16:08:02 -07001502 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001503 try {
1504 int page = data.page;
1505 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001506
Michael Jurka39e5d172012-03-12 18:36:12 -07001507 ArrayList<Object> items = data.items;
1508 int count = items.size();
1509 for (int i = 0; i < count; ++i) {
1510 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1511 if (widget != null) {
1512 Bitmap preview = data.generatedImages.get(i);
1513 widget.applyPreview(new FastBitmapDrawable(preview), i);
1514 }
1515 }
Winson Chung68e4c642011-11-10 15:48:25 -08001516
Michael Jurka39e5d172012-03-12 18:36:12 -07001517 layout.createHardwareLayer();
1518 invalidate();
1519
1520 // Update all thread priorities
1521 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1522 while (iter.hasNext()) {
1523 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1524 int pageIndex = task.page;
1525 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1526 }
1527 } finally {
1528 data.cleanup(false);
Winson Chung68e4c642011-11-10 15:48:25 -08001529 }
Winson Chungb44b5242011-06-13 11:32:14 -07001530 }
Winson Chung46af2e82011-05-09 16:00:53 -07001531
Winson Chung785d2eb2011-04-14 16:08:02 -07001532 @Override
1533 public void syncPages() {
1534 removeAllViews();
Adam Cohen0cd3b642011-10-14 14:58:00 -07001535 cancelAllTasks();
Winson Chung875de7e2011-06-28 14:25:17 -07001536
Adam Cohen0cd3b642011-10-14 14:58:00 -07001537 Context context = getContext();
1538 for (int j = 0; j < mNumWidgetPages; ++j) {
1539 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1540 mWidgetCountY);
1541 setupPage(layout);
Michael Jurka39e5d172012-03-12 18:36:12 -07001542 addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
Adam Cohen0cd3b642011-10-14 14:58:00 -07001543 LayoutParams.MATCH_PARENT));
Winson Chung875de7e2011-06-28 14:25:17 -07001544 }
1545
Adam Cohen0cd3b642011-10-14 14:58:00 -07001546 for (int i = 0; i < mNumAppsPages; ++i) {
1547 PagedViewCellLayout layout = new PagedViewCellLayout(context);
1548 setupPage(layout);
1549 addView(layout);
Winson Chung785d2eb2011-04-14 16:08:02 -07001550 }
1551 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001552
Winson Chung785d2eb2011-04-14 16:08:02 -07001553 @Override
Winson Chungf314b0e2011-08-16 11:54:27 -07001554 public void syncPageItems(int page, boolean immediate) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07001555 if (page < mNumAppsPages) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001556 syncAppsPageItems(page, immediate);
Adam Cohen0cd3b642011-10-14 14:58:00 -07001557 } else {
Michael Jurka39e5d172012-03-12 18:36:12 -07001558 syncWidgetPageItems(page, immediate);
Winson Chung785d2eb2011-04-14 16:08:02 -07001559 }
1560 }
1561
Adam Cohen22f823d2011-09-01 17:22:18 -07001562 // We want our pages to be z-ordered such that the further a page is to the left, the higher
1563 // it is in the z-order. This is important to insure touch events are handled correctly.
1564 View getPageAt(int index) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001565 return getChildAt(indexToPage(index));
Adam Cohen22f823d2011-09-01 17:22:18 -07001566 }
1567
Adam Cohenae4f1552011-10-20 00:15:42 -07001568 @Override
1569 protected int indexToPage(int index) {
1570 return getChildCount() - index - 1;
1571 }
1572
Adam Cohen22f823d2011-09-01 17:22:18 -07001573 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1574 @Override
1575 protected void screenScrolled(int screenCenter) {
1576 super.screenScrolled(screenCenter);
Adam Cohen22f823d2011-09-01 17:22:18 -07001577
1578 for (int i = 0; i < getChildCount(); i++) {
1579 View v = getPageAt(i);
1580 if (v != null) {
Adam Cohenb5ba0972011-09-07 18:02:31 -07001581 float scrollProgress = getScrollProgress(screenCenter, v, i);
Adam Cohen22f823d2011-09-01 17:22:18 -07001582
1583 float interpolatedProgress =
1584 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1585 float scale = (1 - interpolatedProgress) +
1586 interpolatedProgress * TRANSITION_SCALE_FACTOR;
1587 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001588
Adam Cohen2591f6a2011-10-25 14:36:40 -07001589 float alpha;
1590
Winson Chungd167e2a2012-04-26 13:13:01 -07001591 if (scrollProgress < 0) {
Adam Cohen2591f6a2011-10-25 14:36:40 -07001592 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
Adam Cohenb5ba0972011-09-07 18:02:31 -07001593 1 - Math.abs(scrollProgress)) : 1.0f;
Adam Cohen2591f6a2011-10-25 14:36:40 -07001594 } else {
1595 // On large screens we need to fade the page as it nears its leftmost position
1596 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1597 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001598
1599 v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1600 int pageWidth = v.getMeasuredWidth();
1601 int pageHeight = v.getMeasuredHeight();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001602
1603 if (PERFORM_OVERSCROLL_ROTATION) {
1604 if (i == 0 && scrollProgress < 0) {
1605 // Overscroll to the left
1606 v.setPivotX(TRANSITION_PIVOT * pageWidth);
1607 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1608 scale = 1.0f;
1609 alpha = 1.0f;
1610 // On the first page, we don't want the page to have any lateral motion
Adam Cohenebea84d2011-11-09 17:20:41 -08001611 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001612 } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1613 // Overscroll to the right
1614 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1615 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1616 scale = 1.0f;
1617 alpha = 1.0f;
1618 // On the last page, we don't want the page to have any lateral motion.
Adam Cohenebea84d2011-11-09 17:20:41 -08001619 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001620 } else {
1621 v.setPivotY(pageHeight / 2.0f);
1622 v.setPivotX(pageWidth / 2.0f);
1623 v.setRotationY(0f);
1624 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001625 }
1626
1627 v.setTranslationX(translationX);
1628 v.setScaleX(scale);
1629 v.setScaleY(scale);
1630 v.setAlpha(alpha);
Adam Cohen4e844012011-11-09 13:48:04 -08001631
1632 // If the view has 0 alpha, we set it to be invisible so as to prevent
1633 // it from accepting touches
Michael Jurka8b805b12012-04-18 14:23:14 -07001634 if (alpha == 0) {
Adam Cohen4e844012011-11-09 13:48:04 -08001635 v.setVisibility(INVISIBLE);
1636 } else if (v.getVisibility() != VISIBLE) {
1637 v.setVisibility(VISIBLE);
1638 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001639 }
1640 }
1641 }
1642
1643 protected void overScroll(float amount) {
Adam Cohencff6af82011-09-13 14:51:53 -07001644 acceleratedOverScroll(amount);
Adam Cohen22f823d2011-09-01 17:22:18 -07001645 }
1646
Winson Chung785d2eb2011-04-14 16:08:02 -07001647 /**
1648 * Used by the parent to get the content width to set the tab bar to
1649 * @return
1650 */
1651 public int getPageContentWidth() {
1652 return mContentWidth;
1653 }
1654
Winson Chungb26f3d62011-06-02 10:49:29 -07001655 @Override
Winson Chungb26f3d62011-06-02 10:49:29 -07001656 protected void onPageEndMoving() {
Winson Chungb26f3d62011-06-02 10:49:29 -07001657 super.onPageEndMoving();
Michael Jurka5e368ff2012-05-14 23:13:15 -07001658 mForceDrawAllChildrenNextFrame = true;
Winson Chung5afbf7b2011-07-25 11:53:08 -07001659 // We reset the save index when we change pages so that it will be recalculated on next
1660 // rotation
1661 mSaveInstanceStateItemIndex = -1;
Winson Chungb26f3d62011-06-02 10:49:29 -07001662 }
1663
Winson Chung785d2eb2011-04-14 16:08:02 -07001664 /*
1665 * AllAppsView implementation
1666 */
Winson Chung785d2eb2011-04-14 16:08:02 -07001667 public void setup(Launcher launcher, DragController dragController) {
1668 mLauncher = launcher;
1669 mDragController = dragController;
1670 }
Winson Chung9802ac92012-06-08 16:01:58 -07001671
1672 /**
1673 * We should call thise method whenever the core data changes (mApps, mWidgets) so that we can
1674 * appropriately determine when to invalidate the PagedView page data. In cases where the data
1675 * has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the
1676 * next onMeasure() pass, which will trigger an invalidatePageData() itself.
1677 */
1678 private void invalidateOnDataChange() {
1679 if (!isDataReady()) {
1680 // The next layout pass will trigger data-ready if both widgets and apps are set, so
1681 // request a layout to trigger the page data when ready.
1682 requestLayout();
1683 } else {
1684 cancelAllTasks();
1685 invalidatePageData();
1686 }
1687 }
1688
Winson Chung785d2eb2011-04-14 16:08:02 -07001689 public void setApps(ArrayList<ApplicationInfo> list) {
1690 mApps = list;
1691 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001692 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001693 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001694 }
1695 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1696 // We add it in place, in alphabetical order
1697 int count = list.size();
1698 for (int i = 0; i < count; ++i) {
1699 ApplicationInfo info = list.get(i);
1700 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1701 if (index < 0) {
1702 mApps.add(-(index + 1), info);
1703 }
1704 }
1705 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001706 public void addApps(ArrayList<ApplicationInfo> list) {
1707 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001708 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001709 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001710 }
1711 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1712 ComponentName removeComponent = item.intent.getComponent();
1713 int length = list.size();
1714 for (int i = 0; i < length; ++i) {
1715 ApplicationInfo info = list.get(i);
1716 if (info.intent.getComponent().equals(removeComponent)) {
1717 return i;
1718 }
1719 }
1720 return -1;
1721 }
Winson Chungcd810732012-06-18 16:45:43 -07001722 private int findAppByPackage(List<ApplicationInfo> list, String packageName) {
1723 int length = list.size();
1724 for (int i = 0; i < length; ++i) {
1725 ApplicationInfo info = list.get(i);
1726 if (ItemInfo.getPackageName(info.intent).equals(packageName)) {
1727 return i;
1728 }
1729 }
1730 return -1;
1731 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001732 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1733 // loop through all the apps and remove apps that have the same component
1734 int length = list.size();
1735 for (int i = 0; i < length; ++i) {
1736 ApplicationInfo info = list.get(i);
1737 int removeIndex = findAppByComponent(mApps, info);
1738 if (removeIndex > -1) {
1739 mApps.remove(removeIndex);
Winson Chung785d2eb2011-04-14 16:08:02 -07001740 }
1741 }
1742 }
Winson Chungcd810732012-06-18 16:45:43 -07001743 private void removeAppsWithPackageNameWithoutInvalidate(ArrayList<String> packageNames) {
1744 // loop through all the package names and remove apps that have the same package name
1745 for (String pn : packageNames) {
1746 int removeIndex = findAppByPackage(mApps, pn);
1747 while (removeIndex > -1) {
1748 mApps.remove(removeIndex);
1749 removeIndex = findAppByPackage(mApps, pn);
1750 }
1751 }
1752 }
1753 public void removeApps(ArrayList<String> packageNames) {
1754 removeAppsWithPackageNameWithoutInvalidate(packageNames);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001755 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001756 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001757 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001758 public void updateApps(ArrayList<ApplicationInfo> list) {
1759 // We remove and re-add the updated applications list because it's properties may have
1760 // changed (ie. the title), and this will ensure that the items will be in their proper
1761 // place in the list.
1762 removeAppsWithoutInvalidate(list);
1763 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001764 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001765 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001766 }
Michael Jurka35aa14d2011-07-07 17:01:08 -07001767
Winson Chung785d2eb2011-04-14 16:08:02 -07001768 public void reset() {
Winson Chung649668f2012-01-10 13:07:16 -08001769 // If we have reset, then we should not continue to restore the previous state
1770 mSaveInstanceStateItemIndex = -1;
1771
Adam Cohenb64d36e2011-10-17 21:48:02 -07001772 AppsCustomizeTabHost tabHost = getTabHost();
1773 String tag = tabHost.getCurrentTabTag();
Winson Chung6a8103c2011-10-21 11:08:32 -07001774 if (tag != null) {
1775 if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1776 tabHost.setCurrentTabFromContent(ContentType.Applications);
1777 }
Adam Cohenb64d36e2011-10-17 21:48:02 -07001778 }
Winson Chung649668f2012-01-10 13:07:16 -08001779
Adam Cohenb64d36e2011-10-17 21:48:02 -07001780 if (mCurrentPage != 0) {
1781 invalidatePageData(0);
1782 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001783 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001784
1785 private AppsCustomizeTabHost getTabHost() {
1786 return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1787 }
1788
Winson Chung785d2eb2011-04-14 16:08:02 -07001789 public void dumpState() {
1790 // TODO: Dump information related to current list of Applications, Widgets, etc.
Adam Cohen0e56cc92012-05-11 15:57:05 -07001791 ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1792 dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
Winson Chung785d2eb2011-04-14 16:08:02 -07001793 }
Adam Cohen4e844012011-11-09 13:48:04 -08001794
Winson Chung785d2eb2011-04-14 16:08:02 -07001795 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chungd2945262011-06-24 15:22:14 -07001796 ArrayList<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001797 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -07001798 for (Object i: list) {
1799 if (i instanceof AppWidgetProviderInfo) {
1800 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1801 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
1802 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1803 + " initialLayout=" + info.initialLayout
1804 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1805 } else if (i instanceof ResolveInfo) {
1806 ResolveInfo info = (ResolveInfo) i;
1807 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1808 + info.icon);
1809 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001810 }
1811 }
Adam Cohen4e844012011-11-09 13:48:04 -08001812
Winson Chung785d2eb2011-04-14 16:08:02 -07001813 public void surrender() {
1814 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1815 // should stop this now.
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001816
1817 // Stop all background tasks
1818 cancelAllTasks();
Winson Chung785d2eb2011-04-14 16:08:02 -07001819 }
Winson Chung007c6982011-06-14 13:27:53 -07001820
Winson Chunge4e50662012-01-23 14:45:13 -08001821 @Override
1822 public void iconPressed(PagedViewIcon icon) {
1823 // Reset the previously pressed icon and store a reference to the pressed icon so that
1824 // we can reset it on return to Launcher (in Launcher.onResume())
1825 if (mPressedIcon != null) {
1826 mPressedIcon.resetDrawableState();
1827 }
1828 mPressedIcon = icon;
1829 }
1830
1831 public void resetDrawableState() {
1832 if (mPressedIcon != null) {
1833 mPressedIcon.resetDrawableState();
1834 mPressedIcon = null;
1835 }
1836 }
Winson Chung68e4c642011-11-10 15:48:25 -08001837
Winson Chungb44b5242011-06-13 11:32:14 -07001838 /*
1839 * We load an extra page on each side to prevent flashes from scrolling and loading of the
1840 * widget previews in the background with the AsyncTasks.
1841 */
Winson Chung68e4c642011-11-10 15:48:25 -08001842 final static int sLookBehindPageCount = 2;
1843 final static int sLookAheadPageCount = 2;
Winson Chungb44b5242011-06-13 11:32:14 -07001844 protected int getAssociatedLowerPageBound(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001845 final int count = getChildCount();
1846 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1847 int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1848 return windowMinIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001849 }
1850 protected int getAssociatedUpperPageBound(int page) {
1851 final int count = getChildCount();
Winson Chung68e4c642011-11-10 15:48:25 -08001852 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1853 int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1854 count - 1);
1855 return windowMaxIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001856 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07001857
1858 @Override
1859 protected String getCurrentPageDescription() {
1860 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1861 int stringId = R.string.default_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001862 int count = 0;
1863
Adam Cohen0cd3b642011-10-14 14:58:00 -07001864 if (page < mNumAppsPages) {
Winson Chung6a0f57d2011-06-29 20:10:49 -07001865 stringId = R.string.apps_customize_apps_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001866 count = mNumAppsPages;
Adam Cohen0cd3b642011-10-14 14:58:00 -07001867 } else {
1868 page -= mNumAppsPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001869 stringId = R.string.apps_customize_widgets_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001870 count = mNumWidgetPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001871 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001872
Michael Jurka8b805b12012-04-18 14:23:14 -07001873 return String.format(getContext().getString(stringId), page + 1, count);
Winson Chung6a0f57d2011-06-29 20:10:49 -07001874 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001875}