blob: 8cb169e17f949d3dcad059771ce55d124ff6a617 [file] [log] [blame]
Winson Chung785d2eb2011-04-14 16:08:02 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
Winson Chung55b65502011-05-26 12:03:43 -070019import android.animation.AnimatorSet;
Winson Chung4b576be2011-04-27 17:40:20 -070020import android.animation.ObjectAnimator;
Winson Chungd2e87b32011-06-02 10:53:07 -070021import android.animation.ValueAnimator;
Adam Cohened66b2b2012-01-23 17:28:51 -080022import android.appwidget.AppWidgetHostView;
Winson Chung785d2eb2011-04-14 16:08:02 -070023import android.appwidget.AppWidgetManager;
24import android.appwidget.AppWidgetProviderInfo;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.Intent;
28import android.content.pm.PackageManager;
29import android.content.pm.ResolveInfo;
Winson Chungf0ea4d32011-06-06 14:27:16 -070030import android.content.res.Configuration;
Winson Chung785d2eb2011-04-14 16:08:02 -070031import android.content.res.Resources;
32import android.content.res.TypedArray;
33import android.graphics.Bitmap;
Adam Cohen4e844012011-11-09 13:48:04 -080034import android.graphics.Bitmap.Config;
Winson Chung785d2eb2011-04-14 16:08:02 -070035import android.graphics.Canvas;
Michael Jurkadac85912012-05-18 15:04:49 -070036import android.graphics.ColorMatrix;
37import android.graphics.ColorMatrixColorFilter;
38import android.graphics.Insets;
Peter Ng8db70002011-10-25 15:40:08 -070039import android.graphics.MaskFilter;
Winson Chung72d59842012-02-22 13:51:36 -080040import android.graphics.Matrix;
Peter Ng8db70002011-10-25 15:40:08 -070041import android.graphics.Paint;
Michael Jurkadac85912012-05-18 15:04:49 -070042import android.graphics.PorterDuff;
Winson Chung785d2eb2011-04-14 16:08:02 -070043import android.graphics.Rect;
Winson Chung72d59842012-02-22 13:51:36 -080044import android.graphics.RectF;
Michael Jurkadac85912012-05-18 15:04:49 -070045import android.graphics.Shader;
Peter Ng8db70002011-10-25 15:40:08 -070046import android.graphics.TableMaskFilter;
Michael Jurkadac85912012-05-18 15:04:49 -070047import android.graphics.drawable.BitmapDrawable;
Winson Chung785d2eb2011-04-14 16:08:02 -070048import android.graphics.drawable.Drawable;
Winson Chungb44b5242011-06-13 11:32:14 -070049import android.os.AsyncTask;
50import android.os.Process;
Winson Chung785d2eb2011-04-14 16:08:02 -070051import android.util.AttributeSet;
52import android.util.Log;
Winson Chung72d8b392011-07-29 13:56:44 -070053import android.view.Gravity;
Winson Chungc6f10b92011-11-14 11:39:07 -080054import android.view.KeyEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070055import android.view.LayoutInflater;
Winson Chungde1af762011-07-21 16:44:07 -070056import android.view.MotionEvent;
Winson Chung785d2eb2011-04-14 16:08:02 -070057import android.view.View;
Winson Chung63257c12011-05-05 17:06:13 -070058import android.view.ViewGroup;
Winson Chung55b65502011-05-26 12:03:43 -070059import android.view.animation.AccelerateInterpolator;
Adam Cohen2591f6a2011-10-25 14:36:40 -070060import android.view.animation.DecelerateInterpolator;
Winson Chungfd3385f2011-06-15 19:51:24 -070061import android.widget.GridLayout;
Winson Chung785d2eb2011-04-14 16:08:02 -070062import android.widget.ImageView;
Michael Jurkadac85912012-05-18 15:04:49 -070063import android.widget.LinearLayout;
Winson Chung55b65502011-05-26 12:03:43 -070064import android.widget.Toast;
Winson Chung785d2eb2011-04-14 16:08:02 -070065
66import com.android.launcher.R;
Adam Cohenc0dcf592011-06-01 15:30:43 -070067import com.android.launcher2.DropTarget.DragObject;
68
69import java.util.ArrayList;
70import java.util.Collections;
71import java.util.Iterator;
72import java.util.List;
Michael Jurkadac85912012-05-18 15:04:49 -070073import java.lang.ref.WeakReference;
Winson Chung785d2eb2011-04-14 16:08:02 -070074
Winson Chungb44b5242011-06-13 11:32:14 -070075/**
76 * A simple callback interface which also provides the results of the task.
77 */
78interface AsyncTaskCallback {
79 void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data);
80}
Winson Chung4e076542011-06-23 13:04:10 -070081
Winson Chungb44b5242011-06-13 11:32:14 -070082/**
83 * The data needed to perform either of the custom AsyncTasks.
84 */
85class AsyncTaskPageData {
Winson Chung875de7e2011-06-28 14:25:17 -070086 enum Type {
Michael Jurka82369a12012-01-12 08:08:38 -080087 LoadWidgetPreviewData
Winson Chung875de7e2011-06-28 14:25:17 -070088 }
89
Winson Chungb44b5242011-06-13 11:32:14 -070090 AsyncTaskPageData(int p, ArrayList<Object> l, ArrayList<Bitmap> si, AsyncTaskCallback bgR,
91 AsyncTaskCallback postR) {
92 page = p;
93 items = l;
Winson Chung4e076542011-06-23 13:04:10 -070094 sourceImages = si;
95 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -070096 maxImageWidth = maxImageHeight = -1;
Winson Chungb44b5242011-06-13 11:32:14 -070097 doInBackgroundCallback = bgR;
98 postExecuteCallback = postR;
99 }
Michael Jurka038f9d82011-11-03 13:50:45 -0700100 AsyncTaskPageData(int p, ArrayList<Object> l, int cw, int ch, AsyncTaskCallback bgR,
Winson Chungb44b5242011-06-13 11:32:14 -0700101 AsyncTaskCallback postR) {
102 page = p;
103 items = l;
Winson Chung4e076542011-06-23 13:04:10 -0700104 generatedImages = new ArrayList<Bitmap>();
Michael Jurka038f9d82011-11-03 13:50:45 -0700105 maxImageWidth = cw;
106 maxImageHeight = ch;
Winson Chungb44b5242011-06-13 11:32:14 -0700107 doInBackgroundCallback = bgR;
108 postExecuteCallback = postR;
109 }
Winson Chung09945932011-09-20 14:22:40 -0700110 void cleanup(boolean cancelled) {
111 // Clean up any references to source/generated bitmaps
112 if (sourceImages != null) {
113 if (cancelled) {
114 for (Bitmap b : sourceImages) {
115 b.recycle();
116 }
117 }
118 sourceImages.clear();
119 }
120 if (generatedImages != null) {
121 if (cancelled) {
122 for (Bitmap b : generatedImages) {
123 b.recycle();
124 }
125 }
126 generatedImages.clear();
127 }
128 }
Winson Chungb44b5242011-06-13 11:32:14 -0700129 int page;
130 ArrayList<Object> items;
Winson Chung4e076542011-06-23 13:04:10 -0700131 ArrayList<Bitmap> sourceImages;
132 ArrayList<Bitmap> generatedImages;
Michael Jurka038f9d82011-11-03 13:50:45 -0700133 int maxImageWidth;
134 int maxImageHeight;
Winson Chungb44b5242011-06-13 11:32:14 -0700135 AsyncTaskCallback doInBackgroundCallback;
136 AsyncTaskCallback postExecuteCallback;
137}
Winson Chung4e076542011-06-23 13:04:10 -0700138
Winson Chungb44b5242011-06-13 11:32:14 -0700139/**
140 * A generic template for an async task used in AppsCustomize.
141 */
142class AppsCustomizeAsyncTask extends AsyncTask<AsyncTaskPageData, Void, AsyncTaskPageData> {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700143 AppsCustomizeAsyncTask(int p, AsyncTaskPageData.Type ty) {
Winson Chungb44b5242011-06-13 11:32:14 -0700144 page = p;
Winson Chungb44b5242011-06-13 11:32:14 -0700145 threadPriority = Process.THREAD_PRIORITY_DEFAULT;
Winson Chung875de7e2011-06-28 14:25:17 -0700146 dataType = ty;
Winson Chungb44b5242011-06-13 11:32:14 -0700147 }
148 @Override
149 protected AsyncTaskPageData doInBackground(AsyncTaskPageData... params) {
150 if (params.length != 1) return null;
151 // Load each of the widget previews in the background
152 params[0].doInBackgroundCallback.run(this, params[0]);
153 return params[0];
154 }
155 @Override
156 protected void onPostExecute(AsyncTaskPageData result) {
157 // All the widget previews are loaded, so we can just callback to inflate the page
158 result.postExecuteCallback.run(this, result);
159 }
160
161 void setThreadPriority(int p) {
162 threadPriority = p;
163 }
164 void syncThreadPriority() {
165 Process.setThreadPriority(threadPriority);
166 }
167
168 // The page that this async task is associated with
Winson Chung875de7e2011-06-28 14:25:17 -0700169 AsyncTaskPageData.Type dataType;
Winson Chungb44b5242011-06-13 11:32:14 -0700170 int page;
Winson Chungb44b5242011-06-13 11:32:14 -0700171 int threadPriority;
172}
Winson Chungb44b5242011-06-13 11:32:14 -0700173
Michael Jurkadac85912012-05-18 15:04:49 -0700174abstract class WeakReferenceThreadLocal<T> {
175 private ThreadLocal<WeakReference<T>> mThreadLocal;
176 public WeakReferenceThreadLocal() {
177 mThreadLocal = new ThreadLocal<WeakReference<T>>();
178 }
179
180 abstract T initialValue();
181
182 public void set(T t) {
183 mThreadLocal.set(new WeakReference<T>(t));
184 }
185
186 public T get() {
187 WeakReference<T> reference = mThreadLocal.get();
188 T obj;
189 if (reference == null) {
190 obj = initialValue();
191 mThreadLocal.set(new WeakReference<T>(obj));
192 return obj;
193 } else {
194 obj = reference.get();
195 if (obj == null) {
196 obj = initialValue();
197 mThreadLocal.set(new WeakReference<T>(obj));
198 }
199 return obj;
200 }
201 }
202}
203
204class CanvasCache extends WeakReferenceThreadLocal<Canvas> {
205 @Override
206 protected Canvas initialValue() {
207 return new Canvas();
208 }
209}
210
211class PaintCache extends WeakReferenceThreadLocal<Paint> {
212 @Override
213 protected Paint initialValue() {
214 return null;
215 }
216}
217
218class BitmapCache extends WeakReferenceThreadLocal<Bitmap> {
219 @Override
220 protected Bitmap initialValue() {
221 return null;
222 }
223}
224
225class RectCache extends WeakReferenceThreadLocal<Rect> {
226 @Override
227 protected Rect initialValue() {
228 return new Rect();
229 }
230}
231
Winson Chungb44b5242011-06-13 11:32:14 -0700232/**
233 * The Apps/Customize page that displays all the applications, widgets, and shortcuts.
234 */
Winson Chung785d2eb2011-04-14 16:08:02 -0700235public class AppsCustomizePagedView extends PagedViewWithDraggableItems implements
Winson Chunge4e50662012-01-23 14:45:13 -0800236 AllAppsView, View.OnClickListener, View.OnKeyListener, DragSource,
Michael Jurka39e5d172012-03-12 18:36:12 -0700237 PagedViewIcon.PressedCallback, PagedViewWidget.ShortPressListener,
238 LauncherTransitionable {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700239 static final String TAG = "AppsCustomizePagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -0700240
241 /**
242 * The different content types that this paged view can show.
243 */
244 public enum ContentType {
245 Applications,
Winson Chung6a26e5b2011-05-26 14:36:06 -0700246 Widgets
Winson Chung785d2eb2011-04-14 16:08:02 -0700247 }
248
249 // Refs
250 private Launcher mLauncher;
251 private DragController mDragController;
252 private final LayoutInflater mLayoutInflater;
253 private final PackageManager mPackageManager;
254
Winson Chung5afbf7b2011-07-25 11:53:08 -0700255 // Save and Restore
256 private int mSaveInstanceStateItemIndex = -1;
Winson Chunge4e50662012-01-23 14:45:13 -0800257 private PagedViewIcon mPressedIcon;
Winson Chung5afbf7b2011-07-25 11:53:08 -0700258
Winson Chung785d2eb2011-04-14 16:08:02 -0700259 // Content
Winson Chung785d2eb2011-04-14 16:08:02 -0700260 private ArrayList<ApplicationInfo> mApps;
Winson Chungd2945262011-06-24 15:22:14 -0700261 private ArrayList<Object> mWidgets;
Winson Chung1ed747a2011-05-03 16:18:34 -0700262
Winson Chung7d7541e2011-09-16 20:14:36 -0700263 // Cling
Winson Chung3f4e1422011-11-17 14:58:51 -0800264 private boolean mHasShownAllAppsCling;
Winson Chung7d7541e2011-09-16 20:14:36 -0700265 private int mClingFocusedX;
266 private int mClingFocusedY;
267
Winson Chung1ed747a2011-05-03 16:18:34 -0700268 // Caching
Winson Chungb44b5242011-06-13 11:32:14 -0700269 private Canvas mCanvas;
Winson Chung1ed747a2011-05-03 16:18:34 -0700270 private Drawable mDefaultWidgetBackground;
Winson Chung4dbea792011-05-05 14:21:32 -0700271 private IconCache mIconCache;
Winson Chung785d2eb2011-04-14 16:08:02 -0700272
273 // Dimens
274 private int mContentWidth;
Winson Chungd2945262011-06-24 15:22:14 -0700275 private int mAppIconSize;
Winson Chung6032e7e2011-11-08 15:47:17 -0800276 private int mMaxAppCellCountX, mMaxAppCellCountY;
Winson Chung4b576be2011-04-27 17:40:20 -0700277 private int mWidgetCountX, mWidgetCountY;
Winson Chungd2945262011-06-24 15:22:14 -0700278 private int mWidgetWidthGap, mWidgetHeightGap;
Winson Chung1ed747a2011-05-03 16:18:34 -0700279 private final float sWidgetPreviewIconPaddingPercentage = 0.25f;
Winson Chung785d2eb2011-04-14 16:08:02 -0700280 private PagedViewCellLayout mWidgetSpacingLayout;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700281 private int mNumAppsPages;
282 private int mNumWidgetPages;
Winson Chung785d2eb2011-04-14 16:08:02 -0700283
Adam Cohen22f823d2011-09-01 17:22:18 -0700284 // Relating to the scroll and overscroll effects
285 Workspace.ZInterpolator mZInterpolator = new Workspace.ZInterpolator(0.5f);
Adam Cohencff6af82011-09-13 14:51:53 -0700286 private static float CAMERA_DISTANCE = 6500;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700287 private static float TRANSITION_SCALE_FACTOR = 0.74f;
Adam Cohencff6af82011-09-13 14:51:53 -0700288 private static float TRANSITION_PIVOT = 0.65f;
289 private static float TRANSITION_MAX_ROTATION = 22;
290 private static final boolean PERFORM_OVERSCROLL_ROTATION = true;
Adam Cohenb5ba0972011-09-07 18:02:31 -0700291 private AccelerateInterpolator mAlphaInterpolator = new AccelerateInterpolator(0.9f);
Adam Cohen2591f6a2011-10-25 14:36:40 -0700292 private DecelerateInterpolator mLeftScreenAlphaInterpolator = new DecelerateInterpolator(4);
Adam Cohen22f823d2011-09-01 17:22:18 -0700293
Winson Chungb44b5242011-06-13 11:32:14 -0700294 // Previews & outlines
295 ArrayList<AppsCustomizeAsyncTask> mRunningTasks;
Winson Chung68e4c642011-11-10 15:48:25 -0800296 private static final int sPageSleepDelay = 200;
Winson Chung4b576be2011-04-27 17:40:20 -0700297
Adam Cohened66b2b2012-01-23 17:28:51 -0800298 private Runnable mInflateWidgetRunnable = null;
299 private Runnable mBindWidgetRunnable = null;
300 static final int WIDGET_NO_CLEANUP_REQUIRED = -1;
Adam Cohen21a170b2012-05-30 15:17:06 -0700301 static final int WIDGET_PRELOAD_PENDING = 0;
302 static final int WIDGET_BOUND = 1;
303 static final int WIDGET_INFLATED = 2;
Adam Cohened66b2b2012-01-23 17:28:51 -0800304 int mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
305 int mWidgetLoadingId = -1;
Adam Cohen1b36dc32012-02-13 19:27:37 -0800306 PendingAddWidgetInfo mCreateWidgetInfo = null;
Adam Cohen7a326642012-02-22 12:03:22 -0800307 private boolean mDraggingWidget = false;
Adam Cohened66b2b2012-01-23 17:28:51 -0800308
Michael Jurka39e5d172012-03-12 18:36:12 -0700309 // Deferral of loading widget previews during launcher transitions
310 private boolean mInTransition;
311 private ArrayList<AsyncTaskPageData> mDeferredSyncWidgetPageItems =
312 new ArrayList<AsyncTaskPageData>();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700313 private ArrayList<Runnable> mDeferredPrepareLoadWidgetPreviewsTasks =
314 new ArrayList<Runnable>();
Michael Jurka39e5d172012-03-12 18:36:12 -0700315
Michael Jurkadac85912012-05-18 15:04:49 -0700316 // Used for drawing shortcut previews
317 BitmapCache mCachedShortcutPreviewBitmap = new BitmapCache();
318 PaintCache mCachedShortcutPreviewPaint = new PaintCache();
319 CanvasCache mCachedShortcutPreviewCanvas = new CanvasCache();
320
321 // Used for drawing widget previews
322 CanvasCache mCachedAppWidgetPreviewCanvas = new CanvasCache();
323 RectCache mCachedAppWidgetPreviewSrcRect = new RectCache();
324 RectCache mCachedAppWidgetPreviewDestRect = new RectCache();
325 PaintCache mCachedAppWidgetPreviewPaint = new PaintCache();
326
Winson Chung785d2eb2011-04-14 16:08:02 -0700327 public AppsCustomizePagedView(Context context, AttributeSet attrs) {
328 super(context, attrs);
329 mLayoutInflater = LayoutInflater.from(context);
330 mPackageManager = context.getPackageManager();
Winson Chung785d2eb2011-04-14 16:08:02 -0700331 mApps = new ArrayList<ApplicationInfo>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700332 mWidgets = new ArrayList<Object>();
Winson Chung4dbea792011-05-05 14:21:32 -0700333 mIconCache = ((LauncherApplication) context.getApplicationContext()).getIconCache();
Winson Chungb44b5242011-06-13 11:32:14 -0700334 mCanvas = new Canvas();
335 mRunningTasks = new ArrayList<AppsCustomizeAsyncTask>();
Winson Chung1ed747a2011-05-03 16:18:34 -0700336
337 // Save the default widget preview background
338 Resources resources = context.getResources();
Winson Chung967289b2011-06-30 18:09:30 -0700339 mDefaultWidgetBackground = resources.getDrawable(R.drawable.default_widget_preview_holo);
Winson Chung70fc4382011-08-08 15:31:33 -0700340 mAppIconSize = resources.getDimensionPixelSize(R.dimen.app_icon_size);
Winson Chung785d2eb2011-04-14 16:08:02 -0700341
Winson Chung6032e7e2011-11-08 15:47:17 -0800342 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AppsCustomizePagedView, 0, 0);
343 mMaxAppCellCountX = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountX, -1);
344 mMaxAppCellCountY = a.getInt(R.styleable.AppsCustomizePagedView_maxAppCellCountY, -1);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700345 mWidgetWidthGap =
346 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellWidthGap, 0);
347 mWidgetHeightGap =
348 a.getDimensionPixelSize(R.styleable.AppsCustomizePagedView_widgetCellHeightGap, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700349 mWidgetCountX = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountX, 2);
350 mWidgetCountY = a.getInt(R.styleable.AppsCustomizePagedView_widgetCountY, 2);
Winson Chung7d7541e2011-09-16 20:14:36 -0700351 mClingFocusedX = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedX, 0);
352 mClingFocusedY = a.getInt(R.styleable.AppsCustomizePagedView_clingFocusedY, 0);
Winson Chung4b576be2011-04-27 17:40:20 -0700353 a.recycle();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700354 mWidgetSpacingLayout = new PagedViewCellLayout(getContext());
Winson Chung4b576be2011-04-27 17:40:20 -0700355
Winson Chung1ed747a2011-05-03 16:18:34 -0700356 // The padding on the non-matched dimension for the default widget preview icons
357 // (top + bottom)
Adam Cohen2591f6a2011-10-25 14:36:40 -0700358 mFadeInAdjacentScreens = false;
Svetoslav Ganov08055f62012-05-15 11:06:36 -0700359
360 // Unless otherwise specified this view is important for accessibility.
361 if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
362 setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
363 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700364 }
365
366 @Override
367 protected void init() {
368 super.init();
Winson Chung6a877402011-10-26 14:51:44 -0700369 mCenterPagesVertically = false;
Winson Chung785d2eb2011-04-14 16:08:02 -0700370
371 Context context = getContext();
372 Resources r = context.getResources();
373 setDragSlopeThreshold(r.getInteger(R.integer.config_appsCustomizeDragSlopeThreshold)/100f);
374 }
375
Winson Chungf0ea4d32011-06-06 14:27:16 -0700376 @Override
Michael Jurkad771c962011-08-09 15:00:48 -0700377 protected void onUnhandledTap(MotionEvent ev) {
378 if (LauncherApplication.isScreenLarge()) {
Winson Chungde1af762011-07-21 16:44:07 -0700379 // Dismiss AppsCustomize if we tap
380 mLauncher.showWorkspace(true);
381 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700382 }
383
Winson Chung5afbf7b2011-07-25 11:53:08 -0700384 /** Returns the item index of the center item on this page so that we can restore to this
385 * item index when we rotate. */
386 private int getMiddleComponentIndexOnCurrentPage() {
387 int i = -1;
388 if (getPageCount() > 0) {
389 int currentPage = getCurrentPage();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700390 if (currentPage < mNumAppsPages) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700391 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(currentPage);
Winson Chung5afbf7b2011-07-25 11:53:08 -0700392 PagedViewCellLayoutChildren childrenLayout = layout.getChildrenLayout();
393 int numItemsPerPage = mCellCountX * mCellCountY;
394 int childCount = childrenLayout.getChildCount();
395 if (childCount > 0) {
396 i = (currentPage * numItemsPerPage) + (childCount / 2);
Adam Cohen0cd3b642011-10-14 14:58:00 -0700397 }
398 } else {
399 int numApps = mApps.size();
Adam Cohen22f823d2011-09-01 17:22:18 -0700400 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(currentPage);
Winson Chung5afbf7b2011-07-25 11:53:08 -0700401 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
402 int childCount = layout.getChildCount();
403 if (childCount > 0) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700404 i = numApps +
405 ((currentPage - mNumAppsPages) * numItemsPerPage) + (childCount / 2);
406 }
Winson Chung5afbf7b2011-07-25 11:53:08 -0700407 }
408 }
409 return i;
410 }
411
412 /** Get the index of the item to restore to if we need to restore the current page. */
413 int getSaveInstanceStateIndex() {
414 if (mSaveInstanceStateItemIndex == -1) {
415 mSaveInstanceStateItemIndex = getMiddleComponentIndexOnCurrentPage();
416 }
417 return mSaveInstanceStateItemIndex;
418 }
419
420 /** Returns the page in the current orientation which is expected to contain the specified
421 * item index. */
422 int getPageForComponent(int index) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700423 if (index < 0) return 0;
424
425 if (index < mApps.size()) {
Winson Chung5afbf7b2011-07-25 11:53:08 -0700426 int numItemsPerPage = mCellCountX * mCellCountY;
427 return (index / numItemsPerPage);
Adam Cohen0cd3b642011-10-14 14:58:00 -0700428 } else {
Winson Chung5afbf7b2011-07-25 11:53:08 -0700429 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700430 return mNumAppsPages + ((index - mApps.size()) / numItemsPerPage);
431 }
Winson Chung5afbf7b2011-07-25 11:53:08 -0700432 }
433
Winson Chung5afbf7b2011-07-25 11:53:08 -0700434 /** Restores the page for an item at the specified index */
435 void restorePageForIndex(int index) {
436 if (index < 0) return;
Adam Cohen0cd3b642011-10-14 14:58:00 -0700437 mSaveInstanceStateItemIndex = index;
Winson Chung5afbf7b2011-07-25 11:53:08 -0700438 }
439
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700440 private void updatePageCounts() {
441 mNumWidgetPages = (int) Math.ceil(mWidgets.size() /
442 (float) (mWidgetCountX * mWidgetCountY));
443 mNumAppsPages = (int) Math.ceil((float) mApps.size() / (mCellCountX * mCellCountY));
444 }
445
Winson Chungf0ea4d32011-06-06 14:27:16 -0700446 protected void onDataReady(int width, int height) {
447 // Note that we transpose the counts in portrait so that we get a similar layout
448 boolean isLandscape = getResources().getConfiguration().orientation ==
449 Configuration.ORIENTATION_LANDSCAPE;
450 int maxCellCountX = Integer.MAX_VALUE;
451 int maxCellCountY = Integer.MAX_VALUE;
452 if (LauncherApplication.isScreenLarge()) {
453 maxCellCountX = (isLandscape ? LauncherModel.getCellCountX() :
454 LauncherModel.getCellCountY());
455 maxCellCountY = (isLandscape ? LauncherModel.getCellCountY() :
456 LauncherModel.getCellCountX());
457 }
Winson Chung6032e7e2011-11-08 15:47:17 -0800458 if (mMaxAppCellCountX > -1) {
459 maxCellCountX = Math.min(maxCellCountX, mMaxAppCellCountX);
460 }
461 if (mMaxAppCellCountY > -1) {
462 maxCellCountY = Math.min(maxCellCountY, mMaxAppCellCountY);
463 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700464
465 // Now that the data is ready, we can calculate the content width, the number of cells to
466 // use for each page
467 mWidgetSpacingLayout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
468 mWidgetSpacingLayout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
469 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
470 mWidgetSpacingLayout.calculateCellCount(width, height, maxCellCountX, maxCellCountY);
471 mCellCountX = mWidgetSpacingLayout.getCellCountX();
472 mCellCountY = mWidgetSpacingLayout.getCellCountY();
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700473 updatePageCounts();
Winson Chung5a808352011-06-27 19:08:49 -0700474
Winson Chungdb1138b2011-06-30 14:39:35 -0700475 // Force a measure to update recalculate the gaps
476 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
477 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
478 mWidgetSpacingLayout.measure(widthSpec, heightSpec);
Winson Chungf0ea4d32011-06-06 14:27:16 -0700479 mContentWidth = mWidgetSpacingLayout.getContentWidth();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700480
Michael Jurkae326f182011-11-21 14:05:46 -0800481 AppsCustomizeTabHost host = (AppsCustomizeTabHost) getTabHost();
482 final boolean hostIsTransitioning = host.isTransitioning();
483
Adam Cohen0cd3b642011-10-14 14:58:00 -0700484 // Restore the page
485 int page = getPageForComponent(mSaveInstanceStateItemIndex);
Michael Jurkae326f182011-11-21 14:05:46 -0800486 invalidatePageData(Math.max(0, page), hostIsTransitioning);
Winson Chung7d7541e2011-09-16 20:14:36 -0700487
Winson Chung3f4e1422011-11-17 14:58:51 -0800488 // Show All Apps cling if we are finished transitioning, otherwise, we will try again when
489 // the transition completes in AppsCustomizeTabHost (otherwise the wrong offsets will be
490 // returned while animating)
Michael Jurkae326f182011-11-21 14:05:46 -0800491 if (!hostIsTransitioning) {
Winson Chung3f4e1422011-11-17 14:58:51 -0800492 post(new Runnable() {
493 @Override
494 public void run() {
495 showAllAppsCling();
496 }
497 });
498 }
499 }
Winson Chung7d7541e2011-09-16 20:14:36 -0700500
Winson Chung3f4e1422011-11-17 14:58:51 -0800501 void showAllAppsCling() {
Winson Chung9802ac92012-06-08 16:01:58 -0700502 if (!mHasShownAllAppsCling && isDataReady()) {
Winson Chung3f4e1422011-11-17 14:58:51 -0800503 mHasShownAllAppsCling = true;
504 // Calculate the position for the cling punch through
505 int[] offset = new int[2];
506 int[] pos = mWidgetSpacingLayout.estimateCellPosition(mClingFocusedX, mClingFocusedY);
507 mLauncher.getDragLayer().getLocationInDragLayer(this, offset);
508 // PagedViews are centered horizontally but top aligned
509 pos[0] += (getMeasuredWidth() - mWidgetSpacingLayout.getMeasuredWidth()) / 2 +
510 offset[0];
511 pos[1] += offset[1];
512 mLauncher.showFirstRunAllAppsCling(pos);
513 }
Winson Chungf0ea4d32011-06-06 14:27:16 -0700514 }
515
516 @Override
517 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
518 int width = MeasureSpec.getSize(widthMeasureSpec);
519 int height = MeasureSpec.getSize(heightMeasureSpec);
520 if (!isDataReady()) {
Winson Chung9802ac92012-06-08 16:01:58 -0700521 if (!mApps.isEmpty() && !mWidgets.isEmpty()) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700522 setDataIsReady();
523 setMeasuredDimension(width, height);
524 onDataReady(width, height);
525 }
526 }
527
528 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
529 }
530
Winson Chungc93e5ae2012-07-23 20:48:26 -0700531 public void onPackagesUpdated(boolean immediate) {
532 if (immediate) {
533 updatePackages();
534 } else {
535 // TODO: this isn't ideal, but we actually need to delay here. This call is triggered
536 // by a broadcast receiver, and in order for it to work correctly, we need to know that
537 // the AppWidgetService has already received and processed the same broadcast. Since there
538 // is no guarantee about ordering of broadcast receipt, we just delay here. This is a
539 // workaround until we add a callback from AppWidgetService to AppWidgetHost when widget
540 // packages are added, updated or removed.
541 postDelayed(new Runnable() {
542 public void run() {
543 updatePackages();
544 }
545 }, 1500);
546 }
Adam Cohenb0fa3522011-08-17 16:10:46 -0700547 }
548
549 public void updatePackages() {
Winson Chung1ed747a2011-05-03 16:18:34 -0700550 // Get the list of widgets and shortcuts
551 mWidgets.clear();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700552 List<AppWidgetProviderInfo> widgets =
553 AppWidgetManager.getInstance(mLauncher).getInstalledProviders();
Winson Chungf0ea4d32011-06-06 14:27:16 -0700554 Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
555 List<ResolveInfo> shortcuts = mPackageManager.queryIntentActivities(shortcutsIntent, 0);
Michael Jurkadbc1f652011-11-10 17:02:56 -0800556 for (AppWidgetProviderInfo widget : widgets) {
557 if (widget.minWidth > 0 && widget.minHeight > 0) {
Winson Chunga5c96362012-04-12 14:04:41 -0700558 // Ensure that all widgets we show can be added on a workspace of this size
Adam Cohen2f093b62012-04-30 18:59:53 -0700559 int[] spanXY = Launcher.getSpanForWidget(mLauncher, widget);
560 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, widget);
Winson Chunga5c96362012-04-12 14:04:41 -0700561 int minSpanX = Math.min(spanXY[0], minSpanXY[0]);
562 int minSpanY = Math.min(spanXY[1], minSpanXY[1]);
Adam Cohen336d4912012-04-13 17:57:11 -0700563 if (minSpanX <= LauncherModel.getCellCountX() &&
564 minSpanY <= LauncherModel.getCellCountY()) {
Winson Chunga5c96362012-04-12 14:04:41 -0700565 mWidgets.add(widget);
Winson Chungfd39d8e2012-06-05 10:12:48 -0700566 } else {
567 Log.e(TAG, "Widget " + widget.provider + " can not fit on this device (" +
568 widget.minWidth + ", " + widget.minHeight + ")");
Winson Chunga5c96362012-04-12 14:04:41 -0700569 }
Michael Jurkadbc1f652011-11-10 17:02:56 -0800570 } else {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700571 Log.e(TAG, "Widget " + widget.provider + " has invalid dimensions (" +
Michael Jurkadbc1f652011-11-10 17:02:56 -0800572 widget.minWidth + ", " + widget.minHeight + ")");
573 }
574 }
Winson Chung6a3fd3f2011-08-02 14:03:26 -0700575 mWidgets.addAll(shortcuts);
576 Collections.sort(mWidgets,
577 new LauncherModel.WidgetAndShortcutNameComparator(mPackageManager));
Winson Chung4b0ed8c2011-10-19 15:24:49 -0700578 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -0700579 invalidateOnDataChange();
Winson Chung4b576be2011-04-27 17:40:20 -0700580 }
581
582 @Override
583 public void onClick(View v) {
Adam Cohenfc53cd22011-07-20 15:45:11 -0700584 // When we have exited all apps or are in transition, disregard clicks
Winson Chungc93e5ae2012-07-23 20:48:26 -0700585 if (!mLauncher.isAllAppsVisible() ||
Adam Cohenfc53cd22011-07-20 15:45:11 -0700586 mLauncher.getWorkspace().isSwitchingState()) return;
587
Winson Chung4b576be2011-04-27 17:40:20 -0700588 if (v instanceof PagedViewIcon) {
589 // Animate some feedback to the click
590 final ApplicationInfo appInfo = (ApplicationInfo) v.getTag();
Winson Chung3b187b82012-01-30 15:11:08 -0800591
592 // Lock the drawable state to pressed until we return to Launcher
593 if (mPressedIcon != null) {
594 mPressedIcon.lockDrawableState();
595 }
Winson Chungc7450e32012-04-17 17:34:08 -0700596
Winson Chung18f41f82012-05-09 13:28:10 -0700597 // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
598 // to be consistent. So re-enable the flag here, and we will re-disable it as necessary
599 // when Launcher resumes and we are still in AllApps.
600 mLauncher.updateWallpaperVisibility(true);
Winson Chungc7450e32012-04-17 17:34:08 -0700601 mLauncher.startActivitySafely(v, appInfo.intent, appInfo);
602
Winson Chung4b576be2011-04-27 17:40:20 -0700603 } else if (v instanceof PagedViewWidget) {
Winson Chungd2e87b32011-06-02 10:53:07 -0700604 // Let the user know that they have to long press to add a widget
605 Toast.makeText(getContext(), R.string.long_press_widget_to_add,
606 Toast.LENGTH_SHORT).show();
Winson Chung46af2e82011-05-09 16:00:53 -0700607
Winson Chungd2e87b32011-06-02 10:53:07 -0700608 // Create a little animation to show that the widget can move
609 float offsetY = getResources().getDimensionPixelSize(R.dimen.dragViewOffsetY);
610 final ImageView p = (ImageView) v.findViewById(R.id.widget_preview);
611 AnimatorSet bounce = new AnimatorSet();
612 ValueAnimator tyuAnim = ObjectAnimator.ofFloat(p, "translationY", offsetY);
613 tyuAnim.setDuration(125);
614 ValueAnimator tydAnim = ObjectAnimator.ofFloat(p, "translationY", 0f);
615 tydAnim.setDuration(100);
616 bounce.play(tyuAnim).before(tydAnim);
617 bounce.setInterpolator(new AccelerateInterpolator());
618 bounce.start();
Winson Chung4b576be2011-04-27 17:40:20 -0700619 }
Winson Chung785d2eb2011-04-14 16:08:02 -0700620 }
621
Winson Chungc6f10b92011-11-14 11:39:07 -0800622 public boolean onKey(View v, int keyCode, KeyEvent event) {
623 return FocusHelper.handleAppsCustomizeKeyEvent(v, keyCode, event);
624 }
625
Winson Chung785d2eb2011-04-14 16:08:02 -0700626 /*
627 * PagedViewWithDraggableItems implementation
628 */
629 @Override
630 protected void determineDraggingStart(android.view.MotionEvent ev) {
631 // Disable dragging by pulling an app down for now.
632 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700633
Winson Chung4b576be2011-04-27 17:40:20 -0700634 private void beginDraggingApplication(View v) {
Adam Cohenac8c8762011-07-13 11:15:27 -0700635 mLauncher.getWorkspace().onDragStartedWithItem(v);
636 mLauncher.getWorkspace().beginDragShared(v, this);
Winson Chung4b576be2011-04-27 17:40:20 -0700637 }
Adam Cohenac8c8762011-07-13 11:15:27 -0700638
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700639 private void preloadWidget(final PendingAddWidgetInfo info) {
Adam Cohened66b2b2012-01-23 17:28:51 -0800640 final AppWidgetProviderInfo pInfo = info.info;
641 if (pInfo.configure != null) {
642 return;
643 }
644
Adam Cohen21a170b2012-05-30 15:17:06 -0700645 mWidgetCleanupState = WIDGET_PRELOAD_PENDING;
Adam Cohened66b2b2012-01-23 17:28:51 -0800646 mBindWidgetRunnable = new Runnable() {
647 @Override
648 public void run() {
649 mWidgetLoadingId = mLauncher.getAppWidgetHost().allocateAppWidgetId();
Michael Jurka8b805b12012-04-18 14:23:14 -0700650 if (AppWidgetManager.getInstance(mLauncher)
651 .bindAppWidgetIdIfAllowed(mWidgetLoadingId, info.componentName)) {
652 mWidgetCleanupState = WIDGET_BOUND;
653 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800654 }
655 };
656 post(mBindWidgetRunnable);
657
658 mInflateWidgetRunnable = new Runnable() {
659 @Override
660 public void run() {
Michael Jurka8b805b12012-04-18 14:23:14 -0700661 AppWidgetHostView hostView = mLauncher.
662 getAppWidgetHost().createView(getContext(), mWidgetLoadingId, pInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800663 info.boundWidget = hostView;
664 mWidgetCleanupState = WIDGET_INFLATED;
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800665 hostView.setVisibility(INVISIBLE);
Adam Cohen1f362702012-04-04 14:58:12 -0700666 int[] unScaledSize = mLauncher.getWorkspace().estimateItemSize(info.spanX,
667 info.spanY, info, false);
668
669 // We want the first widget layout to be the correct size. This will be important
670 // for width size reporting to the AppWidgetManager.
671 DragLayer.LayoutParams lp = new DragLayer.LayoutParams(unScaledSize[0],
672 unScaledSize[1]);
673 lp.x = lp.y = 0;
674 lp.customPosition = true;
675 hostView.setLayoutParams(lp);
Adam Cohenef3dd6e2012-02-14 20:54:05 -0800676 mLauncher.getDragLayer().addView(hostView);
Adam Cohened66b2b2012-01-23 17:28:51 -0800677 }
678 };
679 post(mInflateWidgetRunnable);
680 }
681
682 @Override
683 public void onShortPress(View v) {
684 // We are anticipating a long press, and we use this time to load bind and instantiate
685 // the widget. This will need to be cleaned up if it turns out no long press occurs.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700686 if (mCreateWidgetInfo != null) {
687 // Just in case the cleanup process wasn't properly executed. This shouldn't happen.
688 cleanupWidgetPreloading(false);
689 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800690 mCreateWidgetInfo = new PendingAddWidgetInfo((PendingAddWidgetInfo) v.getTag());
Adam Cohenf1dcdf62012-05-10 16:51:52 -0700691 preloadWidget(mCreateWidgetInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -0800692 }
693
Adam Cohen0e56cc92012-05-11 15:57:05 -0700694 private void cleanupWidgetPreloading(boolean widgetWasAdded) {
695 if (!widgetWasAdded) {
696 // If the widget was not added, we may need to do further cleanup.
697 PendingAddWidgetInfo info = mCreateWidgetInfo;
698 mCreateWidgetInfo = null;
Adam Cohen21a170b2012-05-30 15:17:06 -0700699
700 if (mWidgetCleanupState == WIDGET_PRELOAD_PENDING) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700701 // We never did any preloading, so just remove pending callbacks to do so
702 removeCallbacks(mBindWidgetRunnable);
703 removeCallbacks(mInflateWidgetRunnable);
704 } else if (mWidgetCleanupState == WIDGET_BOUND) {
705 // Delete the widget id which was allocated
706 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700707 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
708 }
709
710 // We never got around to inflating the widget, so remove the callback to do so.
Adam Cohen0e56cc92012-05-11 15:57:05 -0700711 removeCallbacks(mInflateWidgetRunnable);
712 } else if (mWidgetCleanupState == WIDGET_INFLATED) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700713 // Delete the widget id which was allocated
714 if (mWidgetLoadingId != -1) {
Adam Cohen21a170b2012-05-30 15:17:06 -0700715 mLauncher.getAppWidgetHost().deleteAppWidgetId(mWidgetLoadingId);
716 }
717
Adam Cohen0e56cc92012-05-11 15:57:05 -0700718 // The widget was inflated and added to the DragLayer -- remove it.
719 AppWidgetHostView widget = info.boundWidget;
720 mLauncher.getDragLayer().removeView(widget);
721 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800722 }
723 mWidgetCleanupState = WIDGET_NO_CLEANUP_REQUIRED;
724 mWidgetLoadingId = -1;
Adam Cohen0e56cc92012-05-11 15:57:05 -0700725 mCreateWidgetInfo = null;
726 PagedViewWidget.resetShortPressTarget();
Adam Cohened66b2b2012-01-23 17:28:51 -0800727 }
728
Adam Cohen7a326642012-02-22 12:03:22 -0800729 @Override
730 public void cleanUpShortPress(View v) {
731 if (!mDraggingWidget) {
Adam Cohen0e56cc92012-05-11 15:57:05 -0700732 cleanupWidgetPreloading(false);
Adam Cohen7a326642012-02-22 12:03:22 -0800733 }
734 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800735
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700736 private boolean beginDraggingWidget(View v) {
Adam Cohen7a326642012-02-22 12:03:22 -0800737 mDraggingWidget = true;
Winson Chung4b576be2011-04-27 17:40:20 -0700738 // Get the widget preview as the drag representation
739 ImageView image = (ImageView) v.findViewById(R.id.widget_preview);
Winson Chung1ed747a2011-05-03 16:18:34 -0700740 PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag();
Winson Chung4b576be2011-04-27 17:40:20 -0700741
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700742 // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
743 // we abort the drag.
744 if (image.getDrawable() == null) {
745 mDraggingWidget = false;
746 return false;
747 }
748
Winson Chung4b576be2011-04-27 17:40:20 -0700749 // Compose the drag image
Winson Chung1120e032011-11-22 16:11:31 -0800750 Bitmap preview;
751 Bitmap outline;
Winson Chung72d59842012-02-22 13:51:36 -0800752 float scale = 1f;
Winson Chung1ed747a2011-05-03 16:18:34 -0700753 if (createItemInfo instanceof PendingAddWidgetInfo) {
Adam Cohen92478922012-05-17 13:43:29 -0700754 // This can happen in some weird cases involving multi-touch. We can't start dragging
755 // the widget if this is null, so we break out.
756 if (mCreateWidgetInfo == null) {
757 return false;
758 }
759
Adam Cohen1b36dc32012-02-13 19:27:37 -0800760 PendingAddWidgetInfo createWidgetInfo = mCreateWidgetInfo;
761 createItemInfo = createWidgetInfo;
Adam Cohen1f362702012-04-04 14:58:12 -0700762 int spanX = createItemInfo.spanX;
763 int spanY = createItemInfo.spanY;
764 int[] size = mLauncher.getWorkspace().estimateItemSize(spanX, spanY,
765 createWidgetInfo, true);
Winson Chung1ed747a2011-05-03 16:18:34 -0700766
Winson Chung72d59842012-02-22 13:51:36 -0800767 FastBitmapDrawable previewDrawable = (FastBitmapDrawable) image.getDrawable();
768 float minScale = 1.25f;
Michael Jurkadac85912012-05-18 15:04:49 -0700769 int maxWidth, maxHeight;
770 maxWidth = Math.min((int) (previewDrawable.getIntrinsicWidth() * minScale), size[0]);
771 maxHeight = Math.min((int) (previewDrawable.getIntrinsicHeight() * minScale), size[1]);
Winson Chung1120e032011-11-22 16:11:31 -0800772 preview = getWidgetPreview(createWidgetInfo.componentName, createWidgetInfo.previewImage,
Michael Jurkadac85912012-05-18 15:04:49 -0700773 createWidgetInfo.icon, spanX, spanY, maxWidth, maxHeight);
Winson Chung72d59842012-02-22 13:51:36 -0800774
775 // Determine the image view drawable scale relative to the preview
776 float[] mv = new float[9];
777 Matrix m = new Matrix();
778 m.setRectToRect(
779 new RectF(0f, 0f, (float) preview.getWidth(), (float) preview.getHeight()),
780 new RectF(0f, 0f, (float) previewDrawable.getIntrinsicWidth(),
781 (float) previewDrawable.getIntrinsicHeight()),
782 Matrix.ScaleToFit.START);
783 m.getValues(mv);
784 scale = (float) mv[0];
Winson Chung1ed747a2011-05-03 16:18:34 -0700785 } else {
Michael Jurkadac85912012-05-18 15:04:49 -0700786 PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag();
787 Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.shortcutActivityInfo);
788 preview = Bitmap.createBitmap(icon.getIntrinsicWidth(),
789 icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
790
Winson Chung1120e032011-11-22 16:11:31 -0800791 mCanvas.setBitmap(preview);
Michael Jurka4ca39222012-05-15 17:18:34 -0700792 mCanvas.save();
Michael Jurkadac85912012-05-18 15:04:49 -0700793 renderDrawableToBitmap(icon, preview, 0, 0,
794 icon.getIntrinsicWidth(), icon.getIntrinsicHeight());
Michael Jurka4ca39222012-05-15 17:18:34 -0700795 mCanvas.restore();
Adam Cohenaaf473c2011-08-03 12:02:47 -0700796 mCanvas.setBitmap(null);
Winson Chung1ed747a2011-05-03 16:18:34 -0700797 createItemInfo.spanX = createItemInfo.spanY = 1;
798 }
Winson Chung4b576be2011-04-27 17:40:20 -0700799
Peter Ng8db70002011-10-25 15:40:08 -0700800 // We use a custom alpha clip table for the default widget previews
801 Paint alphaClipPaint = null;
802 if (createItemInfo instanceof PendingAddWidgetInfo) {
Michael Jurka038f9d82011-11-03 13:50:45 -0700803 if (((PendingAddWidgetInfo) createItemInfo).previewImage != 0) {
Peter Ng8db70002011-10-25 15:40:08 -0700804 MaskFilter alphaClipTable = TableMaskFilter.CreateClipTable(0, 255);
805 alphaClipPaint = new Paint();
806 alphaClipPaint.setMaskFilter(alphaClipTable);
807 }
808 }
809
Winson Chung1120e032011-11-22 16:11:31 -0800810 // Save the preview for the outline generation, then dim the preview
811 outline = Bitmap.createScaledBitmap(preview, preview.getWidth(), preview.getHeight(),
812 false);
Winson Chung1120e032011-11-22 16:11:31 -0800813
Winson Chung4b576be2011-04-27 17:40:20 -0700814 // Start the drag
Winson Chung1120e032011-11-22 16:11:31 -0800815 alphaClipPaint = null;
Winson Chung641d71d2012-04-26 15:58:01 -0700816 mLauncher.lockScreenOrientation();
Winson Chung1120e032011-11-22 16:11:31 -0800817 mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, outline, alphaClipPaint);
818 mDragController.startDrag(image, preview, this, createItemInfo,
Winson Chung72d59842012-02-22 13:51:36 -0800819 DragController.DRAG_ACTION_COPY, null, scale);
Winson Chung1120e032011-11-22 16:11:31 -0800820 outline.recycle();
821 preview.recycle();
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700822 return true;
Winson Chung4b576be2011-04-27 17:40:20 -0700823 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800824
Winson Chung4b576be2011-04-27 17:40:20 -0700825 @Override
Adam Cohened66b2b2012-01-23 17:28:51 -0800826 protected boolean beginDragging(final View v) {
Winson Chung4b576be2011-04-27 17:40:20 -0700827 if (!super.beginDragging(v)) return false;
828
829 if (v instanceof PagedViewIcon) {
830 beginDraggingApplication(v);
831 } else if (v instanceof PagedViewWidget) {
Adam Cohen88c5d2d2012-05-09 21:34:33 -0700832 if (!beginDraggingWidget(v)) {
833 return false;
834 }
Winson Chung4b576be2011-04-27 17:40:20 -0700835 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800836
837 // We delay entering spring-loaded mode slightly to make sure the UI
838 // thready is free of any work.
839 postDelayed(new Runnable() {
840 @Override
841 public void run() {
Adam Cohen1b36dc32012-02-13 19:27:37 -0800842 // We don't enter spring-loaded mode if the drag has been cancelled
843 if (mLauncher.getDragController().isDragging()) {
844 // Dismiss the cling
845 mLauncher.dismissAllAppsCling(null);
Adam Cohened66b2b2012-01-23 17:28:51 -0800846
Adam Cohen1b36dc32012-02-13 19:27:37 -0800847 // Reset the alpha on the dragged icon before we drag
848 resetDrawableState();
Adam Cohened66b2b2012-01-23 17:28:51 -0800849
Adam Cohen1b36dc32012-02-13 19:27:37 -0800850 // Go into spring loaded mode (must happen before we startDrag())
851 mLauncher.enterSpringLoadedDragMode();
852 }
Adam Cohened66b2b2012-01-23 17:28:51 -0800853 }
Winson Chung72d59842012-02-22 13:51:36 -0800854 }, 150);
Adam Cohened66b2b2012-01-23 17:28:51 -0800855
Winson Chung785d2eb2011-04-14 16:08:02 -0700856 return true;
857 }
Adam Cohen1b36dc32012-02-13 19:27:37 -0800858
Winson Chunga48487a2012-03-20 16:19:37 -0700859 /**
860 * Clean up after dragging.
861 *
862 * @param target where the item was dragged to (can be null if the item was flung)
863 */
864 private void endDragging(View target, boolean isFlingToDelete, boolean success) {
Winson Chunga48487a2012-03-20 16:19:37 -0700865 if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() &&
Adam Cohend4d7aa52011-07-19 21:47:37 -0700866 !(target instanceof DeleteDropTarget))) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700867 // Exit spring loaded mode if we have not successfully dropped or have not handled the
868 // drop in Workspace
869 mLauncher.exitSpringLoadedDragMode();
870 }
Winson Chung4b919f82012-05-01 10:44:08 -0700871 mLauncher.unlockScreenOrientation(false);
Winson Chung785d2eb2011-04-14 16:08:02 -0700872 }
873
Winson Chung785d2eb2011-04-14 16:08:02 -0700874 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700875 public View getContent() {
876 return null;
877 }
878
879 @Override
880 public void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700881 mInTransition = true;
882 if (toWorkspace) {
883 cancelAllTasks();
884 }
885 }
886
887 @Override
Michael Jurkaa35e35a2012-04-26 15:04:28 -0700888 public void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace) {
Michael Jurka39e5d172012-03-12 18:36:12 -0700889 }
890
891 @Override
892 public void onLauncherTransitionStep(Launcher l, float t) {
893 }
894
895 @Override
896 public void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace) {
897 mInTransition = false;
898 for (AsyncTaskPageData d : mDeferredSyncWidgetPageItems) {
899 onSyncWidgetPageItems(d);
900 }
901 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700902 for (Runnable r : mDeferredPrepareLoadWidgetPreviewsTasks) {
903 r.run();
904 }
905 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Michael Jurka5e368ff2012-05-14 23:13:15 -0700906 mForceDrawAllChildrenNextFrame = !toWorkspace;
Michael Jurka39e5d172012-03-12 18:36:12 -0700907 }
908
909 @Override
Winson Chunga48487a2012-03-20 16:19:37 -0700910 public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete,
911 boolean success) {
912 // Return early and wait for onFlingToDeleteCompleted if this was the result of a fling
913 if (isFlingToDelete) return;
914
915 endDragging(target, false, success);
Winson Chungfc79c802011-05-02 13:35:34 -0700916
917 // Display an error message if the drag failed due to there not being enough space on the
918 // target layout we were dropping on.
919 if (!success) {
920 boolean showOutOfSpaceMessage = false;
921 if (target instanceof Workspace) {
922 int currentScreen = mLauncher.getCurrentWorkspaceScreen();
923 Workspace workspace = (Workspace) target;
924 CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen);
Adam Cohenc0dcf592011-06-01 15:30:43 -0700925 ItemInfo itemInfo = (ItemInfo) d.dragInfo;
Winson Chungfc79c802011-05-02 13:35:34 -0700926 if (layout != null) {
927 layout.calculateSpans(itemInfo);
928 showOutOfSpaceMessage =
929 !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY);
930 }
931 }
Winson Chungfc79c802011-05-02 13:35:34 -0700932 if (showOutOfSpaceMessage) {
Winson Chung93eef082012-03-23 15:59:27 -0700933 mLauncher.showOutOfSpaceMessage(false);
Winson Chungfc79c802011-05-02 13:35:34 -0700934 }
Adam Cohen7a326642012-02-22 12:03:22 -0800935
Winson Chung7bd1bbb2012-02-13 18:29:29 -0800936 d.deferDragViewCleanupPostAnimation = false;
Winson Chungfc79c802011-05-02 13:35:34 -0700937 }
Adam Cohen0e56cc92012-05-11 15:57:05 -0700938 cleanupWidgetPreloading(success);
Adam Cohen7a326642012-02-22 12:03:22 -0800939 mDraggingWidget = false;
Winson Chung785d2eb2011-04-14 16:08:02 -0700940 }
941
Winson Chunga48487a2012-03-20 16:19:37 -0700942 @Override
943 public void onFlingToDeleteCompleted() {
944 // We just dismiss the drag when we fling, so cleanup here
945 endDragging(null, true, true);
Adam Cohen0e56cc92012-05-11 15:57:05 -0700946 cleanupWidgetPreloading(false);
Winson Chunga48487a2012-03-20 16:19:37 -0700947 mDraggingWidget = false;
948 }
949
950 @Override
Winson Chung043f2af2012-03-01 16:09:54 -0800951 public boolean supportsFlingToDelete() {
Winson Chunga48487a2012-03-20 16:19:37 -0700952 return true;
Winson Chung043f2af2012-03-01 16:09:54 -0800953 }
954
Winson Chung7f0acdd2011-09-19 18:34:19 -0700955 @Override
956 protected void onDetachedFromWindow() {
957 super.onDetachedFromWindow();
Adam Cohen0cd3b642011-10-14 14:58:00 -0700958 cancelAllTasks();
959 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700960
Michael Jurkae326f182011-11-21 14:05:46 -0800961 public void clearAllWidgetPages() {
962 cancelAllTasks();
963 int count = getChildCount();
964 for (int i = 0; i < count; i++) {
965 View v = getPageAt(i);
966 if (v instanceof PagedViewGridLayout) {
967 ((PagedViewGridLayout) v).removeAllViewsOnPage();
968 mDirtyPageContent.set(i, true);
969 }
970 }
971 }
972
Adam Cohen0cd3b642011-10-14 14:58:00 -0700973 private void cancelAllTasks() {
Winson Chung7f0acdd2011-09-19 18:34:19 -0700974 // Clean up all the async tasks
975 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
976 while (iter.hasNext()) {
977 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
978 task.cancel(false);
979 iter.remove();
Michael Jurka39e5d172012-03-12 18:36:12 -0700980 mDirtyPageContent.set(task.page, true);
Winson Chung7ce99852012-05-24 17:34:08 -0700981
982 // We've already preallocated the views for the data to load into, so clear them as well
983 View v = getPageAt(task.page);
984 if (v instanceof PagedViewGridLayout) {
985 ((PagedViewGridLayout) v).removeAllViewsOnPage();
986 }
Winson Chung7f0acdd2011-09-19 18:34:19 -0700987 }
Winson Chung83687b12012-04-25 16:01:01 -0700988 mDeferredSyncWidgetPageItems.clear();
Michael Jurkaf6a96902012-06-06 11:48:13 -0700989 mDeferredPrepareLoadWidgetPreviewsTasks.clear();
Winson Chung7f0acdd2011-09-19 18:34:19 -0700990 }
991
Winson Chung785d2eb2011-04-14 16:08:02 -0700992 public void setContentType(ContentType type) {
Adam Cohen0cd3b642011-10-14 14:58:00 -0700993 if (type == ContentType.Widgets) {
994 invalidatePageData(mNumAppsPages, true);
995 } else if (type == ContentType.Applications) {
996 invalidatePageData(0, true);
997 }
Winson Chungb44b5242011-06-13 11:32:14 -0700998 }
999
Adam Cohen0cd3b642011-10-14 14:58:00 -07001000 protected void snapToPage(int whichPage, int delta, int duration) {
1001 super.snapToPage(whichPage, delta, duration);
1002 updateCurrentTab(whichPage);
Winson Chung68e4c642011-11-10 15:48:25 -08001003
1004 // Update the thread priorities given the direction lookahead
1005 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1006 while (iter.hasNext()) {
1007 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001008 int pageIndex = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -08001009 if ((mNextPage > mCurrentPage && pageIndex >= mCurrentPage) ||
1010 (mNextPage < mCurrentPage && pageIndex <= mCurrentPage)) {
1011 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1012 } else {
1013 task.setThreadPriority(Process.THREAD_PRIORITY_LOWEST);
1014 }
1015 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001016 }
1017
1018 private void updateCurrentTab(int currentPage) {
1019 AppsCustomizeTabHost tabHost = getTabHost();
Winson Chungc6f10b92011-11-14 11:39:07 -08001020 if (tabHost != null) {
1021 String tag = tabHost.getCurrentTabTag();
1022 if (tag != null) {
1023 if (currentPage >= mNumAppsPages &&
1024 !tag.equals(tabHost.getTabTagForContentType(ContentType.Widgets))) {
1025 tabHost.setCurrentTabFromContent(ContentType.Widgets);
1026 } else if (currentPage < mNumAppsPages &&
1027 !tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1028 tabHost.setCurrentTabFromContent(ContentType.Applications);
1029 }
Winson Chung6a8103c2011-10-21 11:08:32 -07001030 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001031 }
1032 }
1033
Winson Chung785d2eb2011-04-14 16:08:02 -07001034 /*
1035 * Apps PagedView implementation
1036 */
Winson Chung63257c12011-05-05 17:06:13 -07001037 private void setVisibilityOnChildren(ViewGroup layout, int visibility) {
1038 int childCount = layout.getChildCount();
1039 for (int i = 0; i < childCount; ++i) {
1040 layout.getChildAt(i).setVisibility(visibility);
1041 }
1042 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001043 private void setupPage(PagedViewCellLayout layout) {
1044 layout.setCellCount(mCellCountX, mCellCountY);
1045 layout.setGap(mPageLayoutWidthGap, mPageLayoutHeightGap);
1046 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1047 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
1048
Winson Chung63257c12011-05-05 17:06:13 -07001049 // Note: We force a measure here to get around the fact that when we do layout calculations
1050 // immediately after syncing, we don't have a proper width. That said, we already know the
1051 // expected page width, so we can actually optimize by hiding all the TextView-based
1052 // children that are expensive to measure, and let that happen naturally later.
1053 setVisibilityOnChildren(layout, View.GONE);
Winson Chungdb1138b2011-06-30 14:39:35 -07001054 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001055 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung63257c12011-05-05 17:06:13 -07001056 layout.setMinimumWidth(getPageContentWidth());
Winson Chung785d2eb2011-04-14 16:08:02 -07001057 layout.measure(widthSpec, heightSpec);
Winson Chung63257c12011-05-05 17:06:13 -07001058 setVisibilityOnChildren(layout, View.VISIBLE);
Winson Chung785d2eb2011-04-14 16:08:02 -07001059 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001060
Winson Chungf314b0e2011-08-16 11:54:27 -07001061 public void syncAppsPageItems(int page, boolean immediate) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001062 // ensure that we have the right number of items on the pages
Winson Chung785d2eb2011-04-14 16:08:02 -07001063 int numCells = mCellCountX * mCellCountY;
1064 int startIndex = page * numCells;
1065 int endIndex = Math.min(startIndex + numCells, mApps.size());
Adam Cohen22f823d2011-09-01 17:22:18 -07001066 PagedViewCellLayout layout = (PagedViewCellLayout) getPageAt(page);
Winson Chung875de7e2011-06-28 14:25:17 -07001067
Winson Chung785d2eb2011-04-14 16:08:02 -07001068 layout.removeAllViewsOnPage();
Winson Chungb44b5242011-06-13 11:32:14 -07001069 ArrayList<Object> items = new ArrayList<Object>();
1070 ArrayList<Bitmap> images = new ArrayList<Bitmap>();
Winson Chung785d2eb2011-04-14 16:08:02 -07001071 for (int i = startIndex; i < endIndex; ++i) {
1072 ApplicationInfo info = mApps.get(i);
1073 PagedViewIcon icon = (PagedViewIcon) mLayoutInflater.inflate(
1074 R.layout.apps_customize_application, layout, false);
Winson Chunge4e50662012-01-23 14:45:13 -08001075 icon.applyFromApplicationInfo(info, true, this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001076 icon.setOnClickListener(this);
1077 icon.setOnLongClickListener(this);
1078 icon.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001079 icon.setOnKeyListener(this);
Winson Chung785d2eb2011-04-14 16:08:02 -07001080
1081 int index = i - startIndex;
1082 int x = index % mCellCountX;
1083 int y = index / mCellCountX;
Winson Chung6a70e9f2011-05-17 16:24:49 -07001084 layout.addViewToCellLayout(icon, -1, i, new PagedViewCellLayout.LayoutParams(x,y, 1,1));
Winson Chungb44b5242011-06-13 11:32:14 -07001085
1086 items.add(info);
1087 images.add(info.iconBitmap);
Winson Chung785d2eb2011-04-14 16:08:02 -07001088 }
Winson Chungf0ea4d32011-06-06 14:27:16 -07001089
Winson Chungf0ea4d32011-06-06 14:27:16 -07001090 layout.createHardwareLayers();
Winson Chung785d2eb2011-04-14 16:08:02 -07001091 }
Winson Chungb44b5242011-06-13 11:32:14 -07001092
1093 /**
Winson Chung68e4c642011-11-10 15:48:25 -08001094 * A helper to return the priority for loading of the specified widget page.
1095 */
1096 private int getWidgetPageLoadPriority(int page) {
1097 // If we are snapping to another page, use that index as the target page index
1098 int toPage = mCurrentPage;
1099 if (mNextPage > -1) {
1100 toPage = mNextPage;
1101 }
1102
1103 // We use the distance from the target page as an initial guess of priority, but if there
1104 // are no pages of higher priority than the page specified, then bump up the priority of
1105 // the specified page.
1106 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1107 int minPageDiff = Integer.MAX_VALUE;
1108 while (iter.hasNext()) {
1109 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001110 minPageDiff = Math.abs(task.page - toPage);
Winson Chung68e4c642011-11-10 15:48:25 -08001111 }
1112
1113 int rawPageDiff = Math.abs(page - toPage);
1114 return rawPageDiff - Math.min(rawPageDiff, minPageDiff);
1115 }
1116 /**
Winson Chungb44b5242011-06-13 11:32:14 -07001117 * Return the appropriate thread priority for loading for a given page (we give the current
1118 * page much higher priority)
1119 */
1120 private int getThreadPriorityForPage(int page) {
1121 // TODO-APPS_CUSTOMIZE: detect number of cores and set thread priorities accordingly below
Winson Chung68e4c642011-11-10 15:48:25 -08001122 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001123 if (pageDiff <= 0) {
Winson Chung68e4c642011-11-10 15:48:25 -08001124 return Process.THREAD_PRIORITY_LESS_FAVORABLE;
Winson Chungb44b5242011-06-13 11:32:14 -07001125 } else if (pageDiff <= 1) {
Winson Chung68e4c642011-11-10 15:48:25 -08001126 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001127 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001128 return Process.THREAD_PRIORITY_LOWEST;
Winson Chungb44b5242011-06-13 11:32:14 -07001129 }
1130 }
Winson Chungf314b0e2011-08-16 11:54:27 -07001131 private int getSleepForPage(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001132 int pageDiff = getWidgetPageLoadPriority(page);
Winson Chungf314b0e2011-08-16 11:54:27 -07001133 return Math.max(0, pageDiff * sPageSleepDelay);
1134 }
Winson Chungb44b5242011-06-13 11:32:14 -07001135 /**
1136 * Creates and executes a new AsyncTask to load a page of widget previews.
1137 */
1138 private void prepareLoadWidgetPreviewsTask(int page, ArrayList<Object> widgets,
Winson Chungd2945262011-06-24 15:22:14 -07001139 int cellWidth, int cellHeight, int cellCountX) {
Winson Chung68e4c642011-11-10 15:48:25 -08001140
Winson Chungb44b5242011-06-13 11:32:14 -07001141 // Prune all tasks that are no longer needed
1142 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1143 while (iter.hasNext()) {
1144 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
Michael Jurka39e5d172012-03-12 18:36:12 -07001145 int taskPage = task.page;
Winson Chung68e4c642011-11-10 15:48:25 -08001146 if (taskPage < getAssociatedLowerPageBound(mCurrentPage) ||
1147 taskPage > getAssociatedUpperPageBound(mCurrentPage)) {
Winson Chungb44b5242011-06-13 11:32:14 -07001148 task.cancel(false);
1149 iter.remove();
1150 } else {
Winson Chung68e4c642011-11-10 15:48:25 -08001151 task.setThreadPriority(getThreadPriorityForPage(taskPage));
Winson Chungb44b5242011-06-13 11:32:14 -07001152 }
1153 }
1154
Winson Chungf314b0e2011-08-16 11:54:27 -07001155 // 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 -07001156 final int sleepMs = getSleepForPage(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001157 AsyncTaskPageData pageData = new AsyncTaskPageData(page, widgets, cellWidth, cellHeight,
Michael Jurka038f9d82011-11-03 13:50:45 -07001158 new AsyncTaskCallback() {
Winson Chungb44b5242011-06-13 11:32:14 -07001159 @Override
1160 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001161 try {
Winson Chung09945932011-09-20 14:22:40 -07001162 try {
1163 Thread.sleep(sleepMs);
1164 } catch (Exception e) {}
1165 loadWidgetPreviewsInBackground(task, data);
1166 } finally {
1167 if (task.isCancelled()) {
1168 data.cleanup(true);
1169 }
1170 }
Winson Chungb44b5242011-06-13 11:32:14 -07001171 }
1172 },
1173 new AsyncTaskCallback() {
1174 @Override
1175 public void run(AppsCustomizeAsyncTask task, AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001176 mRunningTasks.remove(task);
1177 if (task.isCancelled()) return;
1178 // do cleanup inside onSyncWidgetPageItems
1179 onSyncWidgetPageItems(data);
Winson Chungb44b5242011-06-13 11:32:14 -07001180 }
Winson Chung09945932011-09-20 14:22:40 -07001181 });
Winson Chungb44b5242011-06-13 11:32:14 -07001182
1183 // Ensure that the task is appropriately prioritized and runs in parallel
Adam Cohen0cd3b642011-10-14 14:58:00 -07001184 AppsCustomizeAsyncTask t = new AppsCustomizeAsyncTask(page,
Winson Chung875de7e2011-06-28 14:25:17 -07001185 AsyncTaskPageData.Type.LoadWidgetPreviewData);
Michael Jurka39e5d172012-03-12 18:36:12 -07001186 t.setThreadPriority(getThreadPriorityForPage(page));
Winson Chungb44b5242011-06-13 11:32:14 -07001187 t.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageData);
1188 mRunningTasks.add(t);
1189 }
Winson Chungb44b5242011-06-13 11:32:14 -07001190
Winson Chung785d2eb2011-04-14 16:08:02 -07001191 /*
1192 * Widgets PagedView implementation
1193 */
Winson Chung4e6a9762011-05-09 11:56:34 -07001194 private void setupPage(PagedViewGridLayout layout) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001195 layout.setPadding(mPageLayoutPaddingLeft, mPageLayoutPaddingTop,
1196 mPageLayoutPaddingRight, mPageLayoutPaddingBottom);
Winson Chung63257c12011-05-05 17:06:13 -07001197
1198 // Note: We force a measure here to get around the fact that when we do layout calculations
Winson Chungd52f3d82011-07-12 14:29:11 -07001199 // immediately after syncing, we don't have a proper width.
Winson Chung63257c12011-05-05 17:06:13 -07001200 int widthSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.AT_MOST);
1201 int heightSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.AT_MOST);
Winson Chung785d2eb2011-04-14 16:08:02 -07001202 layout.setMinimumWidth(getPageContentWidth());
Winson Chung63257c12011-05-05 17:06:13 -07001203 layout.measure(widthSpec, heightSpec);
Winson Chung785d2eb2011-04-14 16:08:02 -07001204 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001205
Winson Chung5fc72b32011-10-11 17:53:58 -07001206 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h) {
Michael Jurkadac85912012-05-18 15:04:49 -07001207 renderDrawableToBitmap(d, bitmap, x, y, w, h, 1f);
Winson Chung70fc4382011-08-08 15:31:33 -07001208 }
Michael Jurka92f3d462011-11-22 21:02:29 -08001209
Winson Chung5fc72b32011-10-11 17:53:58 -07001210 private void renderDrawableToBitmap(Drawable d, Bitmap bitmap, int x, int y, int w, int h,
Michael Jurkadac85912012-05-18 15:04:49 -07001211 float scale) {
Winson Chung201bc822011-06-20 15:41:53 -07001212 if (bitmap != null) {
Winson Chungb44b5242011-06-13 11:32:14 -07001213 Canvas c = new Canvas(bitmap);
Winson Chung5fc72b32011-10-11 17:53:58 -07001214 c.scale(scale, scale);
Winson Chung201bc822011-06-20 15:41:53 -07001215 Rect oldBounds = d.copyBounds();
1216 d.setBounds(x, y, x + w, y + h);
1217 d.draw(c);
1218 d.setBounds(oldBounds); // Restore the bounds
Adam Cohenaaf473c2011-08-03 12:02:47 -07001219 c.setBitmap(null);
Winson Chung201bc822011-06-20 15:41:53 -07001220 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001221 }
Winson Chung5fc72b32011-10-11 17:53:58 -07001222
Michael Jurkadac85912012-05-18 15:04:49 -07001223 private Bitmap getShortcutPreview(ResolveInfo info, int maxWidth, int maxHeight) {
1224 Bitmap tempBitmap = mCachedShortcutPreviewBitmap.get();
1225 final Canvas c = mCachedShortcutPreviewCanvas.get();
1226 if (tempBitmap == null ||
1227 tempBitmap.getWidth() != maxWidth ||
1228 tempBitmap.getHeight() != maxHeight) {
1229 tempBitmap = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1230 mCachedShortcutPreviewBitmap.set(tempBitmap);
1231 } else {
1232 c.setBitmap(tempBitmap);
1233 c.drawColor(0, PorterDuff.Mode.CLEAR);
1234 c.setBitmap(null);
1235 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001236 // Render the icon
Winson Chung0b9fcf52011-10-31 13:05:15 -07001237 Drawable icon = mIconCache.getFullResIcon(info);
Michael Jurkadac85912012-05-18 15:04:49 -07001238
1239 int paddingTop =
1240 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_top);
1241 int paddingLeft =
1242 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_left);
1243 int paddingRight =
1244 getResources().getDimensionPixelOffset(R.dimen.shortcut_preview_padding_right);
1245
1246 int scaledIconWidth = (maxWidth - paddingLeft - paddingRight);
1247 float scaleSize = scaledIconWidth / (float) mAppIconSize;
1248
1249 renderDrawableToBitmap(
1250 icon, tempBitmap, paddingLeft, paddingTop, scaledIconWidth, scaledIconWidth);
1251
1252 Bitmap preview = Bitmap.createBitmap(maxWidth, maxHeight, Config.ARGB_8888);
1253 c.setBitmap(preview);
1254 Paint p = mCachedShortcutPreviewPaint.get();
1255 if (p == null) {
1256 p = new Paint();
1257 ColorMatrix colorMatrix = new ColorMatrix();
1258 colorMatrix.setSaturation(0);
1259 p.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
1260 p.setAlpha((int) (255 * 0.06f));
1261 //float density = 1f;
1262 //p.setMaskFilter(new BlurMaskFilter(15*density, BlurMaskFilter.Blur.NORMAL));
1263 mCachedShortcutPreviewPaint.set(p);
1264 }
1265 c.drawBitmap(tempBitmap, 0, 0, p);
1266 c.setBitmap(null);
1267
1268 renderDrawableToBitmap(icon, preview, 0, 0, mAppIconSize, mAppIconSize);
1269
Winson Chungb44b5242011-06-13 11:32:14 -07001270 return preview;
Winson Chung1ed747a2011-05-03 16:18:34 -07001271 }
Winson Chung1ed747a2011-05-03 16:18:34 -07001272
Michael Jurkadac85912012-05-18 15:04:49 -07001273 private Bitmap getWidgetPreview(ComponentName provider, int previewImage,
1274 int iconId, int cellHSpan, int cellVSpan, int maxWidth,
1275 int maxHeight) {
Winson Chung4b576be2011-04-27 17:40:20 -07001276 // Load the preview image if possible
Michael Jurka038f9d82011-11-03 13:50:45 -07001277 String packageName = provider.getPackageName();
1278 if (maxWidth < 0) maxWidth = Integer.MAX_VALUE;
1279 if (maxHeight < 0) maxHeight = Integer.MAX_VALUE;
Winson Chung4b576be2011-04-27 17:40:20 -07001280
Michael Jurka038f9d82011-11-03 13:50:45 -07001281 Drawable drawable = null;
1282 if (previewImage != 0) {
1283 drawable = mPackageManager.getDrawable(packageName, previewImage, null);
1284 if (drawable == null) {
Adam Cohen0e56cc92012-05-11 15:57:05 -07001285 Log.w(TAG, "Can't load widget preview drawable 0x" +
Michael Jurka038f9d82011-11-03 13:50:45 -07001286 Integer.toHexString(previewImage) + " for provider: " + provider);
Winson Chung4b576be2011-04-27 17:40:20 -07001287 }
1288 }
1289
Michael Jurka038f9d82011-11-03 13:50:45 -07001290 int bitmapWidth;
1291 int bitmapHeight;
Michael Jurkadac85912012-05-18 15:04:49 -07001292 Bitmap defaultPreview = null;
Michael Jurka038f9d82011-11-03 13:50:45 -07001293 boolean widgetPreviewExists = (drawable != null);
1294 if (widgetPreviewExists) {
1295 bitmapWidth = drawable.getIntrinsicWidth();
1296 bitmapHeight = drawable.getIntrinsicHeight();
Michael Jurka038f9d82011-11-03 13:50:45 -07001297 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001298 // Generate a preview image if we couldn't load one
Michael Jurkac7e52f52012-03-26 06:20:31 -07001299 if (cellHSpan < 1) cellHSpan = 1;
1300 if (cellVSpan < 1) cellVSpan = 1;
Michael Jurkadac85912012-05-18 15:04:49 -07001301
1302 BitmapDrawable previewDrawable = (BitmapDrawable) getResources()
1303 .getDrawable(R.drawable.widget_preview_tile);
1304 final int previewDrawableWidth = previewDrawable
1305 .getIntrinsicWidth();
1306 final int previewDrawableHeight = previewDrawable
1307 .getIntrinsicHeight();
1308 bitmapWidth = previewDrawableWidth * cellHSpan; // subtract 2 dips
1309 bitmapHeight = previewDrawableHeight * cellVSpan;
1310
1311 defaultPreview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1312 Config.ARGB_8888);
1313 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1314 c.setBitmap(defaultPreview);
1315 previewDrawable.setBounds(0, 0, bitmapWidth, bitmapHeight);
1316 previewDrawable.setTileModeXY(Shader.TileMode.REPEAT,
1317 Shader.TileMode.REPEAT);
1318 previewDrawable.draw(c);
1319 c.setBitmap(null);
1320
1321 // Draw the icon in the top left corner
1322 int minOffset = (int) (mAppIconSize * sWidgetPreviewIconPaddingPercentage);
1323 int smallestSide = Math.min(bitmapWidth, bitmapHeight);
1324 float iconScale = Math.min((float) smallestSide
1325 / (mAppIconSize + 2 * minOffset), 1f);
1326
1327 try {
1328 Drawable icon = null;
1329 int hoffset =
1330 (int) ((previewDrawableWidth - mAppIconSize * iconScale) / 2);
1331 int yoffset =
1332 (int) ((previewDrawableHeight - mAppIconSize * iconScale) / 2);
1333 if (iconId > 0)
1334 icon = mIconCache.getFullResIcon(packageName, iconId);
1335 Resources resources = mLauncher.getResources();
1336 if (icon != null) {
1337 renderDrawableToBitmap(icon, defaultPreview, hoffset,
1338 yoffset, (int) (mAppIconSize * iconScale),
1339 (int) (mAppIconSize * iconScale));
Winson Chung5fc72b32011-10-11 17:53:58 -07001340 }
Michael Jurkadac85912012-05-18 15:04:49 -07001341 } catch (Resources.NotFoundException e) {
Winson Chung1ed747a2011-05-03 16:18:34 -07001342 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001343 }
1344
Michael Jurkadac85912012-05-18 15:04:49 -07001345 // Scale to fit width only - let the widget preview be clipped in the
1346 // vertical dimension
Michael Jurka038f9d82011-11-03 13:50:45 -07001347 float scale = 1f;
1348 if (bitmapWidth > maxWidth) {
1349 scale = maxWidth / (float) bitmapWidth;
1350 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001351 if (scale != 1f) {
1352 bitmapWidth = (int) (scale * bitmapWidth);
1353 bitmapHeight = (int) (scale * bitmapHeight);
1354 }
1355
Michael Jurkadac85912012-05-18 15:04:49 -07001356 Bitmap preview = Bitmap.createBitmap(bitmapWidth, bitmapHeight,
1357 Config.ARGB_8888);
Michael Jurka038f9d82011-11-03 13:50:45 -07001358
Michael Jurkadac85912012-05-18 15:04:49 -07001359 // Draw the scaled preview into the final bitmap
Michael Jurka038f9d82011-11-03 13:50:45 -07001360 if (widgetPreviewExists) {
Michael Jurkadac85912012-05-18 15:04:49 -07001361 renderDrawableToBitmap(drawable, preview, 0, 0, bitmapWidth,
1362 bitmapHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001363 } else {
Michael Jurkadac85912012-05-18 15:04:49 -07001364 final Canvas c = mCachedAppWidgetPreviewCanvas.get();
1365 final Rect src = mCachedAppWidgetPreviewSrcRect.get();
1366 final Rect dest = mCachedAppWidgetPreviewDestRect.get();
1367 c.setBitmap(preview);
1368 src.set(0, 0, defaultPreview.getWidth(), defaultPreview.getHeight());
1369 dest.set(0, 0, preview.getWidth(), preview.getHeight());
1370
1371 Paint p = mCachedAppWidgetPreviewPaint.get();
1372 if (p == null) {
1373 p = new Paint();
1374 p.setFilterBitmap(true);
1375 mCachedAppWidgetPreviewPaint.set(p);
Peter Ng8db70002011-10-25 15:40:08 -07001376 }
Michael Jurkadac85912012-05-18 15:04:49 -07001377 c.drawBitmap(defaultPreview, src, dest, p);
1378 c.setBitmap(null);
Winson Chung4b576be2011-04-27 17:40:20 -07001379 }
Winson Chungb44b5242011-06-13 11:32:14 -07001380 return preview;
Winson Chung785d2eb2011-04-14 16:08:02 -07001381 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001382
Michael Jurka038f9d82011-11-03 13:50:45 -07001383 public void syncWidgetPageItems(final int page, final boolean immediate) {
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001384 int numItemsPerPage = mWidgetCountX * mWidgetCountY;
Winson Chungb44b5242011-06-13 11:32:14 -07001385
Winson Chungd2945262011-06-24 15:22:14 -07001386 // Calculate the dimensions of each cell we are giving to each widget
Michael Jurka038f9d82011-11-03 13:50:45 -07001387 final ArrayList<Object> items = new ArrayList<Object>();
1388 int contentWidth = mWidgetSpacingLayout.getContentWidth();
1389 final int cellWidth = ((contentWidth - mPageLayoutPaddingLeft - mPageLayoutPaddingRight
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001390 - ((mWidgetCountX - 1) * mWidgetWidthGap)) / mWidgetCountX);
Michael Jurka038f9d82011-11-03 13:50:45 -07001391 int contentHeight = mWidgetSpacingLayout.getContentHeight();
1392 final int cellHeight = ((contentHeight - mPageLayoutPaddingTop - mPageLayoutPaddingBottom
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001393 - ((mWidgetCountY - 1) * mWidgetHeightGap)) / mWidgetCountY);
Winson Chungd2945262011-06-24 15:22:14 -07001394
Winson Chunge4a647f2011-09-30 14:41:25 -07001395 // Prepare the set of widgets to load previews for in the background
Michael Jurka39e5d172012-03-12 18:36:12 -07001396 int offset = (page - mNumAppsPages) * numItemsPerPage;
Winson Chung6a3fd3f2011-08-02 14:03:26 -07001397 for (int i = offset; i < Math.min(offset + numItemsPerPage, mWidgets.size()); ++i) {
1398 items.add(mWidgets.get(i));
Winson Chungb44b5242011-06-13 11:32:14 -07001399 }
1400
Winson Chunge4a647f2011-09-30 14:41:25 -07001401 // Prepopulate the pages with the other widget info, and fill in the previews later
Michael Jurka39e5d172012-03-12 18:36:12 -07001402 final PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chunge4a647f2011-09-30 14:41:25 -07001403 layout.setColumnCount(layout.getCellCountX());
1404 for (int i = 0; i < items.size(); ++i) {
1405 Object rawInfo = items.get(i);
1406 PendingAddItemInfo createItemInfo = null;
1407 PagedViewWidget widget = (PagedViewWidget) mLayoutInflater.inflate(
1408 R.layout.apps_customize_widget, layout, false);
1409 if (rawInfo instanceof AppWidgetProviderInfo) {
1410 // Fill in the widget information
1411 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
1412 createItemInfo = new PendingAddWidgetInfo(info, null, null);
Adam Cohen1f362702012-04-04 14:58:12 -07001413
1414 // Determine the widget spans and min resize spans.
Adam Cohen2f093b62012-04-30 18:59:53 -07001415 int[] spanXY = Launcher.getSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001416 createItemInfo.spanX = spanXY[0];
1417 createItemInfo.spanY = spanXY[1];
Adam Cohen2f093b62012-04-30 18:59:53 -07001418 int[] minSpanXY = Launcher.getMinSpanForWidget(mLauncher, info);
Adam Cohen1f362702012-04-04 14:58:12 -07001419 createItemInfo.minSpanX = minSpanXY[0];
1420 createItemInfo.minSpanY = minSpanXY[1];
1421
1422 widget.applyFromAppWidgetProviderInfo(info, -1, spanXY);
Winson Chunge4a647f2011-09-30 14:41:25 -07001423 widget.setTag(createItemInfo);
Adam Cohened66b2b2012-01-23 17:28:51 -08001424 widget.setShortPressListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001425 } else if (rawInfo instanceof ResolveInfo) {
1426 // Fill in the shortcuts information
1427 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001428 createItemInfo = new PendingAddShortcutInfo(info.activityInfo);
Winson Chunge4a647f2011-09-30 14:41:25 -07001429 createItemInfo.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT;
1430 createItemInfo.componentName = new ComponentName(info.activityInfo.packageName,
1431 info.activityInfo.name);
Michael Jurka82369a12012-01-12 08:08:38 -08001432 widget.applyFromResolveInfo(mPackageManager, info);
Winson Chunge4a647f2011-09-30 14:41:25 -07001433 widget.setTag(createItemInfo);
1434 }
1435 widget.setOnClickListener(this);
1436 widget.setOnLongClickListener(this);
1437 widget.setOnTouchListener(this);
Winson Chungc6f10b92011-11-14 11:39:07 -08001438 widget.setOnKeyListener(this);
Winson Chunge4a647f2011-09-30 14:41:25 -07001439
1440 // Layout each widget
1441 int ix = i % mWidgetCountX;
1442 int iy = i / mWidgetCountX;
1443 GridLayout.LayoutParams lp = new GridLayout.LayoutParams(
1444 GridLayout.spec(iy, GridLayout.LEFT),
1445 GridLayout.spec(ix, GridLayout.TOP));
1446 lp.width = cellWidth;
1447 lp.height = cellHeight;
1448 lp.setGravity(Gravity.TOP | Gravity.LEFT);
1449 if (ix > 0) lp.leftMargin = mWidgetWidthGap;
1450 if (iy > 0) lp.topMargin = mWidgetHeightGap;
1451 layout.addView(widget, lp);
1452 }
1453
Michael Jurka038f9d82011-11-03 13:50:45 -07001454 // wait until a call on onLayout to start loading, because
1455 // PagedViewWidget.getPreviewSize() will return 0 if it hasn't been laid out
1456 // TODO: can we do a measure/layout immediately?
1457 layout.setOnLayoutListener(new Runnable() {
1458 public void run() {
1459 // Load the widget previews
1460 int maxPreviewWidth = cellWidth;
1461 int maxPreviewHeight = cellHeight;
1462 if (layout.getChildCount() > 0) {
1463 PagedViewWidget w = (PagedViewWidget) layout.getChildAt(0);
1464 int[] maxSize = w.getPreviewSize();
1465 maxPreviewWidth = maxSize[0];
1466 maxPreviewHeight = maxSize[1];
1467 }
1468 if (immediate) {
1469 AsyncTaskPageData data = new AsyncTaskPageData(page, items,
1470 maxPreviewWidth, maxPreviewHeight, null, null);
1471 loadWidgetPreviewsInBackground(null, data);
1472 onSyncWidgetPageItems(data);
1473 } else {
Michael Jurkaf6a96902012-06-06 11:48:13 -07001474 if (mInTransition) {
1475 mDeferredPrepareLoadWidgetPreviewsTasks.add(this);
1476 } else {
1477 prepareLoadWidgetPreviewsTask(page, items,
1478 maxPreviewWidth, maxPreviewHeight, mWidgetCountX);
1479 }
Michael Jurka038f9d82011-11-03 13:50:45 -07001480 }
1481 }
1482 });
Winson Chungf314b0e2011-08-16 11:54:27 -07001483 }
1484 private void loadWidgetPreviewsInBackground(AppsCustomizeAsyncTask task,
1485 AsyncTaskPageData data) {
Winson Chung68e4c642011-11-10 15:48:25 -08001486 // loadWidgetPreviewsInBackground can be called without a task to load a set of widget
1487 // previews synchronously
Winson Chungf314b0e2011-08-16 11:54:27 -07001488 if (task != null) {
1489 // Ensure that this task starts running at the correct priority
1490 task.syncThreadPriority();
1491 }
1492
1493 // Load each of the widget/shortcut previews
1494 ArrayList<Object> items = data.items;
1495 ArrayList<Bitmap> images = data.generatedImages;
1496 int count = items.size();
Winson Chungf314b0e2011-08-16 11:54:27 -07001497 for (int i = 0; i < count; ++i) {
1498 if (task != null) {
1499 // Ensure we haven't been cancelled yet
1500 if (task.isCancelled()) break;
1501 // Before work on each item, ensure that this task is running at the correct
1502 // priority
1503 task.syncThreadPriority();
1504 }
1505
1506 Object rawInfo = items.get(i);
1507 if (rawInfo instanceof AppWidgetProviderInfo) {
1508 AppWidgetProviderInfo info = (AppWidgetProviderInfo) rawInfo;
Adam Cohen2f093b62012-04-30 18:59:53 -07001509 int[] cellSpans = Launcher.getSpanForWidget(mLauncher, info);
Winson Chung72d59842012-02-22 13:51:36 -08001510
1511 int maxWidth = Math.min(data.maxImageWidth,
1512 mWidgetSpacingLayout.estimateCellWidth(cellSpans[0]));
1513 int maxHeight = Math.min(data.maxImageHeight,
1514 mWidgetSpacingLayout.estimateCellHeight(cellSpans[1]));
Michael Jurka038f9d82011-11-03 13:50:45 -07001515 Bitmap b = getWidgetPreview(info.provider, info.previewImage, info.icon,
Winson Chung72d59842012-02-22 13:51:36 -08001516 cellSpans[0], cellSpans[1], maxWidth, maxHeight);
Michael Jurka038f9d82011-11-03 13:50:45 -07001517 images.add(b);
Winson Chungf314b0e2011-08-16 11:54:27 -07001518 } else if (rawInfo instanceof ResolveInfo) {
1519 // Fill in the shortcuts information
1520 ResolveInfo info = (ResolveInfo) rawInfo;
Michael Jurkadac85912012-05-18 15:04:49 -07001521 images.add(getShortcutPreview(info, data.maxImageWidth, data.maxImageHeight));
Winson Chungf314b0e2011-08-16 11:54:27 -07001522 }
1523 }
Winson Chungb44b5242011-06-13 11:32:14 -07001524 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001525
Winson Chungb44b5242011-06-13 11:32:14 -07001526 private void onSyncWidgetPageItems(AsyncTaskPageData data) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001527 if (mInTransition) {
1528 mDeferredSyncWidgetPageItems.add(data);
1529 return;
Winson Chung785d2eb2011-04-14 16:08:02 -07001530 }
Michael Jurka39e5d172012-03-12 18:36:12 -07001531 try {
1532 int page = data.page;
1533 PagedViewGridLayout layout = (PagedViewGridLayout) getPageAt(page);
Winson Chungb44b5242011-06-13 11:32:14 -07001534
Michael Jurka39e5d172012-03-12 18:36:12 -07001535 ArrayList<Object> items = data.items;
1536 int count = items.size();
1537 for (int i = 0; i < count; ++i) {
1538 PagedViewWidget widget = (PagedViewWidget) layout.getChildAt(i);
1539 if (widget != null) {
1540 Bitmap preview = data.generatedImages.get(i);
1541 widget.applyPreview(new FastBitmapDrawable(preview), i);
1542 }
1543 }
Winson Chung68e4c642011-11-10 15:48:25 -08001544
Michael Jurka39e5d172012-03-12 18:36:12 -07001545 layout.createHardwareLayer();
1546 invalidate();
1547
1548 // Update all thread priorities
1549 Iterator<AppsCustomizeAsyncTask> iter = mRunningTasks.iterator();
1550 while (iter.hasNext()) {
1551 AppsCustomizeAsyncTask task = (AppsCustomizeAsyncTask) iter.next();
1552 int pageIndex = task.page;
1553 task.setThreadPriority(getThreadPriorityForPage(pageIndex));
1554 }
1555 } finally {
1556 data.cleanup(false);
Winson Chung68e4c642011-11-10 15:48:25 -08001557 }
Winson Chungb44b5242011-06-13 11:32:14 -07001558 }
Winson Chung46af2e82011-05-09 16:00:53 -07001559
Winson Chung785d2eb2011-04-14 16:08:02 -07001560 @Override
1561 public void syncPages() {
1562 removeAllViews();
Adam Cohen0cd3b642011-10-14 14:58:00 -07001563 cancelAllTasks();
Winson Chung875de7e2011-06-28 14:25:17 -07001564
Adam Cohen0cd3b642011-10-14 14:58:00 -07001565 Context context = getContext();
1566 for (int j = 0; j < mNumWidgetPages; ++j) {
1567 PagedViewGridLayout layout = new PagedViewGridLayout(context, mWidgetCountX,
1568 mWidgetCountY);
1569 setupPage(layout);
Michael Jurka39e5d172012-03-12 18:36:12 -07001570 addView(layout, new PagedView.LayoutParams(LayoutParams.MATCH_PARENT,
Adam Cohen0cd3b642011-10-14 14:58:00 -07001571 LayoutParams.MATCH_PARENT));
Winson Chung875de7e2011-06-28 14:25:17 -07001572 }
1573
Adam Cohen0cd3b642011-10-14 14:58:00 -07001574 for (int i = 0; i < mNumAppsPages; ++i) {
1575 PagedViewCellLayout layout = new PagedViewCellLayout(context);
1576 setupPage(layout);
1577 addView(layout);
Winson Chung785d2eb2011-04-14 16:08:02 -07001578 }
1579 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001580
Winson Chung785d2eb2011-04-14 16:08:02 -07001581 @Override
Winson Chungf314b0e2011-08-16 11:54:27 -07001582 public void syncPageItems(int page, boolean immediate) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07001583 if (page < mNumAppsPages) {
Winson Chungf314b0e2011-08-16 11:54:27 -07001584 syncAppsPageItems(page, immediate);
Adam Cohen0cd3b642011-10-14 14:58:00 -07001585 } else {
Michael Jurka39e5d172012-03-12 18:36:12 -07001586 syncWidgetPageItems(page, immediate);
Winson Chung785d2eb2011-04-14 16:08:02 -07001587 }
1588 }
1589
Adam Cohen22f823d2011-09-01 17:22:18 -07001590 // We want our pages to be z-ordered such that the further a page is to the left, the higher
1591 // it is in the z-order. This is important to insure touch events are handled correctly.
1592 View getPageAt(int index) {
Michael Jurka39e5d172012-03-12 18:36:12 -07001593 return getChildAt(indexToPage(index));
Adam Cohen22f823d2011-09-01 17:22:18 -07001594 }
1595
Adam Cohenae4f1552011-10-20 00:15:42 -07001596 @Override
1597 protected int indexToPage(int index) {
1598 return getChildCount() - index - 1;
1599 }
1600
Adam Cohen22f823d2011-09-01 17:22:18 -07001601 // In apps customize, we have a scrolling effect which emulates pulling cards off of a stack.
1602 @Override
1603 protected void screenScrolled(int screenCenter) {
1604 super.screenScrolled(screenCenter);
Adam Cohen22f823d2011-09-01 17:22:18 -07001605
1606 for (int i = 0; i < getChildCount(); i++) {
1607 View v = getPageAt(i);
1608 if (v != null) {
Adam Cohenb5ba0972011-09-07 18:02:31 -07001609 float scrollProgress = getScrollProgress(screenCenter, v, i);
Adam Cohen22f823d2011-09-01 17:22:18 -07001610
1611 float interpolatedProgress =
1612 mZInterpolator.getInterpolation(Math.abs(Math.min(scrollProgress, 0)));
1613 float scale = (1 - interpolatedProgress) +
1614 interpolatedProgress * TRANSITION_SCALE_FACTOR;
1615 float translationX = Math.min(0, scrollProgress) * v.getMeasuredWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001616
Adam Cohen2591f6a2011-10-25 14:36:40 -07001617 float alpha;
1618
Winson Chungd167e2a2012-04-26 13:13:01 -07001619 if (scrollProgress < 0) {
Adam Cohen2591f6a2011-10-25 14:36:40 -07001620 alpha = scrollProgress < 0 ? mAlphaInterpolator.getInterpolation(
Adam Cohenb5ba0972011-09-07 18:02:31 -07001621 1 - Math.abs(scrollProgress)) : 1.0f;
Adam Cohen2591f6a2011-10-25 14:36:40 -07001622 } else {
1623 // On large screens we need to fade the page as it nears its leftmost position
1624 alpha = mLeftScreenAlphaInterpolator.getInterpolation(1 - scrollProgress);
1625 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001626
1627 v.setCameraDistance(mDensity * CAMERA_DISTANCE);
1628 int pageWidth = v.getMeasuredWidth();
1629 int pageHeight = v.getMeasuredHeight();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001630
1631 if (PERFORM_OVERSCROLL_ROTATION) {
1632 if (i == 0 && scrollProgress < 0) {
1633 // Overscroll to the left
1634 v.setPivotX(TRANSITION_PIVOT * pageWidth);
1635 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1636 scale = 1.0f;
1637 alpha = 1.0f;
1638 // On the first page, we don't want the page to have any lateral motion
Adam Cohenebea84d2011-11-09 17:20:41 -08001639 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001640 } else if (i == getChildCount() - 1 && scrollProgress > 0) {
1641 // Overscroll to the right
1642 v.setPivotX((1 - TRANSITION_PIVOT) * pageWidth);
1643 v.setRotationY(-TRANSITION_MAX_ROTATION * scrollProgress);
1644 scale = 1.0f;
1645 alpha = 1.0f;
1646 // On the last page, we don't want the page to have any lateral motion.
Adam Cohenebea84d2011-11-09 17:20:41 -08001647 translationX = 0;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001648 } else {
1649 v.setPivotY(pageHeight / 2.0f);
1650 v.setPivotX(pageWidth / 2.0f);
1651 v.setRotationY(0f);
1652 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001653 }
1654
1655 v.setTranslationX(translationX);
1656 v.setScaleX(scale);
1657 v.setScaleY(scale);
1658 v.setAlpha(alpha);
Adam Cohen4e844012011-11-09 13:48:04 -08001659
1660 // If the view has 0 alpha, we set it to be invisible so as to prevent
1661 // it from accepting touches
Michael Jurka8b805b12012-04-18 14:23:14 -07001662 if (alpha == 0) {
Adam Cohen4e844012011-11-09 13:48:04 -08001663 v.setVisibility(INVISIBLE);
1664 } else if (v.getVisibility() != VISIBLE) {
1665 v.setVisibility(VISIBLE);
1666 }
Adam Cohen22f823d2011-09-01 17:22:18 -07001667 }
1668 }
1669 }
1670
1671 protected void overScroll(float amount) {
Adam Cohencff6af82011-09-13 14:51:53 -07001672 acceleratedOverScroll(amount);
Adam Cohen22f823d2011-09-01 17:22:18 -07001673 }
1674
Winson Chung785d2eb2011-04-14 16:08:02 -07001675 /**
1676 * Used by the parent to get the content width to set the tab bar to
1677 * @return
1678 */
1679 public int getPageContentWidth() {
1680 return mContentWidth;
1681 }
1682
Winson Chungb26f3d62011-06-02 10:49:29 -07001683 @Override
Winson Chungb26f3d62011-06-02 10:49:29 -07001684 protected void onPageEndMoving() {
Winson Chungb26f3d62011-06-02 10:49:29 -07001685 super.onPageEndMoving();
Michael Jurka5e368ff2012-05-14 23:13:15 -07001686 mForceDrawAllChildrenNextFrame = true;
Winson Chung5afbf7b2011-07-25 11:53:08 -07001687 // We reset the save index when we change pages so that it will be recalculated on next
1688 // rotation
1689 mSaveInstanceStateItemIndex = -1;
Winson Chungb26f3d62011-06-02 10:49:29 -07001690 }
1691
Winson Chung785d2eb2011-04-14 16:08:02 -07001692 /*
1693 * AllAppsView implementation
1694 */
1695 @Override
1696 public void setup(Launcher launcher, DragController dragController) {
1697 mLauncher = launcher;
1698 mDragController = dragController;
1699 }
1700 @Override
1701 public void zoom(float zoom, boolean animate) {
1702 // TODO-APPS_CUSTOMIZE: Call back to mLauncher.zoomed()
1703 }
1704 @Override
1705 public boolean isVisible() {
1706 return (getVisibility() == VISIBLE);
1707 }
1708 @Override
1709 public boolean isAnimating() {
1710 return false;
1711 }
Winson Chung9802ac92012-06-08 16:01:58 -07001712
1713 /**
1714 * We should call thise method whenever the core data changes (mApps, mWidgets) so that we can
1715 * appropriately determine when to invalidate the PagedView page data. In cases where the data
1716 * has yet to be set, we can requestLayout() and wait for onDataReady() to be called in the
1717 * next onMeasure() pass, which will trigger an invalidatePageData() itself.
1718 */
1719 private void invalidateOnDataChange() {
1720 if (!isDataReady()) {
1721 // The next layout pass will trigger data-ready if both widgets and apps are set, so
1722 // request a layout to trigger the page data when ready.
1723 requestLayout();
1724 } else {
1725 cancelAllTasks();
1726 invalidatePageData();
1727 }
1728 }
1729
Winson Chung785d2eb2011-04-14 16:08:02 -07001730 @Override
1731 public void setApps(ArrayList<ApplicationInfo> list) {
1732 mApps = list;
1733 Collections.sort(mApps, LauncherModel.APP_NAME_COMPARATOR);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001734 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001735 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001736 }
1737 private void addAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1738 // We add it in place, in alphabetical order
1739 int count = list.size();
1740 for (int i = 0; i < count; ++i) {
1741 ApplicationInfo info = list.get(i);
1742 int index = Collections.binarySearch(mApps, info, LauncherModel.APP_NAME_COMPARATOR);
1743 if (index < 0) {
1744 mApps.add(-(index + 1), info);
1745 }
1746 }
1747 }
1748 @Override
1749 public void addApps(ArrayList<ApplicationInfo> list) {
1750 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001751 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001752 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001753 }
1754 private int findAppByComponent(List<ApplicationInfo> list, ApplicationInfo item) {
1755 ComponentName removeComponent = item.intent.getComponent();
1756 int length = list.size();
1757 for (int i = 0; i < length; ++i) {
1758 ApplicationInfo info = list.get(i);
1759 if (info.intent.getComponent().equals(removeComponent)) {
1760 return i;
1761 }
1762 }
1763 return -1;
1764 }
1765 private void removeAppsWithoutInvalidate(ArrayList<ApplicationInfo> list) {
1766 // loop through all the apps and remove apps that have the same component
1767 int length = list.size();
1768 for (int i = 0; i < length; ++i) {
1769 ApplicationInfo info = list.get(i);
1770 int removeIndex = findAppByComponent(mApps, info);
1771 if (removeIndex > -1) {
1772 mApps.remove(removeIndex);
Winson Chung785d2eb2011-04-14 16:08:02 -07001773 }
1774 }
1775 }
1776 @Override
1777 public void removeApps(ArrayList<ApplicationInfo> list) {
1778 removeAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001779 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001780 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001781 }
1782 @Override
1783 public void updateApps(ArrayList<ApplicationInfo> list) {
1784 // We remove and re-add the updated applications list because it's properties may have
1785 // changed (ie. the title), and this will ensure that the items will be in their proper
1786 // place in the list.
1787 removeAppsWithoutInvalidate(list);
1788 addAppsWithoutInvalidate(list);
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001789 updatePageCounts();
Winson Chung9802ac92012-06-08 16:01:58 -07001790 invalidateOnDataChange();
Winson Chung785d2eb2011-04-14 16:08:02 -07001791 }
Michael Jurka35aa14d2011-07-07 17:01:08 -07001792
Winson Chung785d2eb2011-04-14 16:08:02 -07001793 @Override
1794 public void reset() {
Winson Chung649668f2012-01-10 13:07:16 -08001795 // If we have reset, then we should not continue to restore the previous state
1796 mSaveInstanceStateItemIndex = -1;
1797
Adam Cohenb64d36e2011-10-17 21:48:02 -07001798 AppsCustomizeTabHost tabHost = getTabHost();
1799 String tag = tabHost.getCurrentTabTag();
Winson Chung6a8103c2011-10-21 11:08:32 -07001800 if (tag != null) {
1801 if (!tag.equals(tabHost.getTabTagForContentType(ContentType.Applications))) {
1802 tabHost.setCurrentTabFromContent(ContentType.Applications);
1803 }
Adam Cohenb64d36e2011-10-17 21:48:02 -07001804 }
Winson Chung649668f2012-01-10 13:07:16 -08001805
Adam Cohenb64d36e2011-10-17 21:48:02 -07001806 if (mCurrentPage != 0) {
1807 invalidatePageData(0);
1808 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001809 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001810
1811 private AppsCustomizeTabHost getTabHost() {
1812 return (AppsCustomizeTabHost) mLauncher.findViewById(R.id.apps_customize_pane);
1813 }
1814
Winson Chung785d2eb2011-04-14 16:08:02 -07001815 @Override
1816 public void dumpState() {
1817 // TODO: Dump information related to current list of Applications, Widgets, etc.
Adam Cohen0e56cc92012-05-11 15:57:05 -07001818 ApplicationInfo.dumpApplicationInfoList(TAG, "mApps", mApps);
1819 dumpAppWidgetProviderInfoList(TAG, "mWidgets", mWidgets);
Winson Chung785d2eb2011-04-14 16:08:02 -07001820 }
Adam Cohen4e844012011-11-09 13:48:04 -08001821
Winson Chung785d2eb2011-04-14 16:08:02 -07001822 private void dumpAppWidgetProviderInfoList(String tag, String label,
Winson Chungd2945262011-06-24 15:22:14 -07001823 ArrayList<Object> list) {
Winson Chung785d2eb2011-04-14 16:08:02 -07001824 Log.d(tag, label + " size=" + list.size());
Winson Chung1ed747a2011-05-03 16:18:34 -07001825 for (Object i: list) {
1826 if (i instanceof AppWidgetProviderInfo) {
1827 AppWidgetProviderInfo info = (AppWidgetProviderInfo) i;
1828 Log.d(tag, " label=\"" + info.label + "\" previewImage=" + info.previewImage
1829 + " resizeMode=" + info.resizeMode + " configure=" + info.configure
1830 + " initialLayout=" + info.initialLayout
1831 + " minWidth=" + info.minWidth + " minHeight=" + info.minHeight);
1832 } else if (i instanceof ResolveInfo) {
1833 ResolveInfo info = (ResolveInfo) i;
1834 Log.d(tag, " label=\"" + info.loadLabel(mPackageManager) + "\" icon="
1835 + info.icon);
1836 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001837 }
1838 }
Adam Cohen4e844012011-11-09 13:48:04 -08001839
Winson Chung785d2eb2011-04-14 16:08:02 -07001840 @Override
1841 public void surrender() {
1842 // TODO: If we are in the middle of any process (ie. for holographic outlines, etc) we
1843 // should stop this now.
Winson Chung4b0ed8c2011-10-19 15:24:49 -07001844
1845 // Stop all background tasks
1846 cancelAllTasks();
Winson Chung785d2eb2011-04-14 16:08:02 -07001847 }
Winson Chung007c6982011-06-14 13:27:53 -07001848
Winson Chunge4e50662012-01-23 14:45:13 -08001849 @Override
1850 public void iconPressed(PagedViewIcon icon) {
1851 // Reset the previously pressed icon and store a reference to the pressed icon so that
1852 // we can reset it on return to Launcher (in Launcher.onResume())
1853 if (mPressedIcon != null) {
1854 mPressedIcon.resetDrawableState();
1855 }
1856 mPressedIcon = icon;
1857 }
1858
1859 public void resetDrawableState() {
1860 if (mPressedIcon != null) {
1861 mPressedIcon.resetDrawableState();
1862 mPressedIcon = null;
1863 }
1864 }
Winson Chung68e4c642011-11-10 15:48:25 -08001865
Winson Chungb44b5242011-06-13 11:32:14 -07001866 /*
1867 * We load an extra page on each side to prevent flashes from scrolling and loading of the
1868 * widget previews in the background with the AsyncTasks.
1869 */
Winson Chung68e4c642011-11-10 15:48:25 -08001870 final static int sLookBehindPageCount = 2;
1871 final static int sLookAheadPageCount = 2;
Winson Chungb44b5242011-06-13 11:32:14 -07001872 protected int getAssociatedLowerPageBound(int page) {
Winson Chung68e4c642011-11-10 15:48:25 -08001873 final int count = getChildCount();
1874 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1875 int windowMinIndex = Math.max(Math.min(page - sLookBehindPageCount, count - windowSize), 0);
1876 return windowMinIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001877 }
1878 protected int getAssociatedUpperPageBound(int page) {
1879 final int count = getChildCount();
Winson Chung68e4c642011-11-10 15:48:25 -08001880 int windowSize = Math.min(count, sLookBehindPageCount + sLookAheadPageCount + 1);
1881 int windowMaxIndex = Math.min(Math.max(page + sLookAheadPageCount, windowSize - 1),
1882 count - 1);
1883 return windowMaxIndex;
Winson Chungb44b5242011-06-13 11:32:14 -07001884 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07001885
1886 @Override
1887 protected String getCurrentPageDescription() {
1888 int page = (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
1889 int stringId = R.string.default_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001890 int count = 0;
1891
Adam Cohen0cd3b642011-10-14 14:58:00 -07001892 if (page < mNumAppsPages) {
Winson Chung6a0f57d2011-06-29 20:10:49 -07001893 stringId = R.string.apps_customize_apps_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001894 count = mNumAppsPages;
Adam Cohen0cd3b642011-10-14 14:58:00 -07001895 } else {
1896 page -= mNumAppsPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001897 stringId = R.string.apps_customize_widgets_scroll_format;
Adam Cohend3357b12011-10-18 14:58:11 -07001898 count = mNumWidgetPages;
Winson Chung6a0f57d2011-06-29 20:10:49 -07001899 }
Adam Cohen0cd3b642011-10-14 14:58:00 -07001900
Michael Jurka8b805b12012-04-18 14:23:14 -07001901 return String.format(getContext().getString(stringId), page + 1, count);
Winson Chung6a0f57d2011-06-29 20:10:49 -07001902 }
Winson Chung785d2eb2011-04-14 16:08:02 -07001903}