blob: d7bb4380ced89061d589805afcca79c587bc943e [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;
Peter Ng8db70002011-10-25 15:40:08 -070037import android.graphics.MaskFilter;
Winson Chung72d59842012-02-22 13:51:36 -080038import android.graphics.Matrix;
Peter Ng8db70002011-10-25 15:40:08 -070039import android.graphics.Paint;
Michael Jurkadac85912012-05-18 15:04:49 -070040import android.graphics.PorterDuff;
Winson Chung785d2eb2011-04-14 16:08:02 -070041import android.graphics.Rect;
Winson Chung72d59842012-02-22 13:51:36 -080042import android.graphics.RectF;
Michael Jurkadac85912012-05-18 15:04:49 -070043import android.graphics.Shader;
Peter Ng8db70002011-10-25 15:40:08 -070044import android.graphics.TableMaskFilter;
Michael Jurkadac85912012-05-18 15:04:49 -070045import android.graphics.drawable.BitmapDrawable;
Winson Chung785d2eb2011-04-14 16:08:02 -070046import android.graphics.drawable.Drawable;
Winson Chungb44b5242011-06-13 11:32:14 -070047import android.os.AsyncTask;
48import android.os.Process;
Winson Chung785d2eb2011-04-14 16:08:02 -070049import android.util.AttributeSet;
50import android.util.Log;
Winson Chung72d8b392011-07-29 13:56:44 -070051import android.view.Gravity;
Winson Chungc6f10b92011-11-14 11:39:07 -080052import android.view.KeyEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070053import android.view.LayoutInflater;
Winson Chungde1af762011-07-21 16:44:07 -070054import android.view.MotionEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070055import android.view.View;
Winson Chung63257c12011-05-05 17:06:13 -070056import android.view.ViewGroup;
Winson Chung55b65502011-05-26 12:03:43 -070057import android.view.animation.AccelerateInterpolator;
Adam Cohen2591f6a2011-10-25 14:36:40 -070058import android.view.animation.DecelerateInterpolator;
Winson Chungfd3385f2011-06-15 19:51:24 -070059import android.widget.GridLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070060import android.widget.ImageView;
Winson Chung55b65502011-05-26 12:03:43 -070061import android.widget.Toast;
Winson Chung785d2eb2011-04-14 16:08:02 -070062
63import com.android.launcher.R;
Adam Cohenc0dcf592011-06-01 15:30:43 -070064import com.android.launcher2.DropTarget.DragObject;
65
Michael Jurka9bc8eba2012-05-21 20:36:44 -070066import java.lang.ref.WeakReference;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067import java.util.ArrayList;
68import java.util.Collections;
69import java.util.Iterator;
70import java.util.List;
Winson Chung785d2eb2011-04-14 16:08:02 -070071
Winson Chungb44b5242011-06-13 11:32:14 -070072/**
73 * A simple callback interface which also provides the results of the task.
74 */
75interface AsyncTaskCallback {
76 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
77}
Winson Chung4e076542011-06-23 13:04:10 -070078
Winson Chungb44b5242011-06-13 11:32:14 -070079/**
80 * The data needed to perform either of the custom AsyncTasks.
81 */
82class AsyncTaskPageData {
Winson Chung875de7e2011-06-28 14:25:17 -070083 enum Type {
Michael Jurka82369a12012-01-12 08:08:38 -080084 LoadWidgetPreviewData
Winson Chung875de7e2011-06-28 14:25:17 -070085 }
86
Winson Chungb44b5242011-06-13 11:32:14 -070087 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
88 AsyncTaskCallback postR) {
89 page = p;
90 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070091 sourceImages = si;
92 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -070093 maxImageWidth = maxImageHeight = -1;
Winson Chungb44b5242011-06-13 11:32:14 -070094 doInBackgroundCallback = bgR;
95 postExecuteCallback = postR;
96 }
Michael Jurka038f9d82011-11-03 13:50:45 -070097 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
Winson Chungb44b5242011-06-13 11:32:14 -070098 AsyncTaskCallback postR) {
99 page = p;
100 items = l;
Winson Chung4e076542011-06-23 13:04:10 -0700101 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -0700102 maxImageWidth = cw;
103 maxImageHeight = ch;
Winson Chungb44b5242011-06-13 11:32:14 -0700104 doInBackgroundCallback = bgR;
105 postExecuteCallback = postR;
106 }
Winson Chung09945932011-09-20 14:22:40 -0700107 void cleanup(boolean cancelled) {
108 // Clean up any references to source/generated bitmaps
109 if (sourceImages != null) {
110 if (cancelled) {
111 for (Bitmap b : sourceImages) {
112 b.recycle();
113 }
114 }
115 sourceImages.clear();
116 }
117 if (generatedImages != null) {
118 if (cancelled) {
119 for (Bitmap b : generatedImages) {
120 b.recycle();
121 }
122 }
123 generatedImages.clear();
124 }
125 }
Winson Chungb44b5242011-06-13 11:32:14 -0700126 int page;
127 ArrayList<Object> items;
Winson Chung4e076542011-06-23 13:04:10 -0700128 ArrayList<Bitmap> sourceImages;
129 ArrayList<Bitmap> generatedImages;
Michael Jurka038f9d82011-11-03 13:50:45 -0700130 int maxImageWidth;
131 int maxImageHeight;
Winson Chungb44b5242011-06-13 11:32:14 -0700132 AsyncTaskCallback doInBackgroundCallback;
133 AsyncTaskCallback postExecuteCallback;
134}
Winson Chung4e076542011-06-23 13:04:10 -0700135
Winson Chungb44b5242011-06-13 11:32:14 -0700136/**
137 * A generic template for an async task used in AppsCustomize.
138 */
139class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700140 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
Winson Chungb44b5242011-06-13 11:32:14 -0700141 page = p;
Winson Chungb44b5242011-06-13 11:32:14 -0700142 threadPriority = Process.THREAD_PRIORITY_DEFAULT;
Winson Chung875de7e2011-06-28 14:25:17 -0700143 dataType = ty;
Winson Chungb44b5242011-06-13 11:32:14 -0700144 }
145 @Override
146 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
147 if (params.length != 1) return null;
148 // Load each of the widget previews in the background
149 params[0].doInBackgroundCallback.run(this, params[0]);
150 return params[0];
151 }
152 @Override
153 protected void onPostExecute(AsyncTaskPageData result) {
154 // All the widget previews are loaded, so we can just callback to inflate the page
155 result.postExecuteCallback.run(this, result);
156 }
157
158 void setThreadPriority(int p) {
159 threadPriority = p;
160 }
161 void syncThreadPriority() {
162 Process.setThreadPriority(threadPriority);
163 }
164
165 // The page that this async task is associated with
Winson Chung875de7e2011-06-28 14:25:17 -0700166 AsyncTaskPageData.Type dataType;
Winson Chungb44b5242011-06-13 11:32:14 -0700167 int page;
Winson Chungb44b5242011-06-13 11:32:14 -0700168 int threadPriority;
169}
Winson Chungb44b5242011-06-13 11:32:14 -0700170
Michael Jurkadac85912012-05-18 15:04:49 -0700171abstract class WeakReferenceThreadLocal<T> {
172 private ThreadLocal<WeakReference<T>> mThreadLocal;
173 public WeakReferenceThreadLocal() {
174 mThreadLocal = new ThreadLocal<WeakReference<T>>();
175 }
176
177 abstract T initialValue();
178
179 public void set(T t) {
180 mThreadLocal.set(new WeakReference<T>(t));
181 }
182
183 public T get() {
184 WeakReference<T> reference = mThreadLocal.get();
185 T obj;
186 if (reference == null) {
187 obj = initialValue();
188 mThreadLocal.set(new WeakReference<T>(obj));
189 return obj;
190 } else {
191 obj = reference.get();
192 if (obj == null) {
193 obj = initialValue();
194 mThreadLocal.set(new WeakReference<T>(obj));
195 }
196 return obj;
197 }
198 }
199}
200
201class CanvasCache extends WeakReferenceThreadLocal<Canvas> {
202 @Override
203 protected Canvas initialValue() {
204 return new Canvas();
205 }
206}
207
208class PaintCache extends WeakReferenceThreadLocal<Paint> {
209 @Override
210 protected Paint initialValue() {
211 return null;
212 }
213}
214
215class BitmapCache extends WeakReferenceThreadLocal<Bitmap> {
216 @Override
217 protected Bitmap initialValue() {
218 return null;
219 }
220}
221
222class RectCache extends WeakReferenceThreadLocal<Rect> {
223 @Override
224 protected Rect initialValue() {
225 return new Rect();
226 }
227}
228
Winson Chungb44b5242011-06-13 11:32:14 -0700229/**
230 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
231 */
Winson Chung785d2eb2011-04-14 16:08:02 -0700232public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
Winson Chungcd810732012-06-18 16:45:43 -0700233 View.OnClickListener, View.OnKeyListener, DragSource,
Michael Jurka39e5d172012-03-12 18:36:12 -0700234 PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener,
235 LauncherTransitionable {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700236 static final String TAG = "AppsCustomizePagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -0700237
238 /**
239 * The different content types that this paged view can show.
240 */
241 public enum ContentType {
242 Applications,
Winson Chung6a26e5b2011-05-26 14:36:06 -0700243 Widgets
Winson Chung785d2eb2011-04-14 16:08:02 -0700244 }
245
246 // Refs
247 private Launcher mLauncher;
248 private DragController mDragController;
249 private final LayoutInflater mLayoutInflater;
250 private final PackageManager mPackageManager;
251
Winson Chung5afbf7b2011-07-25 11:53:08 -0700252 // Save and Restore
253 private int mSaveInstanceStateItemIndex = -1;
Winson Chunge4e50662012-01-23 14:45:13 -0800254 private PagedViewIcon mPressedIcon;
Winson Chung5afbf7b2011-07-25 11:53:08 -0700255
Winson Chung785d2eb2011-04-14 16:08:02 -0700256 // Content
Winson Chung785d2eb2011-04-14 16:08:02 -0700257 private ArrayList<ApplicationInfo> mApps;
Winson Chungd2945262011-06-24 15:22:14 -0700258 private ArrayList<Object> mWidgets;
Winson Chung1ed747a2011-05-03 16:18:34 -0700259
Winson Chung7d7541e2011-09-16 20:14:36 -0700260 // Cling
Winson Chung3f4e1422011-11-17 14:58:51 -0800261 private boolean mHasShownAllAppsCling;
Winson Chung7d7541e2011-09-16 20:14:36 -0700262 private int mClingFocusedX;
263 private int mClingFocusedY;
264
Winson Chung1ed747a2011-05-03 16:18:34 -0700265 // Caching
Winson Chungb44b5242011-06-13 11:32:14 -0700266 private Canvas mCanvas;
Winson Chung4dbea792011-05-05 14:21:32 -0700267 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -0700268
269 // Dimens
270 private int mContentWidth;
Winson Chungd2945262011-06-24 15:22:14 -0700271 private int mAppIconSize;
Winson Chung6032e7e2011-11-08 15:47:17 -0800272 private int mMaxAppCellCountX, mMaxAppCellCountY;
Winson Chung4b576be2011-04-27 17:40:20 -0700273 private int mWidgetCountX, mWidgetCountY;
Winson Chungd2945262011-06-24 15:22:14 -0700274 private int mWidgetWidthGap, mWidgetHeightGap;
Winson Chung1ed747a2011-05-03 16:18:34 -0700275 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -0700276 private PagedViewCellLayout mWidgetSpacingLayout;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700277 private int mNumAppsPages;
278 private int mNumWidgetPages;
Winson Chung785d2eb2011-04-14 16:08:02 -0700279
Adam Cohen22f823d2011-09-01 17:22:18 -0700280 // Relating to the scroll and overscroll effects
281 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
Adam Cohencff6af82011-09-13 14:51:53 -0700282 private static float CAMERA_DISTANCE = 6500;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700283 private static float TRANSITION_SCALE_FACTOR = 0.74f;
Adam Cohencff6af82011-09-13 14:51:53 -0700284 private static float TRANSITION_PIVOT = 0.65f;
285 private static float TRANSITION_MAX_ROTATION = 22;
286 private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700287 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
Adam Cohen2591f6a2011-10-25 14:36:40 -0700288 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
Adam Cohen22f823d2011-09-01 17:22:18 -0700289
Winson Chungb44b5242011-06-13 11:32:14 -0700290 // Previews & outlines
291 ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
Winson Chung68e4c642011-11-10 15:48:25 -0800292 private static final int sPageSleepDelay = 200;
Winson Chung4b576be2011-04-27 17:40:20 -0700293
Adam Cohened66b2b2012-01-23 17:28:51 -0800294 private Runnable mInflateWidgetRunnable = null;
295 private Runnable mBindWidgetRunnable = null;
296 static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
Adam Cohen21a170b2012-05-30 15:17:06 -0700297 static final int WIDGET_PRELOAD_PENDING = 0;
298 static final int WIDGET_BOUND = 1;
299 static final int WIDGET_INFLATED = 2;
Adam Cohened66b2b2012-01-23 17:28:51 -0800300 int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
301 int mWidgetLoadingId = -1;
Adam Cohen1b36dc32012-02-13 19:27:37 -0800302 PendingAddWidgetInfo mCreateWidgetInfo = null;
Adam Cohen7a326642012-02-22 12:03:22 -0800303 private boolean mDraggingWidget = false;
Adam Cohened66b2b2012-01-23 17:28:51 -0800304
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
582 Toast.makeText(getContext(), R.string.long_press_widget_to_add,
583 Toast.LENGTH_SHORT).show();
Winson Chung46af2e82011-05-09 16:00:53 -0700584
Winson Chungd2e87b32011-06-02 10:53:07 -0700585 // Create a little animation to show that the widget can move
586 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
587 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
Michael Jurka2ecf9952012-06-18 12:52:28 -0700588 AnimatorSet bounce = LauncherAnimUtils.createAnimatorSet();
589 ValueAnimator tyuAnim = LauncherAnimUtils.ofFloat(p, "translationY", offsetY);
Winson Chungd2e87b32011-06-02 10:53:07 -0700590 tyuAnim.setDuration(125);
Michael Jurka2ecf9952012-06-18 12:52:28 -0700591 ValueAnimator tydAnim = LauncherAnimUtils.ofFloat(p, "translationY", 0f);
Winson Chungd2e87b32011-06-02 10:53:07 -0700592 tydAnim.setDuration(100);
593 bounce.play(tyuAnim).before(tydAnim);
594 bounce.setInterpolator(new AccelerateInterpolator());
595 bounce.start();
Winson Chung4b576be2011-04-27 17:40:20 -0700596 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700597 }
598
Winson Chungc6f10b92011-11-14 11:39:07 -0800599 public boolean onKey(View v, int keyCode, KeyEvent event) {
600 return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event);
601 }
602
Winson Chung785d2eb2011-04-14 16:08:02 -0700603 /*
604 * PagedViewWithDraggableItems implementation
605 */
606 @Override
607 protected void determineDraggingStart(android.view.MotionEvent ev) {
608 // Disable dragging by pulling an app down for now.
609 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700610
Winson Chung4b576be2011-04-27 17:40:20 -0700611 private void beginDraggingApplication(View v) {
Adam Cohenac8c8762011-07-13 11:15:27 -0700612 mLauncher.getWorkspace().onDragStartedWithItem(v);
613 mLauncher.getWorkspace().beginDragShared(v, this);
Winson Chung4b576be2011-04-27 17:40:20 -0700614 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700615
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700616 private void preloadWidget(final PendingAddWidgetInfo info) {
Adam Cohened66b2b2012-01-23 17:28:51 -0800617 final AppWidgetProviderInfo pInfo = info.info;
618 if (pInfo.configure != null) {
619 return;
620 }
621
Adam Cohen21a170b2012-05-30 15:17:06 -0700622 mWidgetCleanupState = WIDGET_PRELOAD_PENDING;
Adam Cohened66b2b2012-01-23 17:28:51 -0800623 mBindWidgetRunnable = new Runnable() {
624 @Override
625 public void run() {
626 mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
Michael Jurka8b805b12012-04-18 14:23:14 -0700627 if (AppWidgetManager.getInstance(mLauncher)
628 .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
629 mWidgetCleanupState = WIDGET_BOUND;
630 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800631 }
632 };
633 post(mBindWidgetRunnable);
634
635 mInflateWidgetRunnable = new Runnable() {
636 @Override
637 public void run() {
Michael Jurka8b805b12012-04-18 14:23:14 -0700638 AppWidgetHostView hostView = mLauncher.
639 getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800640 info.boundWidget = hostView;
641 mWidgetCleanupState = WIDGET_INFLATED;
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800642 hostView.setVisibility(INVISIBLE);
Adam Cohen1f362702012-04-04 14:58:12 -0700643 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
644 info.spanY, info, false);
645
646 // We want the first widget layout to be the correct size. This will be important
647 // for width size reporting to the AppWidgetManager.
648 DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
649 unScaledSize[1]);
650 lp.x = lp.y = 0;
651 lp.customPosition = true;
652 hostView.setLayoutParams(lp);
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800653 mLauncher.getDragLayer().addView(hostView);
Adam Cohened66b2b2012-01-23 17:28:51 -0800654 }
655 };
656 post(mInflateWidgetRunnable);
657 }
658
659 @Override
660 public void onShortPress(View v) {
661 // We are anticipating a long press, and we use this time to load bind and instantiate
662 // the widget. This will need to be cleaned up if it turns out no long press occurs.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700663 if (mCreateWidgetInfo != null) {
664 // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
665 cleanupWidgetPreloading(false);
666 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800667 mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700668 preloadWidget(mCreateWidgetInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800669 }
670
Adam Cohen0e56cc92012-05-11 15:57:05 -0700671 private void cleanupWidgetPreloading(boolean widgetWasAdded) {
672 if (!widgetWasAdded) {
673 // If the widget was not added, we may need to do further cleanup.
674 PendingAddWidgetInfo info = mCreateWidgetInfo;
675 mCreateWidgetInfo = null;
Adam Cohen21a170b2012-05-30 15:17:06 -0700676
677 if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700678 // We never did any preloading, so just remove pending callbacks to do so
679 removeCallbacks(mBindWidgetRunnable);
680 removeCallbacks(mInflateWidgetRunnable);
681 } else if (mWidgetCleanupState == WIDGET_BOUND) {
682 // Delete the widget id which was allocated
683 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700684 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
685 }
686
687 // We never got around to inflating the widget, so remove the callback to do so.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700688 removeCallbacks(mInflateWidgetRunnable);
689 } else if (mWidgetCleanupState == WIDGET_INFLATED) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700690 // Delete the widget id which was allocated
691 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700692 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
693 }
694
Adam Cohen0e56cc92012-05-11 15:57:05 -0700695 // The widget was inflated and added to the DragLayer -- remove it.
696 AppWidgetHostView widget = info.boundWidget;
697 mLauncher.getDragLayer().removeView(widget);
698 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800699 }
700 mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
701 mWidgetLoadingId = -1;
Adam Cohen0e56cc92012-05-11 15:57:05 -0700702 mCreateWidgetInfo = null;
703 PagedViewWidget.resetShortPressTarget();
Adam Cohened66b2b2012-01-23 17:28:51 -0800704 }
705
Adam Cohen7a326642012-02-22 12:03:22 -0800706 @Override
707 public void cleanUpShortPress(View v) {
708 if (!mDraggingWidget) {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700709 cleanupWidgetPreloading(false);
Adam Cohen7a326642012-02-22 12:03:22 -0800710 }
711 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800712
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700713 private boolean beginDraggingWidget(View v) {
Adam Cohen7a326642012-02-22 12:03:22 -0800714 mDraggingWidget = true;
Winson Chung4b576be2011-04-27 17:40:20 -0700715 // Get the widget preview as the drag representation
716 ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
Winson Chung1ed747a2011-05-03 16:18:34 -0700717 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700718
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700719 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
720 // we abort the drag.
721 if (image.getDrawable() == null) {
722 mDraggingWidget = false;
723 return false;
724 }
725
Winson Chung4b576be2011-04-27 17:40:20 -0700726 // Compose the drag image
Winson Chung1120e032011-11-22 16:11:31 -0800727 Bitmap preview;
728 Bitmap outline;
Winson Chung72d59842012-02-22 13:51:36 -0800729 float scale = 1f;
Winson Chung1ed747a2011-05-03 16:18:34 -0700730 if (createItemInfo instanceof PendingAddWidgetInfo) {
Adam Cohen92478922012-05-17 13:43:29 -0700731 // This can happen in some weird cases involving multi-touch. We can't start dragging
732 // the widget if this is null, so we break out.
733 if (mCreateWidgetInfo == null) {
734 return false;
735 }
736
Adam Cohen1b36dc32012-02-13 19:27:37 -0800737 PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
738 createItemInfo = createWidgetInfo;
Adam Cohen1f362702012-04-04 14:58:12 -0700739 int spanX = createItemInfo.spanX;
740 int spanY = createItemInfo.spanY;
741 int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
742 createWidgetInfo, true);
Winson Chung1ed747a2011-05-03 16:18:34 -0700743
Winson Chung72d59842012-02-22 13:51:36 -0800744 FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
745 float minScale = 1.25f;
Michael Jurkadac85912012-05-18 15:04:49 -0700746 int maxWidth, maxHeight;
747 maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
748 maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
Winson Chung1120e032011-11-22 16:11:31 -0800749 preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
Michael Jurkadac85912012-05-18 15:04:49 -0700750 createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);
Winson Chung72d59842012-02-22 13:51:36 -0800751
752 // Determine the image view drawable scale relative to the preview
753 float[] mv = new float[9];
754 Matrix m = new Matrix();
755 m.setRectToRect(
756 new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
757 new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
758 (float) previewDrawable.getIntrinsicHeight()),
759 Matrix.ScaleToFit.START);
760 m.getValues(mv);
761 scale = (float) mv[0];
Winson Chung1ed747a2011-05-03 16:18:34 -0700762 } else {
Michael Jurkadac85912012-05-18 15:04:49 -0700763 PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
764 Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
765 preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
766 icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
767
Winson Chung1120e032011-11-22 16:11:31 -0800768 mCanvas.setBitmap(preview);
Michael Jurka4ca39222012-05-15 17:18:34 -0700769 mCanvas.save();
Michael Jurkadac85912012-05-18 15:04:49 -0700770 renderDrawableToBitmap(icon, preview, 0, 0,
771 icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
Michael Jurka4ca39222012-05-15 17:18:34 -0700772 mCanvas.restore();
Adam Cohenaaf473c2011-08-03 12:02:47 -0700773 mCanvas.setBitmap(null);
Winson Chung1ed747a2011-05-03 16:18:34 -0700774 createItemInfo.spanX = createItemInfo.spanY = 1;
775 }
Winson Chung4b576be2011-04-27 17:40:20 -0700776
Peter Ng8db70002011-10-25 15:40:08 -0700777 // We use a custom alpha clip table for the default widget previews
778 Paint alphaClipPaint = null;
779 if (createItemInfo instanceof PendingAddWidgetInfo) {
Michael Jurka038f9d82011-11-03 13:50:45 -0700780 if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) {
Peter Ng8db70002011-10-25 15:40:08 -0700781 MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255);
782 alphaClipPaint = new Paint();
783 alphaClipPaint.setMaskFilter(alphaClipTable);
784 }
785 }
786
Winson Chung1120e032011-11-22 16:11:31 -0800787 // Save the preview for the outline generation, then dim the preview
788 outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
789 false);
Winson Chung1120e032011-11-22 16:11:31 -0800790
Winson Chung4b576be2011-04-27 17:40:20 -0700791 // Start the drag
Winson Chung1120e032011-11-22 16:11:31 -0800792 alphaClipPaint = null;
Winson Chung641d71d2012-04-26 15:58:01 -0700793 mLauncher.lockScreenOrientation();
Winson Chung1120e032011-11-22 16:11:31 -0800794 mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint);
795 mDragController.startDrag(image, preview, this, createItemInfo,
Winson Chung72d59842012-02-22 13:51:36 -0800796 DragController.DRAG_ACTION_COPY, null, scale);
Winson Chung1120e032011-11-22 16:11:31 -0800797 outline.recycle();
798 preview.recycle();
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700799 return true;
Winson Chung4b576be2011-04-27 17:40:20 -0700800 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800801
Winson Chung4b576be2011-04-27 17:40:20 -0700802 @Override
Adam Cohened66b2b2012-01-23 17:28:51 -0800803 protected boolean beginDragging(final View v) {
Winson Chung4b576be2011-04-27 17:40:20 -0700804 if (!super.beginDragging(v)) return false;
805
806 if (v instanceof PagedViewIcon) {
807 beginDraggingApplication(v);
808 } else if (v instanceof PagedViewWidget) {
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700809 if (!beginDraggingWidget(v)) {
810 return false;
811 }
Winson Chung4b576be2011-04-27 17:40:20 -0700812 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800813
814 // We delay entering spring-loaded mode slightly to make sure the UI
815 // thready is free of any work.
816 postDelayed(new Runnable() {
817 @Override
818 public void run() {
Adam Cohen1b36dc32012-02-13 19:27:37 -0800819 // We don't enter spring-loaded mode if the drag has been cancelled
820 if (mLauncher.getDragController().isDragging()) {
821 // Dismiss the cling
822 mLauncher.dismissAllAppsCling(null);
Adam Cohened66b2b2012-01-23 17:28:51 -0800823
Adam Cohen1b36dc32012-02-13 19:27:37 -0800824 // Reset the alpha on the dragged icon before we drag
825 resetDrawableState();
Adam Cohened66b2b2012-01-23 17:28:51 -0800826
Adam Cohen1b36dc32012-02-13 19:27:37 -0800827 // Go into spring loaded mode (must happen before we startDrag())
828 mLauncher.enterSpringLoadedDragMode();
829 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800830 }
Winson Chung72d59842012-02-22 13:51:36 -0800831 }, 150);
Adam Cohened66b2b2012-01-23 17:28:51 -0800832
Winson Chung785d2eb2011-04-14 16:08:02 -0700833 return true;
834 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800835
Winson Chunga48487a2012-03-20 16:19:37 -0700836 /**
837 * Clean up after dragging.
838 *
839 * @param target where the item was dragged to (can be null if the item was flung)
840 */
841 private void endDragging(View target, boolean isFlingToDelete, boolean success) {
Winson Chunga48487a2012-03-20 16:19:37 -0700842 if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
Adam Cohend4d7aa52011-07-19 21:47:37 -0700843 !(target instanceof DeleteDropTarget))) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700844 // Exit spring loaded mode if we have not successfully dropped or have not handled the
845 // drop in Workspace
846 mLauncher.exitSpringLoadedDragMode();
847 }
Winson Chung4b919f82012-05-01 10:44:08 -0700848 mLauncher.unlockScreenOrientation(false);
Winson Chung785d2eb2011-04-14 16:08:02 -0700849 }
850
Winson Chung785d2eb2011-04-14 16:08:02 -0700851 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700852 public View getContent() {
853 return null;
854 }
855
856 @Override
857 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700858 mInTransition = true;
859 if (toWorkspace) {
860 cancelAllTasks();
861 }
862 }
863
864 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700865 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700866 }
867
868 @Override
869 public void onLauncherTransitionStep(Launcher l, float t) {
870 }
871
872 @Override
873 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
874 mInTransition = false;
875 for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
876 onSyncWidgetPageItems(d);
877 }
878 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700879 for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) {
880 r.run();
881 }
882 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Michael Jurka5e368ff2012-05-14 23:13:15 -0700883 mForceDrawAllChildrenNextFrame = !toWorkspace;
Michael Jurka39e5d172012-03-12 18:36:12 -0700884 }
885
886 @Override
Winson Chunga48487a2012-03-20 16:19:37 -0700887 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
888 boolean success) {
889 // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
890 if (isFlingToDelete) return;
891
892 endDragging(target, false, success);
Winson Chungfc79c802011-05-02 13:35:34 -0700893
894 // Display an error message if the drag failed due to there not being enough space on the
895 // target layout we were dropping on.
896 if (!success) {
897 boolean showOutOfSpaceMessage = false;
898 if (target instanceof Workspace) {
899 int currentScreen = mLauncher.getCurrentWorkspaceScreen();
900 Workspace workspace = (Workspace) target;
901 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
Adam Cohenc0dcf592011-06-01 15:30:43 -0700902 ItemInfo itemInfo = (ItemInfo) d.dragInfo;
Winson Chungfc79c802011-05-02 13:35:34 -0700903 if (layout != null) {
904 layout.calculateSpans(itemInfo);
905 showOutOfSpaceMessage =
906 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
907 }
908 }
Winson Chungfc79c802011-05-02 13:35:34 -0700909 if (showOutOfSpaceMessage) {
Winson Chung93eef082012-03-23 15:59:27 -0700910 mLauncher.showOutOfSpaceMessage(false);
Winson Chungfc79c802011-05-02 13:35:34 -0700911 }
Adam Cohen7a326642012-02-22 12:03:22 -0800912
Winson Chung7bd1bbb2012-02-13 18:29:29 -0800913 d.deferDragViewCleanupPostAnimation = false;
Winson Chungfc79c802011-05-02 13:35:34 -0700914 }
Adam Cohen0e56cc92012-05-11 15:57:05 -0700915 cleanupWidgetPreloading(success);
Adam Cohen7a326642012-02-22 12:03:22 -0800916 mDraggingWidget = false;
Winson Chung785d2eb2011-04-14 16:08:02 -0700917 }
918
Winson Chunga48487a2012-03-20 16:19:37 -0700919 @Override
920 public void onFlingToDeleteCompleted() {
921 // We just dismiss the drag when we fling, so cleanup here
922 endDragging(null, true, true);
Adam Cohen0e56cc92012-05-11 15:57:05 -0700923 cleanupWidgetPreloading(false);
Winson Chunga48487a2012-03-20 16:19:37 -0700924 mDraggingWidget = false;
925 }
926
927 @Override
Winson Chung043f2af2012-03-01 16:09:54 -0800928 public boolean supportsFlingToDelete() {
Winson Chunga48487a2012-03-20 16:19:37 -0700929 return true;
Winson Chung043f2af2012-03-01 16:09:54 -0800930 }
931
Winson Chung7f0acdd2011-09-19 18:34:19 -0700932 @Override
933 protected void onDetachedFromWindow() {
934 super.onDetachedFromWindow();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700935 cancelAllTasks();
936 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700937
Michael Jurkae326f182011-11-21 14:05:46 -0800938 public void clearAllWidgetPages() {
939 cancelAllTasks();
940 int count = getChildCount();
941 for (int i = 0; i < count; i++) {
942 View v = getPageAt(i);
943 if (v instanceof PagedViewGridLayout) {
944 ((PagedViewGridLayout) v).removeAllViewsOnPage();
945 mDirtyPageContent.set(i, true);
946 }
947 }
948 }
949
Adam Cohen0cd3b642011-10-14 14:58:00 -0700950 private void cancelAllTasks() {
Winson Chung7f0acdd2011-09-19 18:34:19 -0700951 // Clean up all the async tasks
952 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
953 while (iter.hasNext()) {
954 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
955 task.cancel(false);
956 iter.remove();
Michael Jurka39e5d172012-03-12 18:36:12 -0700957 mDirtyPageContent.set(task.page, true);
Winson Chung7ce99852012-05-24 17:34:08 -0700958
959 // We've already preallocated the views for the data to load into, so clear them as well
960 View v = getPageAt(task.page);
961 if (v instanceof PagedViewGridLayout) {
962 ((PagedViewGridLayout) v).removeAllViewsOnPage();
963 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700964 }
Winson Chung83687b12012-04-25 16:01:01 -0700965 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700966 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Winson Chung7f0acdd2011-09-19 18:34:19 -0700967 }
968
Winson Chung785d2eb2011-04-14 16:08:02 -0700969 public void setContentType(ContentType type) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700970 if (type == ContentType.Widgets) {
971 invalidatePageData(mNumAppsPages, true);
972 } else if (type == ContentType.Applications) {
973 invalidatePageData(0, true);
974 }
Winson Chungb44b5242011-06-13 11:32:14 -0700975 }
976
Adam Cohen0cd3b642011-10-14 14:58:00 -0700977 protected void snapToPage(int whichPage, int delta, int duration) {
978 super.snapToPage(whichPage, delta, duration);
979 updateCurrentTab(whichPage);
Winson Chung68e4c642011-11-10 15:48:25 -0800980
981 // Update the thread priorities given the direction lookahead
982 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
983 while (iter.hasNext()) {
984 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -0700985 int pageIndex = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -0800986 if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
987 (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
988 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
989 } else {
990 task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
991 }
992 }
Adam Cohen0cd3b642011-10-14 14:58:00 -0700993 }
994
995 private void updateCurrentTab(int currentPage) {
996 AppsCustomizeTabHost tabHost = getTabHost();
Winson Chungc6f10b92011-11-14 11:39:07 -0800997 if (tabHost != null) {
998 String tag = tabHost.getCurrentTabTag();
999 if (tag != null) {
1000 if (currentPage >= mNumAppsPages &&
1001 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
1002 tabHost.setCurrentTabFromContent(ContentType.Widgets);
1003 } else if (currentPage < mNumAppsPages &&
1004 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1005 tabHost.setCurrentTabFromContent(ContentType.Applications);
1006 }
Winson Chung6a8103c2011-10-21 11:08:32 -07001007 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001008 }
1009 }
1010
Winson Chung785d2eb2011-04-14 16:08:02 -07001011 /*
1012 * Apps PagedView implementation
1013 */
Winson Chung63257c12011-05-05 17:06:13 -07001014 private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1015 int childCount = layout.getChildCount();
1016 for (int i = 0; i < childCount; ++i) {
1017 layout.getChildAt(i).setVisibility(visibility);
1018 }
1019 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001020 private void setupPage(PagedViewCellLayout layout) {
1021 layout.setCellCount(mCellCountX, mCellCountY);
1022 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1023 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1024 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1025
Winson Chung63257c12011-05-05 17:06:13 -07001026 // Note: We force a measure here to get around the fact that when we do layout calculations
1027 // immediately after syncing, we don't have a proper width. That said, we already know the
1028 // expected page width, so we can actually optimize by hiding all the TextView-based
1029 // children that are expensive to measure, and let that happen naturally later.
1030 setVisibilityOnChildren(layout, View.GONE);
Winson Chungdb1138b2011-06-30 14:39:35 -07001031 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001032 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -07001033 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -07001034 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -07001035 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -07001036 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001037
Winson Chungf314b0e2011-08-16 11:54:27 -07001038 public void syncAppsPageItems(int page, boolean immediate) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001039 // ensure that we have the right number of items on the pages
Winson Chung785d2eb2011-04-14 16:08:02 -07001040 int numCells = mCellCountX * mCellCountY;
1041 int startIndex = page * numCells;
1042 int endIndex = Math.min(startIndex + numCells, mApps.size());
Adam Cohen22f823d2011-09-01 17:22:18 -07001043 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
Winson Chung875de7e2011-06-28 14:25:17 -07001044
Winson Chung785d2eb2011-04-14 16:08:02 -07001045 layout.removeAllViewsOnPage();
Winson Chungb44b5242011-06-13 11:32:14 -07001046 ArrayList<Object> items = new ArrayList<Object>();
1047 ArrayList<Bitmap> images = new ArrayList<Bitmap>();
Winson Chung785d2eb2011-04-14 16:08:02 -07001048 for (int i = startIndex; i < endIndex; ++i) {
1049 ApplicationInfo info = mApps.get(i);
1050 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1051 R.layout.apps_customize_application, layout, false);
Winson Chunge4e50662012-01-23 14:45:13 -08001052 icon.applyFromApplicationInfo(info, true, this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001053 icon.setOnClickListener(this);
1054 icon.setOnLongClickListener(this);
1055 icon.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001056 icon.setOnKeyListener(this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001057
1058 int index = i - startIndex;
1059 int x = index % mCellCountX;
1060 int y = index / mCellCountX;
Winson Chung6a70e9f2011-05-17 16:24:49 -07001061 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
Winson Chungb44b5242011-06-13 11:32:14 -07001062
1063 items.add(info);
1064 images.add(info.iconBitmap);
Winson Chung785d2eb2011-04-14 16:08:02 -07001065 }
Winson Chungf0ea4d32011-06-06 14:27:16 -07001066
Winson Chungf0ea4d32011-06-06 14:27:16 -07001067 layout.createHardwareLayers();
Winson Chung785d2eb2011-04-14 16:08:02 -07001068 }
Winson Chungb44b5242011-06-13 11:32:14 -07001069
1070 /**
Winson Chung68e4c642011-11-10 15:48:25 -08001071 * A helper to return the priority for loading of the specified widget page.
1072 */
1073 private int getWidgetPageLoadPriority(int page) {
1074 // If we are snapping to another page, use that index as the target page index
1075 int toPage = mCurrentPage;
1076 if (mNextPage > -1) {
1077 toPage = mNextPage;
1078 }
1079
1080 // We use the distance from the target page as an initial guess of priority, but if there
1081 // are no pages of higher priority than the page specified, then bump up the priority of
1082 // the specified page.
1083 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1084 int minPageDiff = Integer.MAX_VALUE;
1085 while (iter.hasNext()) {
1086 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001087 minPageDiff = Math.abs(task.page - toPage);
Winson Chung68e4c642011-11-10 15:48:25 -08001088 }
1089
1090 int rawPageDiff = Math.abs(page - toPage);
1091 return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1092 }
1093 /**
Winson Chungb44b5242011-06-13 11:32:14 -07001094 * Return the appropriate thread priority for loading for a given page (we give the current
1095 * page much higher priority)
1096 */
1097 private int getThreadPriorityForPage(int page) {
1098 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
Winson Chung68e4c642011-11-10 15:48:25 -08001099 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001100 if (pageDiff <= 0) {
Winson Chung68e4c642011-11-10 15:48:25 -08001101 return Process.THREAD_PRIORITY_LESS_FAVORABLE;
Winson Chungb44b5242011-06-13 11:32:14 -07001102 } else if (pageDiff <= 1) {
Winson Chung68e4c642011-11-10 15:48:25 -08001103 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001104 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001105 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001106 }
1107 }
Winson Chungf314b0e2011-08-16 11:54:27 -07001108 private int getSleepForPage(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001109 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungf314b0e2011-08-16 11:54:27 -07001110 return Math.max(0, pageDiff * sPageSleepDelay);
1111 }
Winson Chungb44b5242011-06-13 11:32:14 -07001112 /**
1113 * Creates and executes a new AsyncTask to load a page of widget previews.
1114 */
1115 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
Winson Chungd2945262011-06-24 15:22:14 -07001116 int cellWidth, int cellHeight, int cellCountX) {
Winson Chung68e4c642011-11-10 15:48:25 -08001117
Winson Chungb44b5242011-06-13 11:32:14 -07001118 // Prune all tasks that are no longer needed
1119 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1120 while (iter.hasNext()) {
1121 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001122 int taskPage = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -08001123 if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1124 taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
Winson Chungb44b5242011-06-13 11:32:14 -07001125 task.cancel(false);
1126 iter.remove();
1127 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001128 task.setThreadPriority(getThreadPriorityForPage(taskPage));
Winson Chungb44b5242011-06-13 11:32:14 -07001129 }
1130 }
1131
Winson Chungf314b0e2011-08-16 11:54:27 -07001132 // 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 -07001133 final int sleepMs = getSleepForPage(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001134 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
Michael Jurka038f9d82011-11-03 13:50:45 -07001135 new AsyncTaskCallback() {
Winson Chungb44b5242011-06-13 11:32:14 -07001136 @Override
1137 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001138 try {
Winson Chung09945932011-09-20 14:22:40 -07001139 try {
1140 Thread.sleep(sleepMs);
1141 } catch (Exception e) {}
1142 loadWidgetPreviewsInBackground(task, data);
1143 } finally {
1144 if (task.isCancelled()) {
1145 data.cleanup(true);
1146 }
1147 }
Winson Chungb44b5242011-06-13 11:32:14 -07001148 }
1149 },
1150 new AsyncTaskCallback() {
1151 @Override
1152 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001153 mRunningTasks.remove(task);
1154 if (task.isCancelled()) return;
1155 // do cleanup inside onSyncWidgetPageItems
1156 onSyncWidgetPageItems(data);
Winson Chungb44b5242011-06-13 11:32:14 -07001157 }
Winson Chung09945932011-09-20 14:22:40 -07001158 });
Winson Chungb44b5242011-06-13 11:32:14 -07001159
1160 // Ensure that the task is appropriately prioritized and runs in parallel
Adam Cohen0cd3b642011-10-14 14:58:00 -07001161 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
Winson Chung875de7e2011-06-28 14:25:17 -07001162 AsyncTaskPageData.Type.LoadWidgetPreviewData);
Michael Jurka39e5d172012-03-12 18:36:12 -07001163 t.setThreadPriority(getThreadPriorityForPage(page));
Winson Chungb44b5242011-06-13 11:32:14 -07001164 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1165 mRunningTasks.add(t);
1166 }
Winson Chungb44b5242011-06-13 11:32:14 -07001167
Winson Chung785d2eb2011-04-14 16:08:02 -07001168 /*
1169 * Widgets PagedView implementation
1170 */
Winson Chung4e6a9762011-05-09 11:56:34 -07001171 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001172 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1173 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -07001174
1175 // Note: We force a measure here to get around the fact that when we do layout calculations
Winson Chungd52f3d82011-07-12 14:29:11 -07001176 // immediately after syncing, we don't have a proper width.
Winson Chung63257c12011-05-05 17:06:13 -07001177 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1178 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001179 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -07001180 layout.measure(widthSpec, heightSpec);
Winson Chung785d2eb2011-04-14 16:08:02 -07001181 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001182
Winson Chung5fc72b32011-10-11 17:53:58 -07001183 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurkadac85912012-05-18 15:04:49 -07001184 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
Winson Chung70fc4382011-08-08 15:31:33 -07001185 }
Michael Jurka92f3d462011-11-22 21:02:29 -08001186
Winson Chung5fc72b32011-10-11 17:53:58 -07001187 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
Michael Jurkadac85912012-05-18 15:04:49 -07001188 float scale) {
Winson Chung201bc822011-06-20 15:41:53 -07001189 if (bitmap != null) {
Winson Chungb44b5242011-06-13 11:32:14 -07001190 Canvas c = new Canvas(bitmap);
Winson Chung5fc72b32011-10-11 17:53:58 -07001191 c.scale(scale, scale);
Winson Chung201bc822011-06-20 15:41:53 -07001192 Rect oldBounds = d.copyBounds();
1193 d.setBounds(x, y, x + w, y + h);
1194 d.draw(c);
1195 d.setBounds(oldBounds); // Restore the bounds
Adam Cohenaaf473c2011-08-03 12:02:47 -07001196 c.setBitmap(null);
Winson Chung201bc822011-06-20 15:41:53 -07001197 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001198 }
Winson Chung5fc72b32011-10-11 17:53:58 -07001199
Michael Jurkadac85912012-05-18 15:04:49 -07001200 private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1201 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1202 final Canvas c = mCachedShortcutPreviewCanvas.get();
1203 if (tempBitmap == null ||
1204 tempBitmap.getWidth() != maxWidth ||
1205 tempBitmap.getHeight() != maxHeight) {
1206 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1207 mCachedShortcutPreviewBitmap.set(tempBitmap);
1208 } else {
1209 c.setBitmap(tempBitmap);
1210 c.drawColor(0, PorterDuff.Mode.CLEAR);
1211 c.setBitmap(null);
1212 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001213 // Render the icon
Winson Chung0b9fcf52011-10-31 13:05:15 -07001214 Drawable icon = mIconCache.getFullResIcon(info);
Michael Jurkadac85912012-05-18 15:04:49 -07001215
1216 int paddingTop =
1217 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1218 int paddingLeft =
1219 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1220 int paddingRight =
1221 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1222
1223 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
Michael Jurkadac85912012-05-18 15:04:49 -07001224
1225 renderDrawableToBitmap(
1226 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1227
1228 Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1229 c.setBitmap(preview);
1230 Paint p = mCachedShortcutPreviewPaint.get();
1231 if (p == null) {
1232 p = new Paint();
1233 ColorMatrix colorMatrix = new ColorMatrix();
1234 colorMatrix.setSaturation(0);
1235 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1236 p.setAlpha((int) (255 * 0.06f));
1237 //float density = 1f;
1238 //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1239 mCachedShortcutPreviewPaint.set(p);
1240 }
1241 c.drawBitmap(tempBitmap, 0, 0, p);
1242 c.setBitmap(null);
1243
1244 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1245
Winson Chungb44b5242011-06-13 11:32:14 -07001246 return preview;
Winson Chung1ed747a2011-05-03 16:18:34 -07001247 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001248
Michael Jurkadac85912012-05-18 15:04:49 -07001249 private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1250 int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1251 int maxHeight) {
Winson Chung4b576be2011-04-27 17:40:20 -07001252 // Load the preview image if possible
Michael Jurka038f9d82011-11-03 13:50:45 -07001253 String packageName = provider.getPackageName();
1254 if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1255 if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
Winson Chung4b576be2011-04-27 17:40:20 -07001256
Michael Jurka038f9d82011-11-03 13:50:45 -07001257 Drawable drawable = null;
1258 if (previewImage != 0) {
1259 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1260 if (drawable == null) {
Adam Cohen0e56cc92012-05-11 15:57:05 -07001261 Log.w(TAG, "Can't load widget preview drawable 0x" +
Michael Jurka038f9d82011-11-03 13:50:45 -07001262 Integer.toHexString(previewImage) + " for provider: " + provider);
Winson Chung4b576be2011-04-27 17:40:20 -07001263 }
1264 }
1265
Michael Jurka038f9d82011-11-03 13:50:45 -07001266 int bitmapWidth;
1267 int bitmapHeight;
Michael Jurkadac85912012-05-18 15:04:49 -07001268 Bitmap defaultPreview = null;
Michael Jurka038f9d82011-11-03 13:50:45 -07001269 boolean widgetPreviewExists = (drawable != null);
1270 if (widgetPreviewExists) {
1271 bitmapWidth = drawable.getIntrinsicWidth();
1272 bitmapHeight = drawable.getIntrinsicHeight();
Michael Jurka038f9d82011-11-03 13:50:45 -07001273 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001274 // Generate a preview image if we couldn't load one
Michael Jurkac7e52f52012-03-26 06:20:31 -07001275 if (cellHSpan < 1) cellHSpan = 1;
1276 if (cellVSpan < 1) cellVSpan = 1;
Michael Jurkadac85912012-05-18 15:04:49 -07001277
1278 BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1279 .getDrawable(R.drawable.widget_preview_tile);
1280 final int previewDrawableWidth = previewDrawable
1281 .getIntrinsicWidth();
1282 final int previewDrawableHeight = previewDrawable
1283 .getIntrinsicHeight();
1284 bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1285 bitmapHeight = previewDrawableHeight * cellVSpan;
1286
1287 defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1288 Config.ARGB_8888);
1289 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1290 c.setBitmap(defaultPreview);
1291 previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1292 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1293 Shader.TileMode.REPEAT);
1294 previewDrawable.draw(c);
1295 c.setBitmap(null);
1296
1297 // Draw the icon in the top left corner
1298 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1299 int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1300 float iconScale = Math.min((float) smallestSide
1301 / (mAppIconSize + 2 * minOffset), 1f);
1302
1303 try {
1304 Drawable icon = null;
1305 int hoffset =
1306 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1307 int yoffset =
1308 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1309 if (iconId > 0)
1310 icon = mIconCache.getFullResIcon(packageName, iconId);
Michael Jurkadac85912012-05-18 15:04:49 -07001311 if (icon != null) {
1312 renderDrawableToBitmap(icon, defaultPreview, hoffset,
1313 yoffset, (int) (mAppIconSize * iconScale),
1314 (int) (mAppIconSize * iconScale));
Winson Chung5fc72b32011-10-11 17:53:58 -07001315 }
Michael Jurkadac85912012-05-18 15:04:49 -07001316 } catch (Resources.NotFoundException e) {
Winson Chung1ed747a2011-05-03 16:18:34 -07001317 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001318 }
1319
Michael Jurkadac85912012-05-18 15:04:49 -07001320 // Scale to fit width only - let the widget preview be clipped in the
1321 // vertical dimension
Michael Jurka038f9d82011-11-03 13:50:45 -07001322 float scale = 1f;
1323 if (bitmapWidth > maxWidth) {
1324 scale = maxWidth / (float) bitmapWidth;
1325 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001326 if (scale != 1f) {
1327 bitmapWidth = (int) (scale * bitmapWidth);
1328 bitmapHeight = (int) (scale * bitmapHeight);
1329 }
1330
Michael Jurkadac85912012-05-18 15:04:49 -07001331 Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1332 Config.ARGB_8888);
Michael Jurka038f9d82011-11-03 13:50:45 -07001333
Michael Jurkadac85912012-05-18 15:04:49 -07001334 // Draw the scaled preview into the final bitmap
Michael Jurka038f9d82011-11-03 13:50:45 -07001335 if (widgetPreviewExists) {
Michael Jurkadac85912012-05-18 15:04:49 -07001336 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1337 bitmapHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001338 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001339 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1340 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1341 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1342 c.setBitmap(preview);
1343 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1344 dest.set(0, 0, preview.getWidth(), preview.getHeight());
1345
1346 Paint p = mCachedAppWidgetPreviewPaint.get();
1347 if (p == null) {
1348 p = new Paint();
1349 p.setFilterBitmap(true);
1350 mCachedAppWidgetPreviewPaint.set(p);
Peter Ng8db70002011-10-25 15:40:08 -07001351 }
Michael Jurkadac85912012-05-18 15:04:49 -07001352 c.drawBitmap(defaultPreview, src, dest, p);
1353 c.setBitmap(null);
Winson Chung4b576be2011-04-27 17:40:20 -07001354 }
Winson Chungb44b5242011-06-13 11:32:14 -07001355 return preview;
Winson Chung785d2eb2011-04-14 16:08:02 -07001356 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001357
Michael Jurka038f9d82011-11-03 13:50:45 -07001358 public void syncWidgetPageItems(final int page, final boolean immediate) {
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001359 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
Winson Chungb44b5242011-06-13 11:32:14 -07001360
Winson Chungd2945262011-06-24 15:22:14 -07001361 // Calculate the dimensions of each cell we are giving to each widget
Michael Jurka038f9d82011-11-03 13:50:45 -07001362 final ArrayList<Object> items = new ArrayList<Object>();
1363 int contentWidth = mWidgetSpacingLayout.getContentWidth();
1364 final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001365 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
Michael Jurka038f9d82011-11-03 13:50:45 -07001366 int contentHeight = mWidgetSpacingLayout.getContentHeight();
1367 final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001368 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
Winson Chungd2945262011-06-24 15:22:14 -07001369
Winson Chunge4a647f2011-09-30 14:41:25 -07001370 // Prepare the set of widgets to load previews for in the background
Michael Jurka39e5d172012-03-12 18:36:12 -07001371 int offset = (page - mNumAppsPages) * numItemsPerPage;
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001372 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1373 items.add(mWidgets.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -07001374 }
1375
Winson Chunge4a647f2011-09-30 14:41:25 -07001376 // Prepopulate the pages with the other widget info, and fill in the previews later
Michael Jurka39e5d172012-03-12 18:36:12 -07001377 final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chunge4a647f2011-09-30 14:41:25 -07001378 layout.setColumnCount(layout.getCellCountX());
1379 for (int i = 0; i < items.size(); ++i) {
1380 Object rawInfo = items.get(i);
1381 PendingAddItemInfo createItemInfo = null;
1382 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1383 R.layout.apps_customize_widget, layout, false);
1384 if (rawInfo instanceof AppWidgetProviderInfo) {
1385 // Fill in the widget information
1386 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1387 createItemInfo = new PendingAddWidgetInfo(info, null, null);
Adam Cohen1f362702012-04-04 14:58:12 -07001388
1389 // Determine the widget spans and min resize spans.
Adam Cohen2f093b62012-04-30 18:59:53 -07001390 int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001391 createItemInfo.spanX = spanXY[0];
1392 createItemInfo.spanY = spanXY[1];
Adam Cohen2f093b62012-04-30 18:59:53 -07001393 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001394 createItemInfo.minSpanX = minSpanXY[0];
1395 createItemInfo.minSpanY = minSpanXY[1];
1396
1397 widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
Winson Chunge4a647f2011-09-30 14:41:25 -07001398 widget.setTag(createItemInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -08001399 widget.setShortPressListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001400 } else if (rawInfo instanceof ResolveInfo) {
1401 // Fill in the shortcuts information
1402 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001403 createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
Winson Chunge4a647f2011-09-30 14:41:25 -07001404 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1405 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1406 info.activityInfo.name);
Michael Jurka82369a12012-01-12 08:08:38 -08001407 widget.applyFromResolveInfo(mPackageManager, info);
Winson Chunge4a647f2011-09-30 14:41:25 -07001408 widget.setTag(createItemInfo);
1409 }
1410 widget.setOnClickListener(this);
1411 widget.setOnLongClickListener(this);
1412 widget.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001413 widget.setOnKeyListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001414
1415 // Layout each widget
1416 int ix = i % mWidgetCountX;
1417 int iy = i / mWidgetCountX;
1418 GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1419 GridLayout.spec(iy, GridLayout.LEFT),
1420 GridLayout.spec(ix, GridLayout.TOP));
1421 lp.width = cellWidth;
1422 lp.height = cellHeight;
1423 lp.setGravity(Gravity.TOP | Gravity.LEFT);
1424 if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1425 if (iy > 0) lp.topMargin = mWidgetHeightGap;
1426 layout.addView(widget, lp);
1427 }
1428
Michael Jurka038f9d82011-11-03 13:50:45 -07001429 // wait until a call on onLayout to start loading, because
1430 // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1431 // TODO: can we do a measure/layout immediately?
1432 layout.setOnLayoutListener(new Runnable() {
1433 public void run() {
1434 // Load the widget previews
1435 int maxPreviewWidth = cellWidth;
1436 int maxPreviewHeight = cellHeight;
1437 if (layout.getChildCount() > 0) {
1438 PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1439 int[] maxSize = w.getPreviewSize();
1440 maxPreviewWidth = maxSize[0];
1441 maxPreviewHeight = maxSize[1];
1442 }
1443 if (immediate) {
1444 AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1445 maxPreviewWidth, maxPreviewHeight, null, null);
1446 loadWidgetPreviewsInBackground(null, data);
1447 onSyncWidgetPageItems(data);
1448 } else {
Michael Jurkaf6a96902012-06-06 11:48:13 -07001449 if (mInTransition) {
1450 mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
1451 } else {
1452 prepareLoadWidgetPreviewsTask(page, items,
1453 maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1454 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001455 }
1456 }
1457 });
Winson Chungf314b0e2011-08-16 11:54:27 -07001458 }
1459 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1460 AsyncTaskPageData data) {
Winson Chung68e4c642011-11-10 15:48:25 -08001461 // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1462 // previews synchronously
Winson Chungf314b0e2011-08-16 11:54:27 -07001463 if (task != null) {
1464 // Ensure that this task starts running at the correct priority
1465 task.syncThreadPriority();
1466 }
1467
1468 // Load each of the widget/shortcut previews
1469 ArrayList<Object> items = data.items;
1470 ArrayList<Bitmap> images = data.generatedImages;
1471 int count = items.size();
Winson Chungf314b0e2011-08-16 11:54:27 -07001472 for (int i = 0; i < count; ++i) {
1473 if (task != null) {
1474 // Ensure we haven't been cancelled yet
1475 if (task.isCancelled()) break;
1476 // Before work on each item, ensure that this task is running at the correct
1477 // priority
1478 task.syncThreadPriority();
1479 }
1480
1481 Object rawInfo = items.get(i);
1482 if (rawInfo instanceof AppWidgetProviderInfo) {
1483 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
Adam Cohen2f093b62012-04-30 18:59:53 -07001484 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
Winson Chung72d59842012-02-22 13:51:36 -08001485
1486 int maxWidth = Math.min(data.maxImageWidth,
1487 mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1488 int maxHeight = Math.min(data.maxImageHeight,
1489 mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
Michael Jurka038f9d82011-11-03 13:50:45 -07001490 Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
Winson Chung72d59842012-02-22 13:51:36 -08001491 cellSpans[0], cellSpans[1], maxWidth, maxHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001492 images.add(b);
Winson Chungf314b0e2011-08-16 11:54:27 -07001493 } else if (rawInfo instanceof ResolveInfo) {
1494 // Fill in the shortcuts information
1495 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001496 images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
Winson Chungf314b0e2011-08-16 11:54:27 -07001497 }
1498 }
Winson Chungb44b5242011-06-13 11:32:14 -07001499 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001500
Winson Chungb44b5242011-06-13 11:32:14 -07001501 private void onSyncWidgetPageItems(AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001502 if (mInTransition) {
1503 mDeferredSyncWidgetPageItems.add(data);
1504 return;
Winson Chung785d2eb2011-04-14 16:08:02 -07001505 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001506 try {
1507 int page = data.page;
1508 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001509
Michael Jurka39e5d172012-03-12 18:36:12 -07001510 ArrayList<Object> items = data.items;
1511 int count = items.size();
1512 for (int i = 0; i < count; ++i) {
1513 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1514 if (widget != null) {
1515 Bitmap preview = data.generatedImages.get(i);
1516 widget.applyPreview(new FastBitmapDrawable(preview), i);
1517 }
1518 }
Winson Chung68e4c642011-11-10 15:48:25 -08001519
Michael Jurka39e5d172012-03-12 18:36:12 -07001520 layout.createHardwareLayer();
1521 invalidate();
1522
1523 // Update all thread priorities
1524 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1525 while (iter.hasNext()) {
1526 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1527 int pageIndex = task.page;
1528 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1529 }
1530 } finally {
1531 data.cleanup(false);
Winson Chung68e4c642011-11-10 15:48:25 -08001532 }
Winson Chungb44b5242011-06-13 11:32:14 -07001533 }
Winson Chung46af2e82011-05-09 16:00:53 -07001534
Winson Chung785d2eb2011-04-14 16:08:02 -07001535 @Override
1536 public void syncPages() {
1537 removeAllViews();
Adam Cohen0cd3b642011-10-14 14:58:00 -07001538 cancelAllTasks();
Winson Chung875de7e2011-06-28 14:25:17 -07001539
Adam Cohen0cd3b642011-10-14 14:58:00 -07001540 Context context = getContext();
1541 for (int j = 0; j < mNumWidgetPages; ++j) {
1542 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1543 mWidgetCountY);
1544 setupPage(layout);
Michael Jurka39e5d172012-03-12 18:36:12 -07001545 addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
Adam Cohen0cd3b642011-10-14 14:58:00 -07001546 LayoutParams.MATCH_PARENT));
Winson Chung875de7e2011-06-28 14:25:17 -07001547 }
1548
Adam Cohen0cd3b642011-10-14 14:58:00 -07001549 for (int i = 0; i < mNumAppsPages; ++i) {
1550 PagedViewCellLayout layout = new PagedViewCellLayout(context);
1551 setupPage(layout);
1552 addView(layout);
Winson Chung785d2eb2011-04-14 16:08:02 -07001553 }
1554 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001555
Winson Chung785d2eb2011-04-14 16:08:02 -07001556 @Override
Winson Chungf314b0e2011-08-16 11:54:27 -07001557 public void syncPageItems(int page, boolean immediate) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07001558 if (page < mNumAppsPages) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001559 syncAppsPageItems(page, immediate);
Adam Cohen0cd3b642011-10-14 14:58:00 -07001560 } else {
Michael Jurka39e5d172012-03-12 18:36:12 -07001561 syncWidgetPageItems(page, immediate);
Winson Chung785d2eb2011-04-14 16:08:02 -07001562 }
1563 }
1564
Adam Cohen22f823d2011-09-01 17:22:18 -07001565 // We want our pages to be z-ordered such that the further a page is to the left, the higher
1566 // it is in the z-order. This is important to insure touch events are handled correctly.
1567 View getPageAt(int index) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001568 return getChildAt(indexToPage(index));
Adam Cohen22f823d2011-09-01 17:22:18 -07001569 }
1570
Adam Cohenae4f1552011-10-20 00:15:42 -07001571 @Override
1572 protected int indexToPage(int index) {
1573 return getChildCount() - index - 1;
1574 }
1575
Adam Cohen22f823d2011-09-01 17:22:18 -07001576 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1577 @Override
1578 protected void screenScrolled(int screenCenter) {
1579 super.screenScrolled(screenCenter);
Adam Cohen22f823d2011-09-01 17:22:18 -07001580
1581 for (int i = 0; i < getChildCount(); i++) {
1582 View v = getPageAt(i);
1583 if (v != null) {
Adam Cohenb5ba0972011-09-07 18:02:31 -07001584 float scrollProgress = getScrollProgress(screenCenter, v, i);
Adam Cohen22f823d2011-09-01 17:22:18 -07001585
1586 float interpolatedProgress =
1587 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1588 float scale = (1 - interpolatedProgress) +
1589 interpolatedProgress * TRANSITION_SCALE_FACTOR;
1590 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001591
Adam Cohen2591f6a2011-10-25 14:36:40 -07001592 float alpha;
1593
Winson Chungd167e2a2012-04-26 13:13:01 -07001594 if (scrollProgress < 0) {
Adam Cohen2591f6a2011-10-25 14:36:40 -07001595 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
Adam Cohenb5ba0972011-09-07 18:02:31 -07001596 1 - Math.abs(scrollProgress)) : 1.0f;
Adam Cohen2591f6a2011-10-25 14:36:40 -07001597 } else {
1598 // On large screens we need to fade the page as it nears its leftmost position
1599 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1600 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001601
1602 v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1603 int pageWidth = v.getMeasuredWidth();
1604 int pageHeight = v.getMeasuredHeight();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001605
1606 if (PERFORM_OVERSCROLL_ROTATION) {
1607 if (i == 0 && scrollProgress < 0) {
1608 // Overscroll to the left
1609 v.setPivotX(TRANSITION_PIVOT * pageWidth);
1610 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1611 scale = 1.0f;
1612 alpha = 1.0f;
1613 // On the first page, we don't want the page to have any lateral motion
Adam Cohenebea84d2011-11-09 17:20:41 -08001614 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001615 } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1616 // Overscroll to the right
1617 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1618 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1619 scale = 1.0f;
1620 alpha = 1.0f;
1621 // On the last page, we don't want the page to have any lateral motion.
Adam Cohenebea84d2011-11-09 17:20:41 -08001622 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001623 } else {
1624 v.setPivotY(pageHeight / 2.0f);
1625 v.setPivotX(pageWidth / 2.0f);
1626 v.setRotationY(0f);
1627 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001628 }
1629
1630 v.setTranslationX(translationX);
1631 v.setScaleX(scale);
1632 v.setScaleY(scale);
1633 v.setAlpha(alpha);
Adam Cohen4e844012011-11-09 13:48:04 -08001634
1635 // If the view has 0 alpha, we set it to be invisible so as to prevent
1636 // it from accepting touches
Michael Jurka8b805b12012-04-18 14:23:14 -07001637 if (alpha == 0) {
Adam Cohen4e844012011-11-09 13:48:04 -08001638 v.setVisibility(INVISIBLE);
1639 } else if (v.getVisibility() != VISIBLE) {
1640 v.setVisibility(VISIBLE);
1641 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001642 }
1643 }
1644 }
1645
1646 protected void overScroll(float amount) {
Adam Cohencff6af82011-09-13 14:51:53 -07001647 acceleratedOverScroll(amount);
Adam Cohen22f823d2011-09-01 17:22:18 -07001648 }
1649
Winson Chung785d2eb2011-04-14 16:08:02 -07001650 /**
1651 * Used by the parent to get the content width to set the tab bar to
1652 * @return
1653 */
1654 public int getPageContentWidth() {
1655 return mContentWidth;
1656 }
1657
Winson Chungb26f3d62011-06-02 10:49:29 -07001658 @Override
Winson Chungb26f3d62011-06-02 10:49:29 -07001659 protected void onPageEndMoving() {
Winson Chungb26f3d62011-06-02 10:49:29 -07001660 super.onPageEndMoving();
Michael Jurka5e368ff2012-05-14 23:13:15 -07001661 mForceDrawAllChildrenNextFrame = true;
Winson Chung5afbf7b2011-07-25 11:53:08 -07001662 // We reset the save index when we change pages so that it will be recalculated on next
1663 // rotation
1664 mSaveInstanceStateItemIndex = -1;
Winson Chungb26f3d62011-06-02 10:49:29 -07001665 }
1666
Winson Chung785d2eb2011-04-14 16:08:02 -07001667 /*
1668 * AllAppsView implementation
1669 */
Winson Chung785d2eb2011-04-14 16:08:02 -07001670 public void setup(Launcher launcher, DragController dragController) {
1671 mLauncher = launcher;
1672 mDragController = dragController;
1673 }
Winson Chung9802ac92012-06-08 16:01:58 -07001674
1675 /**
1676 * We should call thise method whenever the core data changes (mApps, mWidgets) so that we can
1677 * appropriately determine when to invalidate the PagedView page data. In cases where the data
1678 * has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the
1679 * next onMeasure() pass, which will trigger an invalidatePageData() itself.
1680 */
1681 private void invalidateOnDataChange() {
1682 if (!isDataReady()) {
1683 // The next layout pass will trigger data-ready if both widgets and apps are set, so
1684 // request a layout to trigger the page data when ready.
1685 requestLayout();
1686 } else {
1687 cancelAllTasks();
1688 invalidatePageData();
1689 }
1690 }
1691
Winson Chung785d2eb2011-04-14 16:08:02 -07001692 public void setApps(ArrayList<ApplicationInfo> list) {
1693 mApps = list;
1694 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001695 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001696 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001697 }
1698 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1699 // We add it in place, in alphabetical order
1700 int count = list.size();
1701 for (int i = 0; i < count; ++i) {
1702 ApplicationInfo info = list.get(i);
1703 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1704 if (index < 0) {
1705 mApps.add(-(index + 1), info);
1706 }
1707 }
1708 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001709 public void addApps(ArrayList<ApplicationInfo> list) {
1710 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001711 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001712 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001713 }
1714 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1715 ComponentName removeComponent = item.intent.getComponent();
1716 int length = list.size();
1717 for (int i = 0; i < length; ++i) {
1718 ApplicationInfo info = list.get(i);
1719 if (info.intent.getComponent().equals(removeComponent)) {
1720 return i;
1721 }
1722 }
1723 return -1;
1724 }
Winson Chungcd810732012-06-18 16:45:43 -07001725 private int findAppByPackage(List<ApplicationInfo> list, String packageName) {
1726 int length = list.size();
1727 for (int i = 0; i < length; ++i) {
1728 ApplicationInfo info = list.get(i);
1729 if (ItemInfo.getPackageName(info.intent).equals(packageName)) {
1730 return i;
1731 }
1732 }
1733 return -1;
1734 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001735 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1736 // loop through all the apps and remove apps that have the same component
1737 int length = list.size();
1738 for (int i = 0; i < length; ++i) {
1739 ApplicationInfo info = list.get(i);
1740 int removeIndex = findAppByComponent(mApps, info);
1741 if (removeIndex > -1) {
1742 mApps.remove(removeIndex);
Winson Chung785d2eb2011-04-14 16:08:02 -07001743 }
1744 }
1745 }
Winson Chungcd810732012-06-18 16:45:43 -07001746 private void removeAppsWithPackageNameWithoutInvalidate(ArrayList<String> packageNames) {
1747 // loop through all the package names and remove apps that have the same package name
1748 for (String pn : packageNames) {
1749 int removeIndex = findAppByPackage(mApps, pn);
1750 while (removeIndex > -1) {
1751 mApps.remove(removeIndex);
1752 removeIndex = findAppByPackage(mApps, pn);
1753 }
1754 }
1755 }
1756 public void removeApps(ArrayList<String> packageNames) {
1757 removeAppsWithPackageNameWithoutInvalidate(packageNames);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001758 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001759 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001760 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001761 public void updateApps(ArrayList<ApplicationInfo> list) {
1762 // We remove and re-add the updated applications list because it's properties may have
1763 // changed (ie. the title), and this will ensure that the items will be in their proper
1764 // place in the list.
1765 removeAppsWithoutInvalidate(list);
1766 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001767 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001768 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001769 }
Michael Jurka35aa14d2011-07-07 17:01:08 -07001770
Winson Chung785d2eb2011-04-14 16:08:02 -07001771 public void reset() {
Winson Chung649668f2012-01-10 13:07:16 -08001772 // If we have reset, then we should not continue to restore the previous state
1773 mSaveInstanceStateItemIndex = -1;
1774
Adam Cohenb64d36e2011-10-17 21:48:02 -07001775 AppsCustomizeTabHost tabHost = getTabHost();
1776 String tag = tabHost.getCurrentTabTag();
Winson Chung6a8103c2011-10-21 11:08:32 -07001777 if (tag != null) {
1778 if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1779 tabHost.setCurrentTabFromContent(ContentType.Applications);
1780 }
Adam Cohenb64d36e2011-10-17 21:48:02 -07001781 }
Winson Chung649668f2012-01-10 13:07:16 -08001782
Adam Cohenb64d36e2011-10-17 21:48:02 -07001783 if (mCurrentPage != 0) {
1784 invalidatePageData(0);
1785 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001786 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001787
1788 private AppsCustomizeTabHost getTabHost() {
1789 return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1790 }
1791
Winson Chung785d2eb2011-04-14 16:08:02 -07001792 public void dumpState() {
1793 // TODO: Dump information related to current list of Applications, Widgets, etc.
Adam Cohen0e56cc92012-05-11 15:57:05 -07001794 ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1795 dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
Winson Chung785d2eb2011-04-14 16:08:02 -07001796 }
Adam Cohen4e844012011-11-09 13:48:04 -08001797
Winson Chung785d2eb2011-04-14 16:08:02 -07001798 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chungd2945262011-06-24 15:22:14 -07001799 ArrayList<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001800 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -07001801 for (Object i: list) {
1802 if (i instanceof AppWidgetProviderInfo) {
1803 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1804 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
1805 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1806 + " initialLayout=" + info.initialLayout
1807 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1808 } else if (i instanceof ResolveInfo) {
1809 ResolveInfo info = (ResolveInfo) i;
1810 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1811 + info.icon);
1812 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001813 }
1814 }
Adam Cohen4e844012011-11-09 13:48:04 -08001815
Winson Chung785d2eb2011-04-14 16:08:02 -07001816 public void surrender() {
1817 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1818 // should stop this now.
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001819
1820 // Stop all background tasks
1821 cancelAllTasks();
Winson Chung785d2eb2011-04-14 16:08:02 -07001822 }
Winson Chung007c6982011-06-14 13:27:53 -07001823
Winson Chunge4e50662012-01-23 14:45:13 -08001824 @Override
1825 public void iconPressed(PagedViewIcon icon) {
1826 // Reset the previously pressed icon and store a reference to the pressed icon so that
1827 // we can reset it on return to Launcher (in Launcher.onResume())
1828 if (mPressedIcon != null) {
1829 mPressedIcon.resetDrawableState();
1830 }
1831 mPressedIcon = icon;
1832 }
1833
1834 public void resetDrawableState() {
1835 if (mPressedIcon != null) {
1836 mPressedIcon.resetDrawableState();
1837 mPressedIcon = null;
1838 }
1839 }
Winson Chung68e4c642011-11-10 15:48:25 -08001840
Winson Chungb44b5242011-06-13 11:32:14 -07001841 /*
1842 * We load an extra page on each side to prevent flashes from scrolling and loading of the
1843 * widget previews in the background with the AsyncTasks.
1844 */
Winson Chung68e4c642011-11-10 15:48:25 -08001845 final static int sLookBehindPageCount = 2;
1846 final static int sLookAheadPageCount = 2;
Winson Chungb44b5242011-06-13 11:32:14 -07001847 protected int getAssociatedLowerPageBound(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001848 final int count = getChildCount();
1849 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1850 int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1851 return windowMinIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001852 }
1853 protected int getAssociatedUpperPageBound(int page) {
1854 final int count = getChildCount();
Winson Chung68e4c642011-11-10 15:48:25 -08001855 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1856 int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1857 count - 1);
1858 return windowMaxIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001859 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07001860
1861 @Override
1862 protected String getCurrentPageDescription() {
1863 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1864 int stringId = R.string.default_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001865 int count = 0;
1866
Adam Cohen0cd3b642011-10-14 14:58:00 -07001867 if (page < mNumAppsPages) {
Winson Chung6a0f57d2011-06-29 20:10:49 -07001868 stringId = R.string.apps_customize_apps_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001869 count = mNumAppsPages;
Adam Cohen0cd3b642011-10-14 14:58:00 -07001870 } else {
1871 page -= mNumAppsPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001872 stringId = R.string.apps_customize_widgets_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001873 count = mNumWidgetPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001874 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001875
Michael Jurka8b805b12012-04-18 14:23:14 -07001876 return String.format(getContext().getString(stringId), page + 1, count);
Winson Chung6a0f57d2011-06-29 20:10:49 -07001877 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001878}