Launcher.java revision 9e6a0a20d40675ef98c7fdb8892cf34b90152f7a
1
2/*
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.launcher3;
19
20import android.accounts.Account;
21import android.accounts.AccountManager;
22import android.animation.Animator;
23import android.animation.AnimatorListenerAdapter;
24import android.animation.AnimatorSet;
25import android.animation.ObjectAnimator;
26import android.animation.PropertyValuesHolder;
27import android.animation.ValueAnimator;
28import android.animation.ValueAnimator.AnimatorUpdateListener;
29import android.app.Activity;
30import android.app.ActivityManager;
31import android.app.ActivityOptions;
32import android.app.SearchManager;
33import android.appwidget.AppWidgetHostView;
34import android.appwidget.AppWidgetManager;
35import android.appwidget.AppWidgetProviderInfo;
36import android.content.ActivityNotFoundException;
37import android.content.BroadcastReceiver;
38import android.content.ComponentCallbacks2;
39import android.content.ComponentName;
40import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.SharedPreferences;
45import android.content.pm.ActivityInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.database.ContentObserver;
51import android.graphics.Bitmap;
52import android.graphics.Canvas;
53import android.graphics.Point;
54import android.graphics.PorterDuff;
55import android.graphics.Rect;
56import android.graphics.drawable.Drawable;
57import android.net.Uri;
58import android.os.AsyncTask;
59import android.os.Bundle;
60import android.os.Environment;
61import android.os.Handler;
62import android.os.Message;
63import android.os.StrictMode;
64import android.os.SystemClock;
65import android.provider.Settings;
66import android.speech.RecognizerIntent;
67import android.text.Selection;
68import android.text.SpannableStringBuilder;
69import android.text.TextUtils;
70import android.text.method.TextKeyListener;
71import android.util.DisplayMetrics;
72import android.util.Log;
73import android.view.Display;
74import android.view.Gravity;
75import android.view.HapticFeedbackConstants;
76import android.view.KeyEvent;
77import android.view.LayoutInflater;
78import android.view.Menu;
79import android.view.MenuItem;
80import android.view.MotionEvent;
81import android.view.Surface;
82import android.view.View;
83import android.view.View.OnClickListener;
84import android.view.View.OnLongClickListener;
85import android.view.ViewGroup;
86import android.view.ViewTreeObserver;
87import android.view.ViewTreeObserver.OnGlobalLayoutListener;
88import android.view.WindowManager;
89import android.view.accessibility.AccessibilityEvent;
90import android.view.animation.AccelerateDecelerateInterpolator;
91import android.view.animation.AccelerateInterpolator;
92import android.view.animation.DecelerateInterpolator;
93import android.view.inputmethod.InputMethodManager;
94import android.widget.Advanceable;
95import android.widget.FrameLayout;
96import android.widget.ImageView;
97import android.widget.TextView;
98import android.widget.Toast;
99
100import com.android.launcher3.DropTarget.DragObject;
101
102import java.io.DataInputStream;
103import java.io.DataOutputStream;
104import java.io.FileDescriptor;
105import java.io.FileNotFoundException;
106import java.io.IOException;
107import java.io.PrintWriter;
108import java.util.ArrayList;
109import java.util.Collection;
110import java.util.HashMap;
111import java.util.List;
112
113/**
114 * Default launcher application.
115 */
116public class Launcher extends Activity
117        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
118                   View.OnTouchListener {
119    static final String TAG = "Launcher";
120    static final boolean LOGD = false;
121
122    static final boolean PROFILE_STARTUP = false;
123    static final boolean DEBUG_WIDGETS = false;
124    static final boolean DEBUG_STRICT_MODE = false;
125    static final boolean DEBUG_RESUME_TIME = false;
126
127    private static final int MENU_GROUP_WALLPAPER = 1;
128    private static final int MENU_WALLPAPER_SETTINGS = Menu.FIRST + 1;
129    private static final int MENU_MANAGE_APPS = MENU_WALLPAPER_SETTINGS + 1;
130    private static final int MENU_SYSTEM_SETTINGS = MENU_MANAGE_APPS + 1;
131    private static final int MENU_HELP = MENU_SYSTEM_SETTINGS + 1;
132
133    private static final int REQUEST_CREATE_SHORTCUT = 1;
134    private static final int REQUEST_CREATE_APPWIDGET = 5;
135    private static final int REQUEST_PICK_APPLICATION = 6;
136    private static final int REQUEST_PICK_SHORTCUT = 7;
137    private static final int REQUEST_PICK_APPWIDGET = 9;
138    private static final int REQUEST_PICK_WALLPAPER = 10;
139
140    private static final int REQUEST_BIND_APPWIDGET = 11;
141
142    /**
143     * IntentStarter uses request codes starting with this. This must be greater than all activity
144     * request codes used internally.
145     */
146    protected static final int REQUEST_LAST = 100;
147
148    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
149
150    static final int SCREEN_COUNT = 5;
151    static final int DEFAULT_SCREEN = 2;
152
153    private static final String PREFERENCES = "launcher.preferences";
154    // To turn on these properties, type
155    // adb shell setprop log.tag.PROPERTY_NAME [VERBOSE | SUPPRESS]
156    static final String FORCE_ENABLE_ROTATION_PROPERTY = "launcher_force_rotate";
157    static final String DUMP_STATE_PROPERTY = "launcher_dump_state";
158
159    // The Intent extra that defines whether to ignore the launch animation
160    static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
161            "com.android.launcher3.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
162
163    // Type: int
164    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
165    // Type: int
166    private static final String RUNTIME_STATE = "launcher.state";
167    // Type: int
168    private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
169    // Type: int
170    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
171    // Type: int
172    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
173    // Type: int
174    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
175    // Type: boolean
176    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
177    // Type: long
178    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
179    // Type: int
180    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_span_x";
181    // Type: int
182    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_span_y";
183    // Type: parcelable
184    private static final String RUNTIME_STATE_PENDING_ADD_WIDGET_INFO = "launcher.add_widget_info";
185
186    private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
187    private static final String TOOLBAR_SEARCH_ICON_METADATA_NAME =
188            "com.android.launcher.toolbar_search_icon";
189    private static final String TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME =
190            "com.android.launcher.toolbar_voice_search_icon";
191
192    public static final String SHOW_WEIGHT_WATCHER = "debug.show_mem";
193    public static final boolean SHOW_WEIGHT_WATCHER_DEFAULT = false;
194
195    /** The different states that Launcher can be in. */
196    private enum State { NONE, WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
197    private State mState = State.WORKSPACE;
198    private AnimatorSet mStateAnimation;
199
200    static final int APPWIDGET_HOST_ID = 1024;
201    private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
202    private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
203    private static final int SHOW_CLING_DURATION = 550;
204    private static final int DISMISS_CLING_DURATION = 250;
205
206    private static final Object sLock = new Object();
207    private static int sScreen = DEFAULT_SCREEN;
208
209    // How long to wait before the new-shortcut animation automatically pans the workspace
210    private static int NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS = 10;
211    private static int NEW_APPS_ANIMATION_DELAY = 500;
212
213    private final BroadcastReceiver mCloseSystemDialogsReceiver
214            = new CloseSystemDialogsIntentReceiver();
215    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
216
217    private LayoutInflater mInflater;
218
219    private Workspace mWorkspace;
220    private View mLauncherView;
221    private DragLayer mDragLayer;
222    private DragController mDragController;
223    private View mWeightWatcher;
224
225    private AppWidgetManager mAppWidgetManager;
226    private LauncherAppWidgetHost mAppWidgetHost;
227
228    private ItemInfo mPendingAddInfo = new ItemInfo();
229    private AppWidgetProviderInfo mPendingAddWidgetInfo;
230
231    private int[] mTmpAddItemCellCoordinates = new int[2];
232
233    private FolderInfo mFolderInfo;
234
235    private Hotseat mHotseat;
236    private View mOverviewPanel;
237
238    private View mAllAppsButton;
239
240    private SearchDropTargetBar mSearchDropTargetBar;
241    private AppsCustomizeTabHost mAppsCustomizeTabHost;
242    private AppsCustomizePagedView mAppsCustomizeContent;
243    private boolean mAutoAdvanceRunning = false;
244    private View mQsbBar;
245
246    private Bundle mSavedState;
247    // We set the state in both onCreate and then onNewIntent in some cases, which causes both
248    // scroll issues (because the workspace may not have been measured yet) and extra work.
249    // Instead, just save the state that we need to restore Launcher to, and commit it in onResume.
250    private State mOnResumeState = State.NONE;
251
252    private SpannableStringBuilder mDefaultKeySsb = null;
253
254    private boolean mWorkspaceLoading = true;
255
256    private boolean mPaused = true;
257    private boolean mRestoring;
258    private boolean mWaitingForResult;
259    private boolean mOnResumeNeedsLoad;
260
261    private ArrayList<Runnable> mBindOnResumeCallbacks = new ArrayList<Runnable>();
262    private ArrayList<Runnable> mOnResumeCallbacks = new ArrayList<Runnable>();
263
264    // Keep track of whether the user has left launcher
265    private static boolean sPausedFromUserAction = false;
266
267    private Bundle mSavedInstanceState;
268
269    private LauncherModel mModel;
270    private IconCache mIconCache;
271    private boolean mUserPresent = true;
272    private boolean mVisible = false;
273    private boolean mAttached = false;
274    private static final boolean DISABLE_CLINGS = true;
275
276    private static LocaleConfiguration sLocaleConfiguration = null;
277
278    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
279
280    private Intent mAppMarketIntent = null;
281
282    // Related to the auto-advancing of widgets
283    private final int ADVANCE_MSG = 1;
284    private final int mAdvanceInterval = 20000;
285    private final int mAdvanceStagger = 250;
286    private long mAutoAdvanceSentTime;
287    private long mAutoAdvanceTimeLeft = -1;
288    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
289        new HashMap<View, AppWidgetProviderInfo>();
290
291    // Determines how long to wait after a rotation before restoring the screen orientation to
292    // match the sensor state.
293    private final int mRestoreScreenOrientationDelay = 500;
294
295    // External icons saved in case of resource changes, orientation, etc.
296    private static Drawable.ConstantState[] sGlobalSearchIcon = new Drawable.ConstantState[2];
297    private static Drawable.ConstantState[] sVoiceSearchIcon = new Drawable.ConstantState[2];
298    private static Drawable.ConstantState[] sAppMarketIcon = new Drawable.ConstantState[2];
299
300    private Drawable mWorkspaceBackgroundDrawable;
301
302    private final ArrayList<Integer> mSynchronouslyBoundPages = new ArrayList<Integer>();
303
304    static final ArrayList<String> sDumpLogs = new ArrayList<String>();
305
306    // We only want to get the SharedPreferences once since it does an FS stat each time we get
307    // it from the context.
308    private SharedPreferences mSharedPrefs;
309
310    private static ArrayList<ComponentName> mIntentsOnWorkspaceFromUpgradePath = null;
311
312    // Holds the page that we need to animate to, and the icon views that we need to animate up
313    // when we scroll to that page on resume.
314    private ImageView mFolderIconImageView;
315    private Bitmap mFolderIconBitmap;
316    private Canvas mFolderIconCanvas;
317    private Rect mRectForFolderAnimation = new Rect();
318
319    private BubbleTextView mWaitingForResume;
320
321    private HideFromAccessibilityHelper mHideFromAccessibilityHelper
322        = new HideFromAccessibilityHelper();
323
324    private Runnable mBuildLayersRunnable = new Runnable() {
325        public void run() {
326            if (mWorkspace != null) {
327                mWorkspace.buildPageHardwareLayers();
328            }
329        }
330    };
331
332    private static ArrayList<PendingAddArguments> sPendingAddList
333            = new ArrayList<PendingAddArguments>();
334
335    private static boolean sForceEnableRotation = isPropertyEnabled(FORCE_ENABLE_ROTATION_PROPERTY);
336
337    private static class PendingAddArguments {
338        int requestCode;
339        Intent intent;
340        long container;
341        long screenId;
342        int cellX;
343        int cellY;
344    }
345
346    private Stats mStats;
347
348    private static boolean isPropertyEnabled(String propertyName) {
349        return Log.isLoggable(propertyName, Log.VERBOSE);
350    }
351
352    @Override
353    protected void onCreate(Bundle savedInstanceState) {
354        if (DEBUG_STRICT_MODE) {
355            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
356                    .detectDiskReads()
357                    .detectDiskWrites()
358                    .detectNetwork()   // or .detectAll() for all detectable problems
359                    .penaltyLog()
360                    .build());
361            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
362                    .detectLeakedSqlLiteObjects()
363                    .detectLeakedClosableObjects()
364                    .penaltyLog()
365                    .penaltyDeath()
366                    .build());
367        }
368
369        super.onCreate(savedInstanceState);
370
371        LauncherAppState.setApplicationContext(getApplicationContext());
372        LauncherAppState app = LauncherAppState.getInstance();
373
374        // Determine the dynamic grid properties
375        Point smallestSize = new Point();
376        Point largestSize = new Point();
377        Point realSize = new Point();
378        Display display = getWindowManager().getDefaultDisplay();
379        display.getCurrentSizeRange(smallestSize, largestSize);
380        display.getRealSize(realSize);
381        DisplayMetrics dm = new DisplayMetrics();
382        display.getMetrics(dm);
383        // Lazy-initialize the dynamic grid
384        DeviceProfile grid = app.initDynamicGrid(this,
385                Math.min(smallestSize.x, smallestSize.y),
386                Math.min(largestSize.x, largestSize.y),
387                realSize.x, realSize.y,
388                dm.widthPixels, dm.heightPixels);
389
390        // the LauncherApplication should call this, but in case of Instrumentation it might not be present yet
391        mSharedPrefs = getSharedPreferences(LauncherAppState.getSharedPreferencesKey(),
392                Context.MODE_PRIVATE);
393        mModel = app.setLauncher(this);
394        mIconCache = app.getIconCache();
395        mDragController = new DragController(this);
396        mInflater = getLayoutInflater();
397
398        mStats = new Stats(this);
399
400        mAppWidgetManager = AppWidgetManager.getInstance(this);
401        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
402        mAppWidgetHost.startListening();
403
404        // If we are getting an onCreate, we can actually preempt onResume and unset mPaused here,
405        // this also ensures that any synchronous binding below doesn't re-trigger another
406        // LauncherModel load.
407        mPaused = false;
408
409        if (PROFILE_STARTUP) {
410            android.os.Debug.startMethodTracing(
411                    Environment.getExternalStorageDirectory() + "/launcher");
412        }
413
414        checkForLocaleChange();
415        setContentView(R.layout.launcher);
416        setupViews();
417        grid.layout(this);
418        showFirstRunWorkspaceCling();
419
420        registerContentObservers();
421
422        lockAllApps();
423
424        mSavedState = savedInstanceState;
425        restoreState(mSavedState);
426
427        // Update customization drawer _after_ restoring the states
428        if (mAppsCustomizeContent != null) {
429            mAppsCustomizeContent.onPackagesUpdated(
430                LauncherModel.getSortedWidgetsAndShortcuts(this));
431        }
432
433        if (PROFILE_STARTUP) {
434            android.os.Debug.stopMethodTracing();
435        }
436
437        if (!mRestoring) {
438            if (sPausedFromUserAction) {
439                // If the user leaves launcher, then we should just load items asynchronously when
440                // they return.
441                mModel.startLoader(true, -1);
442            } else {
443                // We only load the page synchronously if the user rotates (or triggers a
444                // configuration change) while launcher is in the foreground
445                mModel.startLoader(true, mWorkspace.getCurrentPage());
446            }
447        }
448
449        // For handling default keys
450        mDefaultKeySsb = new SpannableStringBuilder();
451        Selection.setSelection(mDefaultKeySsb, 0);
452
453        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
454        registerReceiver(mCloseSystemDialogsReceiver, filter);
455
456        updateGlobalIcons();
457
458        // On large interfaces, we want the screen to auto-rotate based on the current orientation
459        unlockScreenOrientation(true);
460    }
461
462    protected void onUserLeaveHint() {
463        super.onUserLeaveHint();
464        sPausedFromUserAction = true;
465    }
466
467    /** To be overriden by subclasses to hint to Launcher that we have custom content */
468    protected boolean hasCustomContentToLeft() {
469        return false;
470    }
471
472    private void updateGlobalIcons() {
473        boolean searchVisible = false;
474        boolean voiceVisible = false;
475        // If we have a saved version of these external icons, we load them up immediately
476        int coi = getCurrentOrientationIndexForGlobalIcons();
477        if (sGlobalSearchIcon[coi] == null || sVoiceSearchIcon[coi] == null ||
478                sAppMarketIcon[coi] == null) {
479            updateAppMarketIcon();
480            searchVisible = updateGlobalSearchIcon();
481            voiceVisible = updateVoiceSearchIcon(searchVisible);
482        }
483        if (sGlobalSearchIcon[coi] != null) {
484             updateGlobalSearchIcon(sGlobalSearchIcon[coi]);
485             searchVisible = true;
486        }
487        if (sVoiceSearchIcon[coi] != null) {
488            updateVoiceSearchIcon(sVoiceSearchIcon[coi]);
489            voiceVisible = true;
490        }
491        if (sAppMarketIcon[coi] != null) {
492            updateAppMarketIcon(sAppMarketIcon[coi]);
493        }
494        if (mSearchDropTargetBar != null) {
495            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
496        }
497    }
498
499    private void checkForLocaleChange() {
500        if (sLocaleConfiguration == null) {
501            new AsyncTask<Void, Void, LocaleConfiguration>() {
502                @Override
503                protected LocaleConfiguration doInBackground(Void... unused) {
504                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
505                    readConfiguration(Launcher.this, localeConfiguration);
506                    return localeConfiguration;
507                }
508
509                @Override
510                protected void onPostExecute(LocaleConfiguration result) {
511                    sLocaleConfiguration = result;
512                    checkForLocaleChange();  // recursive, but now with a locale configuration
513                }
514            }.execute();
515            return;
516        }
517
518        final Configuration configuration = getResources().getConfiguration();
519
520        final String previousLocale = sLocaleConfiguration.locale;
521        final String locale = configuration.locale.toString();
522
523        final int previousMcc = sLocaleConfiguration.mcc;
524        final int mcc = configuration.mcc;
525
526        final int previousMnc = sLocaleConfiguration.mnc;
527        final int mnc = configuration.mnc;
528
529        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
530
531        if (localeChanged) {
532            sLocaleConfiguration.locale = locale;
533            sLocaleConfiguration.mcc = mcc;
534            sLocaleConfiguration.mnc = mnc;
535
536            mIconCache.flush();
537
538            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
539            new Thread("WriteLocaleConfiguration") {
540                @Override
541                public void run() {
542                    writeConfiguration(Launcher.this, localeConfiguration);
543                }
544            }.start();
545        }
546    }
547
548    private static class LocaleConfiguration {
549        public String locale;
550        public int mcc = -1;
551        public int mnc = -1;
552    }
553
554    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
555        DataInputStream in = null;
556        try {
557            in = new DataInputStream(context.openFileInput(PREFERENCES));
558            configuration.locale = in.readUTF();
559            configuration.mcc = in.readInt();
560            configuration.mnc = in.readInt();
561        } catch (FileNotFoundException e) {
562            // Ignore
563        } catch (IOException e) {
564            // Ignore
565        } finally {
566            if (in != null) {
567                try {
568                    in.close();
569                } catch (IOException e) {
570                    // Ignore
571                }
572            }
573        }
574    }
575
576    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
577        DataOutputStream out = null;
578        try {
579            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
580            out.writeUTF(configuration.locale);
581            out.writeInt(configuration.mcc);
582            out.writeInt(configuration.mnc);
583            out.flush();
584        } catch (FileNotFoundException e) {
585            // Ignore
586        } catch (IOException e) {
587            //noinspection ResultOfMethodCallIgnored
588            context.getFileStreamPath(PREFERENCES).delete();
589        } finally {
590            if (out != null) {
591                try {
592                    out.close();
593                } catch (IOException e) {
594                    // Ignore
595                }
596            }
597        }
598    }
599
600    public LayoutInflater getInflater() {
601        return mInflater;
602    }
603
604    public DragLayer getDragLayer() {
605        return mDragLayer;
606    }
607
608    boolean isDraggingEnabled() {
609        // We prevent dragging when we are loading the workspace as it is possible to pick up a view
610        // that is subsequently removed from the workspace in startBinding().
611        return !mModel.isLoadingWorkspace();
612    }
613
614    static int getScreen() {
615        synchronized (sLock) {
616            return sScreen;
617        }
618    }
619
620    static void setScreen(int screen) {
621        synchronized (sLock) {
622            sScreen = screen;
623        }
624    }
625
626    /**
627     * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
628     * a configuration step, this allows the proper animations to run after other transitions.
629     */
630    private boolean completeAdd(PendingAddArguments args) {
631        boolean result = false;
632        switch (args.requestCode) {
633            case REQUEST_PICK_APPLICATION:
634                completeAddApplication(args.intent, args.container, args.screenId, args.cellX,
635                        args.cellY);
636                break;
637            case REQUEST_PICK_SHORTCUT:
638                processShortcut(args.intent);
639                break;
640            case REQUEST_CREATE_SHORTCUT:
641                completeAddShortcut(args.intent, args.container, args.screenId, args.cellX,
642                        args.cellY);
643                result = true;
644                break;
645            case REQUEST_CREATE_APPWIDGET:
646                int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
647                completeAddAppWidget(appWidgetId, args.container, args.screenId, null, null);
648                result = true;
649                break;
650            case REQUEST_PICK_WALLPAPER:
651                // We just wanted the activity result here so we can clear mWaitingForResult
652                break;
653        }
654        // Before adding this resetAddInfo(), after a shortcut was added to a workspace screen,
655        // if you turned the screen off and then back while in All Apps, Launcher would not
656        // return to the workspace. Clearing mAddInfo.container here fixes this issue
657        resetAddInfo();
658        return result;
659    }
660
661    @Override
662    protected void onActivityResult(
663            final int requestCode, final int resultCode, final Intent data) {
664        // Reset the startActivity waiting flag
665        mWaitingForResult = false;
666
667        if (requestCode == REQUEST_BIND_APPWIDGET) {
668            int appWidgetId = data != null ?
669                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
670            if (resultCode == RESULT_CANCELED) {
671                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
672            } else if (resultCode == RESULT_OK) {
673                addAppWidgetImpl(appWidgetId, mPendingAddInfo, null, mPendingAddWidgetInfo);
674            }
675            return;
676        }
677        boolean delayExitSpringLoadedMode = false;
678        boolean isWidgetDrop = (requestCode == REQUEST_PICK_APPWIDGET ||
679                requestCode == REQUEST_CREATE_APPWIDGET);
680
681        // We have special handling for widgets
682        if (isWidgetDrop) {
683            int appWidgetId = data != null ?
684                    data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1;
685            if (appWidgetId < 0) {
686                Log.e(TAG, "Error: appWidgetId (EXTRA_APPWIDGET_ID) was not returned from the \\" +
687                        "widget configuration activity.");
688                completeTwoStageWidgetDrop(RESULT_CANCELED, appWidgetId);
689            } else {
690                completeTwoStageWidgetDrop(resultCode, appWidgetId);
691            }
692            return;
693        }
694
695        // The pattern used here is that a user PICKs a specific application,
696        // which, depending on the target, might need to CREATE the actual target.
697
698        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
699        // launch over to the Music app to actually CREATE_SHORTCUT.
700        if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
701            final PendingAddArguments args = new PendingAddArguments();
702            args.requestCode = requestCode;
703            args.intent = data;
704            args.container = mPendingAddInfo.container;
705            args.screenId = mPendingAddInfo.screenId;
706            args.cellX = mPendingAddInfo.cellX;
707            args.cellY = mPendingAddInfo.cellY;
708            if (isWorkspaceLocked()) {
709                sPendingAddList.add(args);
710            } else {
711                delayExitSpringLoadedMode = completeAdd(args);
712            }
713        }
714        mDragLayer.clearAnimatedView();
715        // Exit spring loaded mode if necessary after cancelling the configuration of a widget
716        exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode,
717                null);
718    }
719
720    private void completeTwoStageWidgetDrop(final int resultCode, final int appWidgetId) {
721        CellLayout cellLayout =
722                (CellLayout) mWorkspace.getScreenWithId(mPendingAddInfo.screenId);
723        Runnable onCompleteRunnable = null;
724        int animationType = 0;
725
726        AppWidgetHostView boundWidget = null;
727        if (resultCode == RESULT_OK) {
728            animationType = Workspace.COMPLETE_TWO_STAGE_WIDGET_DROP_ANIMATION;
729            final AppWidgetHostView layout = mAppWidgetHost.createView(this, appWidgetId,
730                    mPendingAddWidgetInfo);
731            boundWidget = layout;
732            onCompleteRunnable = new Runnable() {
733                @Override
734                public void run() {
735                    completeAddAppWidget(appWidgetId, mPendingAddInfo.container,
736                            mPendingAddInfo.screenId, layout, null);
737                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
738                            null);
739                }
740            };
741        } else if (resultCode == RESULT_CANCELED) {
742            animationType = Workspace.CANCEL_TWO_STAGE_WIDGET_DROP_ANIMATION;
743            onCompleteRunnable = new Runnable() {
744                @Override
745                public void run() {
746                    exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), false,
747                            null);
748                }
749            };
750        }
751        if (mDragLayer.getAnimatedView() != null) {
752            mWorkspace.animateWidgetDrop(mPendingAddInfo, cellLayout,
753                    (DragView) mDragLayer.getAnimatedView(), onCompleteRunnable,
754                    animationType, boundWidget, true);
755        } else {
756            // The animated view may be null in the case of a rotation during widget configuration
757            onCompleteRunnable.run();
758        }
759    }
760
761    @Override
762    protected void onStop() {
763        super.onStop();
764        FirstFrameAnimatorHelper.setIsVisible(false);
765    }
766
767    @Override
768    protected void onStart() {
769        super.onStart();
770        FirstFrameAnimatorHelper.setIsVisible(true);
771    }
772
773    @Override
774    protected void onResume() {
775        long startTime = 0;
776        if (DEBUG_RESUME_TIME) {
777            startTime = System.currentTimeMillis();
778            Log.v(TAG, "Launcher.onResume()");
779        }
780        super.onResume();
781
782        // Restore the previous launcher state
783        if (mOnResumeState == State.WORKSPACE) {
784            showWorkspace(false);
785        } else if (mOnResumeState == State.APPS_CUSTOMIZE) {
786            showAllApps(false);
787        }
788        mOnResumeState = State.NONE;
789
790        // Background was set to gradient in onPause(), restore to black if in all apps.
791        setWorkspaceBackground(mState == State.WORKSPACE);
792
793        // Process any items that were added while Launcher was away
794        InstallShortcutReceiver.disableAndFlushInstallQueue(this);
795
796        mPaused = false;
797        sPausedFromUserAction = false;
798        if (mRestoring || mOnResumeNeedsLoad) {
799            mWorkspaceLoading = true;
800            mModel.startLoader(true, -1);
801            mRestoring = false;
802            mOnResumeNeedsLoad = false;
803        }
804        if (mBindOnResumeCallbacks.size() > 0) {
805            // We might have postponed some bind calls until onResume (see waitUntilResume) --
806            // execute them here
807            long startTimeCallbacks = 0;
808            if (DEBUG_RESUME_TIME) {
809                startTimeCallbacks = System.currentTimeMillis();
810            }
811
812            if (mAppsCustomizeContent != null) {
813                mAppsCustomizeContent.setBulkBind(true);
814            }
815            for (int i = 0; i < mBindOnResumeCallbacks.size(); i++) {
816                mBindOnResumeCallbacks.get(i).run();
817            }
818            if (mAppsCustomizeContent != null) {
819                mAppsCustomizeContent.setBulkBind(false);
820            }
821            mBindOnResumeCallbacks.clear();
822            if (DEBUG_RESUME_TIME) {
823                Log.d(TAG, "Time spent processing callbacks in onResume: " +
824                    (System.currentTimeMillis() - startTimeCallbacks));
825            }
826        }
827        if (mOnResumeCallbacks.size() > 0) {
828            for (int i = 0; i < mOnResumeCallbacks.size(); i++) {
829                mOnResumeCallbacks.get(i).run();
830            }
831            mOnResumeCallbacks.clear();
832        }
833
834        // Reset the pressed state of icons that were locked in the press state while activities
835        // were launching
836        if (mWaitingForResume != null) {
837            // Resets the previous workspace icon press state
838            mWaitingForResume.setStayPressed(false);
839        }
840        if (mAppsCustomizeContent != null) {
841            // Resets the previous all apps icon press state
842            mAppsCustomizeContent.resetDrawableState();
843        }
844        // It is possible that widgets can receive updates while launcher is not in the foreground.
845        // Consequently, the widgets will be inflated in the orientation of the foreground activity
846        // (framework issue). On resuming, we ensure that any widgets are inflated for the current
847        // orientation.
848        getWorkspace().reinflateWidgetsIfNecessary();
849
850        // Again, as with the above scenario, it's possible that one or more of the global icons
851        // were updated in the wrong orientation.
852        updateGlobalIcons();
853        if (DEBUG_RESUME_TIME) {
854            Log.d(TAG, "Time spent in onResume: " + (System.currentTimeMillis() - startTime));
855        }
856    }
857
858    @Override
859    protected void onPause() {
860        // NOTE: We want all transitions from launcher to act as if the wallpaper were enabled
861        // to be consistent.  So re-enable the flag here, and we will re-disable it as necessary
862        // when Launcher resumes and we are still in AllApps.
863        updateWallpaperVisibility(true);
864
865        // Ensure that items added to Launcher are queued until Launcher returns
866        InstallShortcutReceiver.enableInstallQueue();
867
868        super.onPause();
869        mPaused = true;
870        mDragController.cancelDrag();
871        mDragController.resetLastGestureUpTime();
872    }
873
874    protected void onFinishBindingItems() {
875    }
876
877    QSBScroller mQsbScroller = new QSBScroller() {
878        int scrollY = 0;
879
880        @Override
881        public void setScrollY(int scroll) {
882            scrollY = scroll;
883
884            if (mWorkspace.isOnOrMovingToCustomContent()) {
885                mSearchDropTargetBar.setTranslationY(- scrollY);
886            }
887        }
888    };
889
890    public void resetQSBScroll() {
891        mSearchDropTargetBar.animate().translationY(0).start();
892    }
893
894    public interface CustomContentCallbacks {
895        // Custom content is completely shown
896        public void onShow();
897
898        // Custom content is completely hidden
899        public void onHide();
900    }
901
902    public interface QSBScroller {
903        public void setScrollY(int scrollY);
904    }
905
906    // Add a fullscreen unpadded view to the workspace to the left all other screens.
907    public QSBScroller addToCustomContentPage(View customContent) {
908        return addToCustomContentPage(customContent, null);
909    }
910
911    public QSBScroller addToCustomContentPage(View customContent,
912            CustomContentCallbacks callbacks) {
913        mWorkspace.addToCustomContentPage(customContent, callbacks);
914        return mQsbScroller;
915    }
916
917    // The custom content needs to offset its content to account for the QSB
918    public int getTopOffsetForCustomContent() {
919        return mWorkspace.getPaddingTop();
920    }
921
922    @Override
923    public Object onRetainNonConfigurationInstance() {
924        // Flag the loader to stop early before switching
925        mModel.stopLoader();
926        if (mAppsCustomizeContent != null) {
927            mAppsCustomizeContent.surrender();
928        }
929        return Boolean.TRUE;
930    }
931
932    // We can't hide the IME if it was forced open.  So don't bother
933    /*
934    @Override
935    public void onWindowFocusChanged(boolean hasFocus) {
936        super.onWindowFocusChanged(hasFocus);
937
938        if (hasFocus) {
939            final InputMethodManager inputManager = (InputMethodManager)
940                    getSystemService(Context.INPUT_METHOD_SERVICE);
941            WindowManager.LayoutParams lp = getWindow().getAttributes();
942            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
943                        android.os.Handler()) {
944                        protected void onReceiveResult(int resultCode, Bundle resultData) {
945                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
946                        }
947                    });
948            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
949        }
950    }
951    */
952
953    private boolean acceptFilter() {
954        final InputMethodManager inputManager = (InputMethodManager)
955                getSystemService(Context.INPUT_METHOD_SERVICE);
956        return !inputManager.isFullscreenMode();
957    }
958
959    @Override
960    public boolean onKeyDown(int keyCode, KeyEvent event) {
961        final int uniChar = event.getUnicodeChar();
962        final boolean handled = super.onKeyDown(keyCode, event);
963        final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
964        if (!handled && acceptFilter() && isKeyNotWhitespace) {
965            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
966                    keyCode, event);
967            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
968                // something usable has been typed - start a search
969                // the typed text will be retrieved and cleared by
970                // showSearchDialog()
971                // If there are multiple keystrokes before the search dialog takes focus,
972                // onSearchRequested() will be called for every keystroke,
973                // but it is idempotent, so it's fine.
974                return onSearchRequested();
975            }
976        }
977
978        // Eat the long press event so the keyboard doesn't come up.
979        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
980            return true;
981        }
982
983        return handled;
984    }
985
986    private String getTypedText() {
987        return mDefaultKeySsb.toString();
988    }
989
990    private void clearTypedText() {
991        mDefaultKeySsb.clear();
992        mDefaultKeySsb.clearSpans();
993        Selection.setSelection(mDefaultKeySsb, 0);
994    }
995
996    /**
997     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
998     * State
999     */
1000    private static State intToState(int stateOrdinal) {
1001        State state = State.WORKSPACE;
1002        final State[] stateValues = State.values();
1003        for (int i = 0; i < stateValues.length; i++) {
1004            if (stateValues[i].ordinal() == stateOrdinal) {
1005                state = stateValues[i];
1006                break;
1007            }
1008        }
1009        return state;
1010    }
1011
1012    /**
1013     * Restores the previous state, if it exists.
1014     *
1015     * @param savedState The previous state.
1016     */
1017    private void restoreState(Bundle savedState) {
1018        if (savedState == null) {
1019            return;
1020        }
1021
1022        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
1023        if (state == State.APPS_CUSTOMIZE) {
1024            mOnResumeState = State.APPS_CUSTOMIZE;
1025        }
1026
1027        int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
1028        if (currentScreen > -1) {
1029            mWorkspace.setRestorePage(currentScreen);
1030        }
1031
1032        final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
1033        final long pendingAddScreen = savedState.getLong(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
1034
1035        if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
1036            mPendingAddInfo.container = pendingAddContainer;
1037            mPendingAddInfo.screenId = pendingAddScreen;
1038            mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
1039            mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
1040            mPendingAddInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
1041            mPendingAddInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
1042            mPendingAddWidgetInfo = savedState.getParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO);
1043            mWaitingForResult = true;
1044            mRestoring = true;
1045        }
1046
1047        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
1048        if (renameFolder) {
1049            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
1050            mFolderInfo = mModel.getFolderById(this, sFolders, id);
1051            mRestoring = true;
1052        }
1053
1054        // Restore the AppsCustomize tab
1055        if (mAppsCustomizeTabHost != null) {
1056            String curTab = savedState.getString("apps_customize_currentTab");
1057            if (curTab != null) {
1058                mAppsCustomizeTabHost.setContentTypeImmediate(
1059                        mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
1060                mAppsCustomizeContent.loadAssociatedPages(
1061                        mAppsCustomizeContent.getCurrentPage());
1062            }
1063
1064            int currentIndex = savedState.getInt("apps_customize_currentIndex");
1065            mAppsCustomizeContent.restorePageForIndex(currentIndex);
1066        }
1067    }
1068
1069    /**
1070     * Finds all the views we need and configure them properly.
1071     */
1072    private void setupViews() {
1073        final DragController dragController = mDragController;
1074
1075        mLauncherView = findViewById(R.id.launcher);
1076        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
1077        mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
1078
1079        mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
1080        mWorkspaceBackgroundDrawable = getResources().getDrawable(R.drawable.workspace_bg);
1081
1082        // Setup the drag layer
1083        mDragLayer.setup(this, dragController);
1084
1085        // Setup the hotseat
1086        mHotseat = (Hotseat) findViewById(R.id.hotseat);
1087        if (mHotseat != null) {
1088            mHotseat.setup(this);
1089        }
1090
1091        mOverviewPanel = findViewById(R.id.overview_panel);
1092        findViewById(R.id.widget_button).setOnClickListener(new OnClickListener() {
1093            @Override
1094            public void onClick(View arg0) {
1095                showAllApps(true);
1096            }
1097        });
1098        findViewById(R.id.wallpaper_button).setOnClickListener(new OnClickListener() {
1099            @Override
1100            public void onClick(View arg0) {
1101                startWallpaper();
1102            }
1103        });
1104
1105        // Setup the workspace
1106        mWorkspace.setHapticFeedbackEnabled(false);
1107        mWorkspace.setOnLongClickListener(this);
1108        mWorkspace.setup(dragController);
1109        dragController.addDragListener(mWorkspace);
1110
1111        // Get the search/delete bar
1112        mSearchDropTargetBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
1113
1114        // Setup AppsCustomize
1115        mAppsCustomizeTabHost = (AppsCustomizeTabHost) findViewById(R.id.apps_customize_pane);
1116        mAppsCustomizeContent = (AppsCustomizePagedView)
1117                mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
1118        mAppsCustomizeContent.setup(this, dragController);
1119
1120        // Setup the drag controller (drop targets have to be added in reverse order in priority)
1121        dragController.setDragScoller(mWorkspace);
1122        dragController.setScrollView(mDragLayer);
1123        dragController.setMoveTarget(mWorkspace);
1124        dragController.addDropTarget(mWorkspace);
1125        if (mSearchDropTargetBar != null) {
1126            mSearchDropTargetBar.setup(this, dragController);
1127        }
1128
1129        if (getResources().getBoolean(R.bool.debug_memory_enabled)) {
1130            Log.v(TAG, "adding WeightWatcher");
1131            mWeightWatcher = new WeightWatcher(this);
1132            mWeightWatcher.setAlpha(0.5f);
1133            ((FrameLayout) mLauncherView).addView(mWeightWatcher,
1134                    new FrameLayout.LayoutParams(
1135                            FrameLayout.LayoutParams.MATCH_PARENT,
1136                            FrameLayout.LayoutParams.WRAP_CONTENT,
1137                            Gravity.BOTTOM)
1138            );
1139
1140            boolean show = shouldShowWeightWatcher();
1141            mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
1142        }
1143    }
1144
1145    /**
1146     * Creates a view representing a shortcut.
1147     *
1148     * @param info The data structure describing the shortcut.
1149     *
1150     * @return A View inflated from R.layout.application.
1151     */
1152    View createShortcut(ShortcutInfo info) {
1153        return createShortcut(R.layout.application,
1154                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
1155    }
1156
1157    /**
1158     * Creates a view representing a shortcut inflated from the specified resource.
1159     *
1160     * @param layoutResId The id of the XML layout used to create the shortcut.
1161     * @param parent The group the shortcut belongs to.
1162     * @param info The data structure describing the shortcut.
1163     *
1164     * @return A View inflated from layoutResId.
1165     */
1166    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
1167        BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
1168        favorite.applyFromShortcutInfo(info, mIconCache);
1169        favorite.setOnClickListener(this);
1170        return favorite;
1171    }
1172
1173    /**
1174     * Add an application shortcut to the workspace.
1175     *
1176     * @param data The intent describing the application.
1177     * @param cellInfo The position on screen where to create the shortcut.
1178     */
1179    void completeAddApplication(Intent data, long container, long screenId, int cellX, int cellY) {
1180        final int[] cellXY = mTmpAddItemCellCoordinates;
1181        final CellLayout layout = getCellLayout(container, screenId);
1182
1183        // First we check if we already know the exact location where we want to add this item.
1184        if (cellX >= 0 && cellY >= 0) {
1185            cellXY[0] = cellX;
1186            cellXY[1] = cellY;
1187        } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
1188            showOutOfSpaceMessage(isHotseatLayout(layout));
1189            return;
1190        }
1191
1192        final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
1193
1194        if (info != null) {
1195            info.setActivity(this, data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
1196                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1197            info.container = ItemInfo.NO_ID;
1198            mWorkspace.addApplicationShortcut(info, layout, container, screenId, cellXY[0], cellXY[1],
1199                    isWorkspaceLocked(), cellX, cellY);
1200        } else {
1201            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
1202        }
1203    }
1204
1205    /**
1206     * Add a shortcut to the workspace.
1207     *
1208     * @param data The intent describing the shortcut.
1209     * @param cellInfo The position on screen where to create the shortcut.
1210     */
1211    private void completeAddShortcut(Intent data, long container, long screenId, int cellX,
1212            int cellY) {
1213        int[] cellXY = mTmpAddItemCellCoordinates;
1214        int[] touchXY = mPendingAddInfo.dropPos;
1215        CellLayout layout = getCellLayout(container, screenId);
1216
1217        boolean foundCellSpan = false;
1218
1219        ShortcutInfo info = mModel.infoFromShortcutIntent(this, data, null);
1220        if (info == null) {
1221            return;
1222        }
1223        final View view = createShortcut(info);
1224
1225        // First we check if we already know the exact location where we want to add this item.
1226        if (cellX >= 0 && cellY >= 0) {
1227            cellXY[0] = cellX;
1228            cellXY[1] = cellY;
1229            foundCellSpan = true;
1230
1231            // If appropriate, either create a folder or add to an existing folder
1232            if (mWorkspace.createUserFolderIfNecessary(view, container, layout, cellXY, 0,
1233                    true, null,null)) {
1234                return;
1235            }
1236            DragObject dragObject = new DragObject();
1237            dragObject.dragInfo = info;
1238            if (mWorkspace.addToExistingFolderIfNecessary(view, layout, cellXY, 0, dragObject,
1239                    true)) {
1240                return;
1241            }
1242        } else if (touchXY != null) {
1243            // when dragging and dropping, just find the closest free spot
1244            int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
1245            foundCellSpan = (result != null);
1246        } else {
1247            foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
1248        }
1249
1250        if (!foundCellSpan) {
1251            showOutOfSpaceMessage(isHotseatLayout(layout));
1252            return;
1253        }
1254
1255        LauncherModel.addItemToDatabase(this, info, container, screenId, cellXY[0], cellXY[1], false);
1256
1257        if (!mRestoring) {
1258            mWorkspace.addInScreen(view, container, screenId, cellXY[0], cellXY[1], 1, 1,
1259                    isWorkspaceLocked());
1260        }
1261    }
1262
1263    static int[] getSpanForWidget(Context context, ComponentName component, int minWidth,
1264            int minHeight) {
1265        Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, component, null);
1266        // We want to account for the extra amount of padding that we are adding to the widget
1267        // to ensure that it gets the full amount of space that it has requested
1268        int requiredWidth = minWidth + padding.left + padding.right;
1269        int requiredHeight = minHeight + padding.top + padding.bottom;
1270        return CellLayout.rectToCell(requiredWidth, requiredHeight, null);
1271    }
1272
1273    static int[] getSpanForWidget(Context context, AppWidgetProviderInfo info) {
1274        return getSpanForWidget(context, info.provider, info.minWidth, info.minHeight);
1275    }
1276
1277    static int[] getMinSpanForWidget(Context context, AppWidgetProviderInfo info) {
1278        return getSpanForWidget(context, info.provider, info.minResizeWidth, info.minResizeHeight);
1279    }
1280
1281    static int[] getSpanForWidget(Context context, PendingAddWidgetInfo info) {
1282        return getSpanForWidget(context, info.componentName, info.minWidth, info.minHeight);
1283    }
1284
1285    static int[] getMinSpanForWidget(Context context, PendingAddWidgetInfo info) {
1286        return getSpanForWidget(context, info.componentName, info.minResizeWidth,
1287                info.minResizeHeight);
1288    }
1289
1290    /**
1291     * Add a widget to the workspace.
1292     *
1293     * @param appWidgetId The app widget id
1294     * @param cellInfo The position on screen where to create the widget.
1295     */
1296    private void completeAddAppWidget(final int appWidgetId, long container, long screenId,
1297            AppWidgetHostView hostView, AppWidgetProviderInfo appWidgetInfo) {
1298        if (appWidgetInfo == null) {
1299            appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1300        }
1301
1302        // Calculate the grid spans needed to fit this widget
1303        CellLayout layout = getCellLayout(container, screenId);
1304
1305        int[] minSpanXY = getMinSpanForWidget(this, appWidgetInfo);
1306        int[] spanXY = getSpanForWidget(this, appWidgetInfo);
1307
1308        // Try finding open space on Launcher screen
1309        // We have saved the position to which the widget was dragged-- this really only matters
1310        // if we are placing widgets on a "spring-loaded" screen
1311        int[] cellXY = mTmpAddItemCellCoordinates;
1312        int[] touchXY = mPendingAddInfo.dropPos;
1313        int[] finalSpan = new int[2];
1314        boolean foundCellSpan = false;
1315        if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
1316            cellXY[0] = mPendingAddInfo.cellX;
1317            cellXY[1] = mPendingAddInfo.cellY;
1318            spanXY[0] = mPendingAddInfo.spanX;
1319            spanXY[1] = mPendingAddInfo.spanY;
1320            foundCellSpan = true;
1321        } else if (touchXY != null) {
1322            // when dragging and dropping, just find the closest free spot
1323            int[] result = layout.findNearestVacantArea(
1324                    touchXY[0], touchXY[1], minSpanXY[0], minSpanXY[1], spanXY[0],
1325                    spanXY[1], cellXY, finalSpan);
1326            spanXY[0] = finalSpan[0];
1327            spanXY[1] = finalSpan[1];
1328            foundCellSpan = (result != null);
1329        } else {
1330            foundCellSpan = layout.findCellForSpan(cellXY, minSpanXY[0], minSpanXY[1]);
1331        }
1332
1333        if (!foundCellSpan) {
1334            if (appWidgetId != -1) {
1335                // Deleting an app widget ID is a void call but writes to disk before returning
1336                // to the caller...
1337                new Thread("deleteAppWidgetId") {
1338                    public void run() {
1339                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1340                    }
1341                }.start();
1342            }
1343            showOutOfSpaceMessage(isHotseatLayout(layout));
1344            return;
1345        }
1346
1347        // Build Launcher-specific widget info and save to database
1348        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId,
1349                appWidgetInfo.provider);
1350        launcherInfo.spanX = spanXY[0];
1351        launcherInfo.spanY = spanXY[1];
1352        launcherInfo.minSpanX = mPendingAddInfo.minSpanX;
1353        launcherInfo.minSpanY = mPendingAddInfo.minSpanY;
1354
1355        LauncherModel.addItemToDatabase(this, launcherInfo,
1356                container, screenId, cellXY[0], cellXY[1], false);
1357
1358        if (!mRestoring) {
1359            if (hostView == null) {
1360                // Perform actual inflation because we're live
1361                launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1362                launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1363            } else {
1364                // The AppWidgetHostView has already been inflated and instantiated
1365                launcherInfo.hostView = hostView;
1366            }
1367
1368            launcherInfo.hostView.setTag(launcherInfo);
1369            launcherInfo.hostView.setVisibility(View.VISIBLE);
1370            launcherInfo.notifyWidgetSizeChanged(this);
1371
1372            mWorkspace.addInScreen(launcherInfo.hostView, container, screenId, cellXY[0], cellXY[1],
1373                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1374
1375            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1376        }
1377        resetAddInfo();
1378    }
1379
1380    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1381        @Override
1382        public void onReceive(Context context, Intent intent) {
1383            final String action = intent.getAction();
1384            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1385                mUserPresent = false;
1386                mDragLayer.clearAllResizeFrames();
1387                updateRunning();
1388
1389                // Reset AllApps to its initial state only if we are not in the middle of
1390                // processing a multi-step drop
1391                if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
1392                    mAppsCustomizeTabHost.reset();
1393                    showWorkspace(false);
1394                }
1395            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1396                mUserPresent = true;
1397                updateRunning();
1398            }
1399        }
1400    };
1401
1402    @Override
1403    public void onAttachedToWindow() {
1404        super.onAttachedToWindow();
1405
1406        // Listen for broadcasts related to user-presence
1407        final IntentFilter filter = new IntentFilter();
1408        filter.addAction(Intent.ACTION_SCREEN_OFF);
1409        filter.addAction(Intent.ACTION_USER_PRESENT);
1410        registerReceiver(mReceiver, filter);
1411        FirstFrameAnimatorHelper.initializeDrawListener(getWindow().getDecorView());
1412        mAttached = true;
1413        mVisible = true;
1414    }
1415
1416    @Override
1417    public void onDetachedFromWindow() {
1418        super.onDetachedFromWindow();
1419        mVisible = false;
1420
1421        if (mAttached) {
1422            unregisterReceiver(mReceiver);
1423            mAttached = false;
1424        }
1425        updateRunning();
1426    }
1427
1428    public void onWindowVisibilityChanged(int visibility) {
1429        mVisible = visibility == View.VISIBLE;
1430        updateRunning();
1431        // The following code used to be in onResume, but it turns out onResume is called when
1432        // you're in All Apps and click home to go to the workspace. onWindowVisibilityChanged
1433        // is a more appropriate event to handle
1434        if (mVisible) {
1435            mAppsCustomizeTabHost.onWindowVisible();
1436            if (!mWorkspaceLoading) {
1437                final ViewTreeObserver observer = mWorkspace.getViewTreeObserver();
1438                // We want to let Launcher draw itself at least once before we force it to build
1439                // layers on all the workspace pages, so that transitioning to Launcher from other
1440                // apps is nice and speedy.
1441                observer.addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
1442                    private boolean mStarted = false;
1443                    public void onDraw() {
1444                        if (mStarted) return;
1445                        mStarted = true;
1446                        // We delay the layer building a bit in order to give
1447                        // other message processing a time to run.  In particular
1448                        // this avoids a delay in hiding the IME if it was
1449                        // currently shown, because doing that may involve
1450                        // some communication back with the app.
1451                        mWorkspace.postDelayed(mBuildLayersRunnable, 500);
1452                        final ViewTreeObserver.OnDrawListener listener = this;
1453                        mWorkspace.post(new Runnable() {
1454                                public void run() {
1455                                    if (mWorkspace != null &&
1456                                            mWorkspace.getViewTreeObserver() != null) {
1457                                        mWorkspace.getViewTreeObserver().
1458                                                removeOnDrawListener(listener);
1459                                    }
1460                                }
1461                            });
1462                        return;
1463                    }
1464                });
1465            }
1466            // When Launcher comes back to foreground, a different Activity might be responsible for
1467            // the app market intent, so refresh the icon
1468            updateAppMarketIcon();
1469            clearTypedText();
1470        }
1471    }
1472
1473    private void sendAdvanceMessage(long delay) {
1474        mHandler.removeMessages(ADVANCE_MSG);
1475        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1476        mHandler.sendMessageDelayed(msg, delay);
1477        mAutoAdvanceSentTime = System.currentTimeMillis();
1478    }
1479
1480    private void updateRunning() {
1481        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1482        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1483            mAutoAdvanceRunning = autoAdvanceRunning;
1484            if (autoAdvanceRunning) {
1485                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1486                sendAdvanceMessage(delay);
1487            } else {
1488                if (!mWidgetsToAdvance.isEmpty()) {
1489                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1490                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1491                }
1492                mHandler.removeMessages(ADVANCE_MSG);
1493                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1494            }
1495        }
1496    }
1497
1498    private final Handler mHandler = new Handler() {
1499        @Override
1500        public void handleMessage(Message msg) {
1501            if (msg.what == ADVANCE_MSG) {
1502                int i = 0;
1503                for (View key: mWidgetsToAdvance.keySet()) {
1504                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1505                    final int delay = mAdvanceStagger * i;
1506                    if (v instanceof Advanceable) {
1507                       postDelayed(new Runnable() {
1508                           public void run() {
1509                               ((Advanceable) v).advance();
1510                           }
1511                       }, delay);
1512                    }
1513                    i++;
1514                }
1515                sendAdvanceMessage(mAdvanceInterval);
1516            }
1517        }
1518    };
1519
1520    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1521        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1522        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1523        if (v instanceof Advanceable) {
1524            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1525            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1526            updateRunning();
1527        }
1528    }
1529
1530    void removeWidgetToAutoAdvance(View hostView) {
1531        if (mWidgetsToAdvance.containsKey(hostView)) {
1532            mWidgetsToAdvance.remove(hostView);
1533            updateRunning();
1534        }
1535    }
1536
1537    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1538        removeWidgetToAutoAdvance(launcherInfo.hostView);
1539        launcherInfo.hostView = null;
1540    }
1541
1542    void showOutOfSpaceMessage(boolean isHotseatLayout) {
1543        int strId = (isHotseatLayout ? R.string.hotseat_out_of_space : R.string.out_of_space);
1544        Toast.makeText(this, getString(strId), Toast.LENGTH_SHORT).show();
1545    }
1546
1547    public LauncherAppWidgetHost getAppWidgetHost() {
1548        return mAppWidgetHost;
1549    }
1550
1551    public LauncherModel getModel() {
1552        return mModel;
1553    }
1554
1555    public void closeSystemDialogs() {
1556        getWindow().closeAllPanels();
1557
1558        // Whatever we were doing is hereby canceled.
1559        mWaitingForResult = false;
1560    }
1561
1562    @Override
1563    protected void onNewIntent(Intent intent) {
1564        long startTime = 0;
1565        if (DEBUG_RESUME_TIME) {
1566            startTime = System.currentTimeMillis();
1567        }
1568        super.onNewIntent(intent);
1569
1570        // Close the menu
1571        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1572            // also will cancel mWaitingForResult.
1573            closeSystemDialogs();
1574
1575            final boolean alreadyOnHome =
1576                    ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1577                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1578
1579            Runnable processIntent = new Runnable() {
1580                public void run() {
1581                    if (mWorkspace == null) {
1582                        // Can be cases where mWorkspace is null, this prevents a NPE
1583                        return;
1584                    }
1585                    Folder openFolder = mWorkspace.getOpenFolder();
1586                    // In all these cases, only animate if we're already on home
1587                    mWorkspace.exitWidgetResizeMode();
1588                    if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive() &&
1589                            openFolder == null) {
1590                        mWorkspace.moveToDefaultScreen(true);
1591                    }
1592
1593                    closeFolder();
1594                    exitSpringLoadedDragMode();
1595
1596                    // If we are already on home, then just animate back to the workspace,
1597                    // otherwise, just wait until onResume to set the state back to Workspace
1598                    if (alreadyOnHome) {
1599                        showWorkspace(true);
1600                        if (mWorkspace.isInOverviewMode()) {
1601                            mWorkspace.exitOverviewMode();
1602                        }
1603                    } else {
1604                        mOnResumeState = State.WORKSPACE;
1605                    }
1606
1607                    final View v = getWindow().peekDecorView();
1608                    if (v != null && v.getWindowToken() != null) {
1609                        InputMethodManager imm = (InputMethodManager)getSystemService(
1610                                INPUT_METHOD_SERVICE);
1611                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1612                    }
1613
1614                    // Reset AllApps to its initial state
1615                    if (!alreadyOnHome && mAppsCustomizeTabHost != null) {
1616                        mAppsCustomizeTabHost.reset();
1617                    }
1618                }
1619            };
1620
1621            if (alreadyOnHome && !mWorkspace.hasWindowFocus()) {
1622                // Delay processing of the intent to allow the status bar animation to finish
1623                // first in order to avoid janky animations.
1624                mWorkspace.postDelayed(processIntent, 350);
1625            } else {
1626                // Process the intent immediately.
1627                processIntent.run();
1628            }
1629
1630        }
1631        if (DEBUG_RESUME_TIME) {
1632            Log.d(TAG, "Time spent in onNewIntent: " + (System.currentTimeMillis() - startTime));
1633        }
1634    }
1635
1636    @Override
1637    public void onRestoreInstanceState(Bundle state) {
1638        super.onRestoreInstanceState(state);
1639        for (int page: mSynchronouslyBoundPages) {
1640            mWorkspace.restoreInstanceStateForChild(page);
1641        }
1642    }
1643
1644    @Override
1645    protected void onSaveInstanceState(Bundle outState) {
1646        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getNextPage());
1647        super.onSaveInstanceState(outState);
1648
1649        outState.putInt(RUNTIME_STATE, mState.ordinal());
1650        // We close any open folder since it will not be re-opened, and we need to make sure
1651        // this state is reflected.
1652        closeFolder();
1653
1654        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screenId > -1 &&
1655                mWaitingForResult) {
1656            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1657            outState.putLong(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screenId);
1658            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1659            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1660            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, mPendingAddInfo.spanX);
1661            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, mPendingAddInfo.spanY);
1662            outState.putParcelable(RUNTIME_STATE_PENDING_ADD_WIDGET_INFO, mPendingAddWidgetInfo);
1663        }
1664
1665        if (mFolderInfo != null && mWaitingForResult) {
1666            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1667            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1668        }
1669
1670        // Save the current AppsCustomize tab
1671        if (mAppsCustomizeTabHost != null) {
1672            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1673            if (currentTabTag != null) {
1674                outState.putString("apps_customize_currentTab", currentTabTag);
1675            }
1676            int currentIndex = mAppsCustomizeContent.getSaveInstanceStateIndex();
1677            outState.putInt("apps_customize_currentIndex", currentIndex);
1678        }
1679    }
1680
1681    @Override
1682    public void onDestroy() {
1683        super.onDestroy();
1684
1685        // Remove all pending runnables
1686        mHandler.removeMessages(ADVANCE_MSG);
1687        mHandler.removeMessages(0);
1688        mWorkspace.removeCallbacks(mBuildLayersRunnable);
1689
1690        // Stop callbacks from LauncherModel
1691        LauncherAppState app = (LauncherAppState.getInstance());
1692        mModel.stopLoader();
1693        app.setLauncher(null);
1694
1695        try {
1696            mAppWidgetHost.stopListening();
1697        } catch (NullPointerException ex) {
1698            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1699        }
1700        mAppWidgetHost = null;
1701
1702        mWidgetsToAdvance.clear();
1703
1704        TextKeyListener.getInstance().release();
1705
1706        // Disconnect any of the callbacks and drawables associated with ItemInfos on the workspace
1707        // to prevent leaking Launcher activities on orientation change.
1708        if (mModel != null) {
1709            mModel.unbindItemInfosAndClearQueuedBindRunnables();
1710        }
1711
1712        getContentResolver().unregisterContentObserver(mWidgetObserver);
1713        unregisterReceiver(mCloseSystemDialogsReceiver);
1714
1715        mDragLayer.clearAllResizeFrames();
1716        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1717        mWorkspace.removeAllViews();
1718        mWorkspace = null;
1719        mDragController = null;
1720
1721        LauncherAnimUtils.onDestroyActivity();
1722    }
1723
1724    public DragController getDragController() {
1725        return mDragController;
1726    }
1727
1728    @Override
1729    public void startActivityForResult(Intent intent, int requestCode) {
1730        if (requestCode >= 0) mWaitingForResult = true;
1731        super.startActivityForResult(intent, requestCode);
1732    }
1733
1734    /**
1735     * Indicates that we want global search for this activity by setting the globalSearch
1736     * argument for {@link #startSearch} to true.
1737     */
1738    @Override
1739    public void startSearch(String initialQuery, boolean selectInitialQuery,
1740            Bundle appSearchData, boolean globalSearch) {
1741
1742        showWorkspace(true);
1743
1744        if (initialQuery == null) {
1745            // Use any text typed in the launcher as the initial query
1746            initialQuery = getTypedText();
1747        }
1748        if (appSearchData == null) {
1749            appSearchData = new Bundle();
1750            appSearchData.putString("source", "launcher-search");
1751        }
1752        Rect sourceBounds = new Rect();
1753        if (mSearchDropTargetBar != null) {
1754            sourceBounds = mSearchDropTargetBar.getSearchBarBounds();
1755        }
1756
1757        startSearch(initialQuery, selectInitialQuery,
1758                appSearchData, sourceBounds);
1759    }
1760
1761    public void startSearch(String initialQuery,
1762            boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
1763        startGlobalSearch(initialQuery, selectInitialQuery,
1764                appSearchData, sourceBounds);
1765    }
1766
1767    /**
1768     * Starts the global search activity. This code is a copied from SearchManager
1769     */
1770    private void startGlobalSearch(String initialQuery,
1771            boolean selectInitialQuery, Bundle appSearchData, Rect sourceBounds) {
1772        final SearchManager searchManager =
1773            (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1774        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
1775        if (globalSearchActivity == null) {
1776            Log.w(TAG, "No global search activity found.");
1777            return;
1778        }
1779        Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
1780        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1781        intent.setComponent(globalSearchActivity);
1782        // Make sure that we have a Bundle to put source in
1783        if (appSearchData == null) {
1784            appSearchData = new Bundle();
1785        } else {
1786            appSearchData = new Bundle(appSearchData);
1787        }
1788        // Set source to package name of app that starts global search, if not set already.
1789        if (!appSearchData.containsKey("source")) {
1790            appSearchData.putString("source", getPackageName());
1791        }
1792        intent.putExtra(SearchManager.APP_DATA, appSearchData);
1793        if (!TextUtils.isEmpty(initialQuery)) {
1794            intent.putExtra(SearchManager.QUERY, initialQuery);
1795        }
1796        if (selectInitialQuery) {
1797            intent.putExtra(SearchManager.EXTRA_SELECT_QUERY, selectInitialQuery);
1798        }
1799        intent.setSourceBounds(sourceBounds);
1800        try {
1801            startActivity(intent);
1802        } catch (ActivityNotFoundException ex) {
1803            Log.e(TAG, "Global search activity not found: " + globalSearchActivity);
1804        }
1805    }
1806
1807    @Override
1808    public boolean onCreateOptionsMenu(Menu menu) {
1809        if (isWorkspaceLocked()) {
1810            return false;
1811        }
1812
1813        super.onCreateOptionsMenu(menu);
1814
1815        Intent manageApps = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
1816        manageApps.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1817                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1818        Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1819        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1820                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1821        String helpUrl = getString(R.string.help_url);
1822        Intent help = new Intent(Intent.ACTION_VIEW, Uri.parse(helpUrl));
1823        help.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1824                | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1825
1826        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1827            .setIcon(android.R.drawable.ic_menu_gallery)
1828            .setAlphabeticShortcut('W');
1829        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1830            .setIcon(android.R.drawable.ic_menu_manage)
1831            .setIntent(manageApps)
1832            .setAlphabeticShortcut('M');
1833        menu.add(0, MENU_SYSTEM_SETTINGS, 0, R.string.menu_settings)
1834            .setIcon(android.R.drawable.ic_menu_preferences)
1835            .setIntent(settings)
1836            .setAlphabeticShortcut('P');
1837        if (!helpUrl.isEmpty()) {
1838            menu.add(0, MENU_HELP, 0, R.string.menu_help)
1839                .setIcon(android.R.drawable.ic_menu_help)
1840                .setIntent(help)
1841                .setAlphabeticShortcut('H');
1842        }
1843        return true;
1844    }
1845
1846    @Override
1847    public boolean onPrepareOptionsMenu(Menu menu) {
1848        super.onPrepareOptionsMenu(menu);
1849
1850        if (mAppsCustomizeTabHost.isTransitioning()) {
1851            return false;
1852        }
1853        boolean allAppsVisible = (mAppsCustomizeTabHost.getVisibility() == View.VISIBLE);
1854        menu.setGroupVisible(MENU_GROUP_WALLPAPER, !allAppsVisible);
1855
1856        return true;
1857    }
1858
1859    @Override
1860    public boolean onOptionsItemSelected(MenuItem item) {
1861        switch (item.getItemId()) {
1862        case MENU_WALLPAPER_SETTINGS:
1863            startWallpaper();
1864            return true;
1865        }
1866
1867        return super.onOptionsItemSelected(item);
1868    }
1869
1870    @Override
1871    public boolean onSearchRequested() {
1872        startSearch(null, false, null, true);
1873        // Use a custom animation for launching search
1874        return true;
1875    }
1876
1877    public boolean isWorkspaceLocked() {
1878        return mWorkspaceLoading || mWaitingForResult;
1879    }
1880
1881    private void resetAddInfo() {
1882        mPendingAddInfo.container = ItemInfo.NO_ID;
1883        mPendingAddInfo.screenId = -1;
1884        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1885        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1886        mPendingAddInfo.minSpanX = mPendingAddInfo.minSpanY = -1;
1887        mPendingAddInfo.dropPos = null;
1888    }
1889
1890    void addAppWidgetImpl(final int appWidgetId, ItemInfo info, AppWidgetHostView boundWidget,
1891            AppWidgetProviderInfo appWidgetInfo) {
1892        if (appWidgetInfo.configure != null) {
1893            mPendingAddWidgetInfo = appWidgetInfo;
1894
1895            // Launch over to configure widget, if needed
1896            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1897            intent.setComponent(appWidgetInfo.configure);
1898            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1899            Utilities.startActivityForResultSafely(this, intent, REQUEST_CREATE_APPWIDGET);
1900        } else {
1901            // Otherwise just add it
1902            completeAddAppWidget(appWidgetId, info.container, info.screenId, boundWidget,
1903                    appWidgetInfo);
1904            // Exit spring loaded mode if necessary after adding the widget
1905            exitSpringLoadedDragModeDelayed(true, false, null);
1906        }
1907    }
1908
1909    /**
1910     * Process a shortcut drop.
1911     *
1912     * @param componentName The name of the component
1913     * @param screenId The ID of the screen where it should be added
1914     * @param cell The cell it should be added to, optional
1915     * @param position The location on the screen where it was dropped, optional
1916     */
1917    void processShortcutFromDrop(ComponentName componentName, long container, long screenId,
1918            int[] cell, int[] loc) {
1919        resetAddInfo();
1920        mPendingAddInfo.container = container;
1921        mPendingAddInfo.screenId = screenId;
1922        mPendingAddInfo.dropPos = loc;
1923
1924        if (cell != null) {
1925            mPendingAddInfo.cellX = cell[0];
1926            mPendingAddInfo.cellY = cell[1];
1927        }
1928
1929        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1930        createShortcutIntent.setComponent(componentName);
1931        processShortcut(createShortcutIntent);
1932    }
1933
1934    /**
1935     * Process a widget drop.
1936     *
1937     * @param info The PendingAppWidgetInfo of the widget being added.
1938     * @param screenId The ID of the screen where it should be added
1939     * @param cell The cell it should be added to, optional
1940     * @param position The location on the screen where it was dropped, optional
1941     */
1942    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, long screenId,
1943            int[] cell, int[] span, int[] loc) {
1944        resetAddInfo();
1945        mPendingAddInfo.container = info.container = container;
1946        mPendingAddInfo.screenId = info.screenId = screenId;
1947        mPendingAddInfo.dropPos = loc;
1948        mPendingAddInfo.minSpanX = info.minSpanX;
1949        mPendingAddInfo.minSpanY = info.minSpanY;
1950
1951        if (cell != null) {
1952            mPendingAddInfo.cellX = cell[0];
1953            mPendingAddInfo.cellY = cell[1];
1954        }
1955        if (span != null) {
1956            mPendingAddInfo.spanX = span[0];
1957            mPendingAddInfo.spanY = span[1];
1958        }
1959
1960        AppWidgetHostView hostView = info.boundWidget;
1961        int appWidgetId;
1962        if (hostView != null) {
1963            appWidgetId = hostView.getAppWidgetId();
1964            addAppWidgetImpl(appWidgetId, info, hostView, info.info);
1965        } else {
1966            // In this case, we either need to start an activity to get permission to bind
1967            // the widget, or we need to start an activity to configure the widget, or both.
1968            appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1969            Bundle options = info.bindOptions;
1970
1971            boolean success = false;
1972            if (options != null) {
1973                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1974                        info.componentName, options);
1975            } else {
1976                success = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId,
1977                        info.componentName);
1978            }
1979            if (success) {
1980                addAppWidgetImpl(appWidgetId, info, null, info.info);
1981            } else {
1982                mPendingAddWidgetInfo = info.info;
1983                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
1984                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1985                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, info.componentName);
1986                // TODO: we need to make sure that this accounts for the options bundle.
1987                // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options);
1988                startActivityForResult(intent, REQUEST_BIND_APPWIDGET);
1989            }
1990        }
1991    }
1992
1993    void processShortcut(Intent intent) {
1994        // Handle case where user selected "Applications"
1995        String applicationName = getResources().getString(R.string.group_applications);
1996        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1997
1998        if (applicationName != null && applicationName.equals(shortcutName)) {
1999            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
2000            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
2001
2002            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
2003            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
2004            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
2005            Utilities.startActivityForResultSafely(this, pickIntent, REQUEST_PICK_APPLICATION);
2006        } else {
2007            Utilities.startActivityForResultSafely(this, intent, REQUEST_CREATE_SHORTCUT);
2008        }
2009    }
2010
2011    void processWallpaper(Intent intent) {
2012        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
2013    }
2014
2015    FolderIcon addFolder(CellLayout layout, long container, final long screenId, int cellX,
2016            int cellY) {
2017        final FolderInfo folderInfo = new FolderInfo();
2018        folderInfo.title = getText(R.string.folder_name);
2019
2020        // Update the model
2021        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screenId, cellX, cellY,
2022                false);
2023        sFolders.put(folderInfo.id, folderInfo);
2024
2025        // Create the view
2026        FolderIcon newFolder =
2027            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
2028        mWorkspace.addInScreen(newFolder, container, screenId, cellX, cellY, 1, 1,
2029                isWorkspaceLocked());
2030        // Force measure the new folder icon
2031        CellLayout parent = mWorkspace.getParentCellLayoutForView(newFolder);
2032        parent.getShortcutsAndWidgets().measureChild(newFolder);
2033        return newFolder;
2034    }
2035
2036    void removeFolder(FolderInfo folder) {
2037        sFolders.remove(folder.id);
2038    }
2039
2040    private void startWallpaper() {
2041        showWorkspace(true);
2042        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
2043        pickWallpaper.setComponent(
2044                new ComponentName(getPackageName(), WallpaperPickerActivity.class.getName()));
2045        startActivityForResult(pickWallpaper, REQUEST_PICK_WALLPAPER);
2046    }
2047
2048    /**
2049     * Registers various content observers. The current implementation registers
2050     * only a favorites observer to keep track of the favorites applications.
2051     */
2052    private void registerContentObservers() {
2053        ContentResolver resolver = getContentResolver();
2054        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
2055                true, mWidgetObserver);
2056    }
2057
2058    @Override
2059    public boolean dispatchKeyEvent(KeyEvent event) {
2060        if (event.getAction() == KeyEvent.ACTION_DOWN) {
2061            switch (event.getKeyCode()) {
2062                case KeyEvent.KEYCODE_HOME:
2063                    return true;
2064                case KeyEvent.KEYCODE_VOLUME_DOWN:
2065                    if (isPropertyEnabled(DUMP_STATE_PROPERTY)) {
2066                        dumpState();
2067                        return true;
2068                    }
2069                    break;
2070            }
2071        } else if (event.getAction() == KeyEvent.ACTION_UP) {
2072            switch (event.getKeyCode()) {
2073                case KeyEvent.KEYCODE_HOME:
2074                    return true;
2075            }
2076        }
2077
2078        return super.dispatchKeyEvent(event);
2079    }
2080
2081    @Override
2082    public void onBackPressed() {
2083        if (isAllAppsVisible()) {
2084            showWorkspace(true);
2085        } else if (mWorkspace.isInOverviewMode()) {
2086            mWorkspace.exitOverviewMode();
2087        } else if (mWorkspace.getOpenFolder() != null) {
2088            Folder openFolder = mWorkspace.getOpenFolder();
2089            if (openFolder.isEditingName()) {
2090                openFolder.dismissEditingName();
2091            } else {
2092                closeFolder();
2093            }
2094        } else {
2095            mWorkspace.exitWidgetResizeMode();
2096
2097            // Back button is a no-op here, but give at least some feedback for the button press
2098            mWorkspace.showOutlinesTemporarily();
2099        }
2100    }
2101
2102    /**
2103     * Re-listen when widgets are reset.
2104     */
2105    private void onAppWidgetReset() {
2106        if (mAppWidgetHost != null) {
2107            mAppWidgetHost.startListening();
2108        }
2109    }
2110
2111    /**
2112     * Launches the intent referred by the clicked shortcut.
2113     *
2114     * @param v The view representing the clicked shortcut.
2115     */
2116    public void onClick(View v) {
2117        // Make sure that rogue clicks don't get through while allapps is launching, or after the
2118        // view has detached (it's possible for this to happen if the view is removed mid touch).
2119        if (v.getWindowToken() == null) {
2120            return;
2121        }
2122
2123        if (!mWorkspace.isFinishedSwitchingState()) {
2124            return;
2125        }
2126
2127        if (v instanceof PageIndicator) {
2128            if (!mWorkspace.isInOverviewMode()) {
2129                mWorkspace.enterOverviewMode();
2130            }
2131            return;
2132        }
2133
2134        if (v instanceof CellLayout) {
2135            if (mWorkspace.isInOverviewMode()) {
2136                mWorkspace.exitOverviewMode(mWorkspace.indexOfChild(v));
2137            }
2138        }
2139
2140        Object tag = v.getTag();
2141        if (tag instanceof ShortcutInfo) {
2142            // Open shortcut
2143            final ShortcutInfo shortcut = (ShortcutInfo) tag;
2144            final Intent intent = shortcut.intent;
2145
2146            // Check for special shortcuts
2147            if (intent.getComponent() != null) {
2148                final String shortcutClass = intent.getComponent().getClassName();
2149
2150                if (shortcutClass.equals(WidgetAdder.class.getName())) {
2151                    showAllApps(true);
2152                    return;
2153                } else if (shortcutClass.equals(MemoryDumpActivity.class.getName())) {
2154                    MemoryDumpActivity.startDump(this);
2155                    return;
2156                } else if (shortcutClass.equals(ToggleWeightWatcher.class.getName())) {
2157                    toggleShowWeightWatcher();
2158                    return;
2159                }
2160            }
2161
2162            // Start activities
2163            int[] pos = new int[2];
2164            v.getLocationOnScreen(pos);
2165            intent.setSourceBounds(new Rect(pos[0], pos[1],
2166                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
2167
2168            boolean success = startActivitySafely(v, intent, tag);
2169
2170            mStats.recordLaunch(intent, shortcut);
2171
2172            if (success && v instanceof BubbleTextView) {
2173                mWaitingForResume = (BubbleTextView) v;
2174                mWaitingForResume.setStayPressed(true);
2175            }
2176        } else if (tag instanceof FolderInfo) {
2177            if (v instanceof FolderIcon) {
2178                FolderIcon fi = (FolderIcon) v;
2179                handleFolderClick(fi);
2180            }
2181        } else if (v == mAllAppsButton) {
2182            if (isAllAppsVisible()) {
2183                showWorkspace(true);
2184            } else {
2185                onClickAllAppsButton(v);
2186            }
2187        }
2188    }
2189
2190    public boolean onTouch(View v, MotionEvent event) {
2191        return false;
2192    }
2193
2194    /**
2195     * Event handler for the search button
2196     *
2197     * @param v The view that was clicked.
2198     */
2199    public void onClickSearchButton(View v) {
2200        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2201
2202        onSearchRequested();
2203    }
2204
2205    /**
2206     * Event handler for the voice button
2207     *
2208     * @param v The view that was clicked.
2209     */
2210    public void onClickVoiceButton(View v) {
2211        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2212
2213        startVoice();
2214    }
2215
2216    public void startVoice() {
2217        try {
2218            final SearchManager searchManager =
2219                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2220            ComponentName activityName = searchManager.getGlobalSearchActivity();
2221            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2222            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2223            if (activityName != null) {
2224                intent.setPackage(activityName.getPackageName());
2225            }
2226            startActivity(null, intent, "onClickVoiceButton");
2227        } catch (ActivityNotFoundException e) {
2228            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2229            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2230            startActivitySafely(null, intent, "onClickVoiceButton");
2231        }
2232    }
2233
2234    /**
2235     * Event handler for the "grid" button that appears on the home screen, which
2236     * enters all apps mode.
2237     *
2238     * @param v The view that was clicked.
2239     */
2240    public void onClickAllAppsButton(View v) {
2241        showAllApps(true);
2242    }
2243
2244    public void onTouchDownAllAppsButton(View v) {
2245        // Provide the same haptic feedback that the system offers for virtual keys.
2246        v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
2247    }
2248
2249    public void onClickAppMarketButton(View v) {
2250        if (mAppMarketIntent != null) {
2251            startActivitySafely(v, mAppMarketIntent, "app market");
2252        } else {
2253            Log.e(TAG, "Invalid app market intent.");
2254        }
2255    }
2256
2257    void startApplicationDetailsActivity(ComponentName componentName) {
2258        String packageName = componentName.getPackageName();
2259        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
2260                Uri.fromParts("package", packageName, null));
2261        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2262        startActivitySafely(null, intent, "startApplicationDetailsActivity");
2263    }
2264
2265    // returns true if the activity was started
2266    boolean startApplicationUninstallActivity(ComponentName componentName, int flags) {
2267        if ((flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
2268            // System applications cannot be installed. For now, show a toast explaining that.
2269            // We may give them the option of disabling apps this way.
2270            int messageId = R.string.uninstall_system_app_text;
2271            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
2272            return false;
2273        } else {
2274            String packageName = componentName.getPackageName();
2275            String className = componentName.getClassName();
2276            Intent intent = new Intent(
2277                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
2278            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
2279                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
2280            startActivity(intent);
2281            return true;
2282        }
2283    }
2284
2285    boolean startActivity(View v, Intent intent, Object tag) {
2286        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2287
2288        try {
2289            // Only launch using the new animation if the shortcut has not opted out (this is a
2290            // private contract between launcher and may be ignored in the future).
2291            boolean useLaunchAnimation = (v != null) &&
2292                    !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
2293            if (useLaunchAnimation) {
2294                ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
2295                        v.getMeasuredWidth(), v.getMeasuredHeight());
2296
2297                startActivity(intent, opts.toBundle());
2298            } else {
2299                startActivity(intent);
2300            }
2301            return true;
2302        } catch (SecurityException e) {
2303            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2304            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
2305                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
2306                    "or use the exported attribute for this activity. "
2307                    + "tag="+ tag + " intent=" + intent, e);
2308        }
2309        return false;
2310    }
2311
2312    boolean startActivitySafely(View v, Intent intent, Object tag) {
2313        boolean success = false;
2314        try {
2315            success = startActivity(v, intent, tag);
2316        } catch (ActivityNotFoundException e) {
2317            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
2318            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
2319        }
2320        return success;
2321    }
2322
2323    private void handleFolderClick(FolderIcon folderIcon) {
2324        final FolderInfo info = folderIcon.getFolderInfo();
2325        Folder openFolder = mWorkspace.getFolderForTag(info);
2326
2327        // If the folder info reports that the associated folder is open, then verify that
2328        // it is actually opened. There have been a few instances where this gets out of sync.
2329        if (info.opened && openFolder == null) {
2330            Log.d(TAG, "Folder info marked as open, but associated folder is not open. Screen: "
2331                    + info.screenId + " (" + info.cellX + ", " + info.cellY + ")");
2332            info.opened = false;
2333        }
2334
2335        if (!info.opened && !folderIcon.getFolder().isDestroyed()) {
2336            // Close any open folder
2337            closeFolder();
2338            // Open the requested folder
2339            openFolder(folderIcon);
2340        } else {
2341            // Find the open folder...
2342            int folderScreen;
2343            if (openFolder != null) {
2344                folderScreen = mWorkspace.getPageForView(openFolder);
2345                // .. and close it
2346                closeFolder(openFolder);
2347                if (folderScreen != mWorkspace.getCurrentPage()) {
2348                    // Close any folder open on the current screen
2349                    closeFolder();
2350                    // Pull the folder onto this screen
2351                    openFolder(folderIcon);
2352                }
2353            }
2354        }
2355    }
2356
2357    /**
2358     * This method draws the FolderIcon to an ImageView and then adds and positions that ImageView
2359     * in the DragLayer in the exact absolute location of the original FolderIcon.
2360     */
2361    private void copyFolderIconToImage(FolderIcon fi) {
2362        final int width = fi.getMeasuredWidth();
2363        final int height = fi.getMeasuredHeight();
2364
2365        // Lazy load ImageView, Bitmap and Canvas
2366        if (mFolderIconImageView == null) {
2367            mFolderIconImageView = new ImageView(this);
2368        }
2369        if (mFolderIconBitmap == null || mFolderIconBitmap.getWidth() != width ||
2370                mFolderIconBitmap.getHeight() != height) {
2371            mFolderIconBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2372            mFolderIconCanvas = new Canvas(mFolderIconBitmap);
2373        }
2374
2375        DragLayer.LayoutParams lp;
2376        if (mFolderIconImageView.getLayoutParams() instanceof DragLayer.LayoutParams) {
2377            lp = (DragLayer.LayoutParams) mFolderIconImageView.getLayoutParams();
2378        } else {
2379            lp = new DragLayer.LayoutParams(width, height);
2380        }
2381
2382        // The layout from which the folder is being opened may be scaled, adjust the starting
2383        // view size by this scale factor.
2384        float scale = mDragLayer.getDescendantRectRelativeToSelf(fi, mRectForFolderAnimation);
2385        lp.customPosition = true;
2386        lp.x = mRectForFolderAnimation.left;
2387        lp.y = mRectForFolderAnimation.top;
2388        lp.width = (int) (scale * width);
2389        lp.height = (int) (scale * height);
2390
2391        mFolderIconCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
2392        fi.draw(mFolderIconCanvas);
2393        mFolderIconImageView.setImageBitmap(mFolderIconBitmap);
2394        if (fi.getFolder() != null) {
2395            mFolderIconImageView.setPivotX(fi.getFolder().getPivotXForIconAnimation());
2396            mFolderIconImageView.setPivotY(fi.getFolder().getPivotYForIconAnimation());
2397        }
2398        // Just in case this image view is still in the drag layer from a previous animation,
2399        // we remove it and re-add it.
2400        if (mDragLayer.indexOfChild(mFolderIconImageView) != -1) {
2401            mDragLayer.removeView(mFolderIconImageView);
2402        }
2403        mDragLayer.addView(mFolderIconImageView, lp);
2404        if (fi.getFolder() != null) {
2405            fi.getFolder().bringToFront();
2406        }
2407    }
2408
2409    private void growAndFadeOutFolderIcon(FolderIcon fi) {
2410        if (fi == null) return;
2411        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
2412        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
2413        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
2414
2415        FolderInfo info = (FolderInfo) fi.getTag();
2416        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2417            CellLayout cl = (CellLayout) fi.getParent().getParent();
2418            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
2419            cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
2420        }
2421
2422        // Push an ImageView copy of the FolderIcon into the DragLayer and hide the original
2423        copyFolderIconToImage(fi);
2424        fi.setVisibility(View.INVISIBLE);
2425
2426        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2427                scaleX, scaleY);
2428        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2429        oa.start();
2430    }
2431
2432    private void shrinkAndFadeInFolderIcon(final FolderIcon fi) {
2433        if (fi == null) return;
2434        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
2435        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
2436        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
2437
2438        final CellLayout cl = (CellLayout) fi.getParent().getParent();
2439
2440        // We remove and re-draw the FolderIcon in-case it has changed
2441        mDragLayer.removeView(mFolderIconImageView);
2442        copyFolderIconToImage(fi);
2443        ObjectAnimator oa = LauncherAnimUtils.ofPropertyValuesHolder(mFolderIconImageView, alpha,
2444                scaleX, scaleY);
2445        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
2446        oa.addListener(new AnimatorListenerAdapter() {
2447            @Override
2448            public void onAnimationEnd(Animator animation) {
2449                if (cl != null) {
2450                    cl.clearFolderLeaveBehind();
2451                    // Remove the ImageView copy of the FolderIcon and make the original visible.
2452                    mDragLayer.removeView(mFolderIconImageView);
2453                    fi.setVisibility(View.VISIBLE);
2454                }
2455            }
2456        });
2457        oa.start();
2458    }
2459
2460    /**
2461     * Opens the user folder described by the specified tag. The opening of the folder
2462     * is animated relative to the specified View. If the View is null, no animation
2463     * is played.
2464     *
2465     * @param folderInfo The FolderInfo describing the folder to open.
2466     */
2467    public void openFolder(FolderIcon folderIcon) {
2468        Folder folder = folderIcon.getFolder();
2469        FolderInfo info = folder.mInfo;
2470
2471        info.opened = true;
2472
2473        // Just verify that the folder hasn't already been added to the DragLayer.
2474        // There was a one-off crash where the folder had a parent already.
2475        if (folder.getParent() == null) {
2476            mDragLayer.addView(folder);
2477            mDragController.addDropTarget((DropTarget) folder);
2478        } else {
2479            Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
2480                    folder.getParent() + ").");
2481        }
2482        folder.animateOpen();
2483        growAndFadeOutFolderIcon(folderIcon);
2484
2485        // Notify the accessibility manager that this folder "window" has appeared and occluded
2486        // the workspace items
2487        folder.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2488        getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED);
2489    }
2490
2491    public void closeFolder() {
2492        Folder folder = mWorkspace.getOpenFolder();
2493        if (folder != null) {
2494            if (folder.isEditingName()) {
2495                folder.dismissEditingName();
2496            }
2497            closeFolder(folder);
2498
2499            // Dismiss the folder cling
2500            dismissFolderCling(null);
2501        }
2502    }
2503
2504    void closeFolder(Folder folder) {
2505        folder.getInfo().opened = false;
2506
2507        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
2508        if (parent != null) {
2509            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
2510            shrinkAndFadeInFolderIcon(fi);
2511        }
2512        folder.animateClosed();
2513
2514        // Notify the accessibility manager that this folder "window" has disappeard and no
2515        // longer occludeds the workspace items
2516        getDragLayer().sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
2517    }
2518
2519    public boolean onLongClick(View v) {
2520        if (!isDraggingEnabled()) return false;
2521        if (isWorkspaceLocked()) return false;
2522        if (mState != State.WORKSPACE) return false;
2523
2524        if (!(v instanceof CellLayout)) {
2525            v = (View) v.getParent().getParent();
2526        }
2527
2528        resetAddInfo();
2529        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
2530        // This happens when long clicking an item with the dpad/trackball
2531        if (longClickCellInfo == null) {
2532            return true;
2533        }
2534
2535        // The hotseat touch handling does not go through Workspace, and we always allow long press
2536        // on hotseat items.
2537        final View itemUnderLongClick = longClickCellInfo.cell;
2538        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
2539        if (allowLongPress && !mDragController.isDragging()) {
2540            if (itemUnderLongClick == null) {
2541                if (mWorkspace.hasNonCustomEmptyScreens()) {
2542                    // User long pressed on empty space
2543                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2544                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2545                    // Disabling reordering until we sort out some issues.
2546                    if (mWorkspace.isInOverviewMode()) {
2547                        mWorkspace.startReordering(v);
2548                    } else {
2549                        mWorkspace.enterOverviewMode();
2550                    }
2551                }
2552            } else {
2553                if (!(itemUnderLongClick instanceof Folder)) {
2554                    // User long pressed on an item
2555                    mWorkspace.startDrag(longClickCellInfo);
2556                }
2557            }
2558        }
2559        return true;
2560    }
2561
2562    boolean isHotseatLayout(View layout) {
2563        return mHotseat != null && layout != null &&
2564                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
2565    }
2566    Hotseat getHotseat() {
2567        return mHotseat;
2568    }
2569    View getOverviewPanel() {
2570        return mOverviewPanel;
2571    }
2572    SearchDropTargetBar getSearchBar() {
2573        return mSearchDropTargetBar;
2574    }
2575
2576    /**
2577     * Returns the CellLayout of the specified container at the specified screen.
2578     */
2579    CellLayout getCellLayout(long container, long screenId) {
2580        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
2581            if (mHotseat != null) {
2582                return mHotseat.getLayout();
2583            } else {
2584                return null;
2585            }
2586        } else {
2587            return (CellLayout) mWorkspace.getScreenWithId(screenId);
2588        }
2589    }
2590
2591    Workspace getWorkspace() {
2592        return mWorkspace;
2593    }
2594
2595    public boolean isAllAppsVisible() {
2596        return (mState == State.APPS_CUSTOMIZE) || (mOnResumeState == State.APPS_CUSTOMIZE);
2597    }
2598
2599    /**
2600     * Helper method for the cameraZoomIn/cameraZoomOut animations
2601     * @param view The view being animated
2602     * @param scaleFactor The scale factor used for the zoom
2603     */
2604    private void setPivotsForZoom(View view, float scaleFactor) {
2605        view.setPivotX(view.getWidth() / 2.0f);
2606        view.setPivotY(view.getHeight() / 2.0f);
2607    }
2608
2609    void disableWallpaperIfInAllApps() {
2610        // Only disable it if we are in all apps
2611        if (isAllAppsVisible()) {
2612            if (mAppsCustomizeTabHost != null &&
2613                    !mAppsCustomizeTabHost.isTransitioning()) {
2614                updateWallpaperVisibility(false);
2615            }
2616        }
2617    }
2618
2619    private void setWorkspaceBackground(boolean workspace) {
2620        mLauncherView.setBackground(workspace ?
2621                mWorkspaceBackgroundDrawable : null);
2622    }
2623
2624    void updateWallpaperVisibility(boolean visible) {
2625        int wpflags = visible ? WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER : 0;
2626        int curflags = getWindow().getAttributes().flags
2627                & WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
2628        if (wpflags != curflags) {
2629            getWindow().setFlags(wpflags, WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
2630        }
2631        setWorkspaceBackground(visible);
2632    }
2633
2634    private void dispatchOnLauncherTransitionPrepare(View v, boolean animated, boolean toWorkspace) {
2635        if (v instanceof LauncherTransitionable) {
2636            ((LauncherTransitionable) v).onLauncherTransitionPrepare(this, animated, toWorkspace);
2637        }
2638    }
2639
2640    private void dispatchOnLauncherTransitionStart(View v, boolean animated, boolean toWorkspace) {
2641        if (v instanceof LauncherTransitionable) {
2642            ((LauncherTransitionable) v).onLauncherTransitionStart(this, animated, toWorkspace);
2643        }
2644
2645        // Update the workspace transition step as well
2646        dispatchOnLauncherTransitionStep(v, 0f);
2647    }
2648
2649    private void dispatchOnLauncherTransitionStep(View v, float t) {
2650        if (v instanceof LauncherTransitionable) {
2651            ((LauncherTransitionable) v).onLauncherTransitionStep(this, t);
2652        }
2653    }
2654
2655    private void dispatchOnLauncherTransitionEnd(View v, boolean animated, boolean toWorkspace) {
2656        if (v instanceof LauncherTransitionable) {
2657            ((LauncherTransitionable) v).onLauncherTransitionEnd(this, animated, toWorkspace);
2658        }
2659
2660        // Update the workspace transition step as well
2661        dispatchOnLauncherTransitionStep(v, 1f);
2662    }
2663
2664    /**
2665     * Things to test when changing the following seven functions.
2666     *   - Home from workspace
2667     *          - from center screen
2668     *          - from other screens
2669     *   - Home from all apps
2670     *          - from center screen
2671     *          - from other screens
2672     *   - Back from all apps
2673     *          - from center screen
2674     *          - from other screens
2675     *   - Launch app from workspace and quit
2676     *          - with back
2677     *          - with home
2678     *   - Launch app from all apps and quit
2679     *          - with back
2680     *          - with home
2681     *   - Go to a screen that's not the default, then all
2682     *     apps, and launch and app, and go back
2683     *          - with back
2684     *          -with home
2685     *   - On workspace, long press power and go back
2686     *          - with back
2687     *          - with home
2688     *   - On all apps, long press power and go back
2689     *          - with back
2690     *          - with home
2691     *   - On workspace, power off
2692     *   - On all apps, power off
2693     *   - Launch an app and turn off the screen while in that app
2694     *          - Go back with home key
2695     *          - Go back with back key  TODO: make this not go to workspace
2696     *          - From all apps
2697     *          - From workspace
2698     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2699     *          - From all apps
2700     *          - From the center workspace
2701     *          - From another workspace
2702     */
2703
2704    /**
2705     * Zoom the camera out from the workspace to reveal 'toView'.
2706     * Assumes that the view to show is anchored at either the very top or very bottom
2707     * of the screen.
2708     */
2709    private void showAppsCustomizeHelper(final boolean animated, final boolean springLoaded) {
2710        if (mStateAnimation != null) {
2711            mStateAnimation.setDuration(0);
2712            mStateAnimation.cancel();
2713            mStateAnimation = null;
2714        }
2715        final Resources res = getResources();
2716
2717        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2718        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2719        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2720        final View fromView = mWorkspace;
2721        final AppsCustomizeTabHost toView = mAppsCustomizeTabHost;
2722        final int startDelay =
2723                res.getInteger(R.integer.config_workspaceAppsCustomizeAnimationStagger);
2724
2725        setPivotsForZoom(toView, scale);
2726
2727        // Shrink workspaces away if going to AppsCustomize from workspace
2728        Animator workspaceAnim =
2729                mWorkspace.getChangeStateAnimation(Workspace.State.SMALL, animated);
2730
2731        if (animated) {
2732            toView.setScaleX(scale);
2733            toView.setScaleY(scale);
2734            final LauncherViewPropertyAnimator scaleAnim = new LauncherViewPropertyAnimator(toView);
2735            scaleAnim.
2736                scaleX(1f).scaleY(1f).
2737                setDuration(duration).
2738                setInterpolator(new Workspace.ZoomOutInterpolator());
2739
2740            toView.setVisibility(View.VISIBLE);
2741            toView.setAlpha(0f);
2742            final ObjectAnimator alphaAnim = LauncherAnimUtils
2743                .ofFloat(toView, "alpha", 0f, 1f)
2744                .setDuration(fadeDuration);
2745            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2746            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2747                @Override
2748                public void onAnimationUpdate(ValueAnimator animation) {
2749                    if (animation == null) {
2750                        throw new RuntimeException("animation is null");
2751                    }
2752                    float t = (Float) animation.getAnimatedValue();
2753                    dispatchOnLauncherTransitionStep(fromView, t);
2754                    dispatchOnLauncherTransitionStep(toView, t);
2755                }
2756            });
2757
2758            // toView should appear right at the end of the workspace shrink
2759            // animation
2760            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2761            mStateAnimation.play(scaleAnim).after(startDelay);
2762            mStateAnimation.play(alphaAnim).after(startDelay);
2763
2764            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2765                boolean animationCancelled = false;
2766
2767                @Override
2768                public void onAnimationStart(Animator animation) {
2769                    updateWallpaperVisibility(true);
2770                    // Prepare the position
2771                    toView.setTranslationX(0.0f);
2772                    toView.setTranslationY(0.0f);
2773                    toView.setVisibility(View.VISIBLE);
2774                    toView.bringToFront();
2775                }
2776                @Override
2777                public void onAnimationEnd(Animator animation) {
2778                    dispatchOnLauncherTransitionEnd(fromView, animated, false);
2779                    dispatchOnLauncherTransitionEnd(toView, animated, false);
2780
2781                    if (!animationCancelled) {
2782                        updateWallpaperVisibility(false);
2783                    }
2784
2785                    // Hide the search bar
2786                    if (mSearchDropTargetBar != null) {
2787                        mSearchDropTargetBar.hideSearchBar(false);
2788                    }
2789                }
2790
2791                @Override
2792                public void onAnimationCancel(Animator animation) {
2793                    animationCancelled = true;
2794                }
2795            });
2796
2797            if (workspaceAnim != null) {
2798                mStateAnimation.play(workspaceAnim);
2799            }
2800
2801            boolean delayAnim = false;
2802
2803            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2804            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2805
2806            // If any of the objects being animated haven't been measured/laid out
2807            // yet, delay the animation until we get a layout pass
2808            if ((((LauncherTransitionable) toView).getContent().getMeasuredWidth() == 0) ||
2809                    (mWorkspace.getMeasuredWidth() == 0) ||
2810                    (toView.getMeasuredWidth() == 0)) {
2811                delayAnim = true;
2812            }
2813
2814            final AnimatorSet stateAnimation = mStateAnimation;
2815            final Runnable startAnimRunnable = new Runnable() {
2816                public void run() {
2817                    // Check that mStateAnimation hasn't changed while
2818                    // we waited for a layout/draw pass
2819                    if (mStateAnimation != stateAnimation)
2820                        return;
2821                    setPivotsForZoom(toView, scale);
2822                    dispatchOnLauncherTransitionStart(fromView, animated, false);
2823                    dispatchOnLauncherTransitionStart(toView, animated, false);
2824                    LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
2825                }
2826            };
2827            if (delayAnim) {
2828                final ViewTreeObserver observer = toView.getViewTreeObserver();
2829                observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
2830                        public void onGlobalLayout() {
2831                            startAnimRunnable.run();
2832                            toView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
2833                        }
2834                    });
2835            } else {
2836                startAnimRunnable.run();
2837            }
2838        } else {
2839            toView.setTranslationX(0.0f);
2840            toView.setTranslationY(0.0f);
2841            toView.setScaleX(1.0f);
2842            toView.setScaleY(1.0f);
2843            toView.setVisibility(View.VISIBLE);
2844            toView.bringToFront();
2845
2846            if (!springLoaded && !LauncherAppState.getInstance().isScreenLarge()) {
2847                // Hide the search bar
2848                if (mSearchDropTargetBar != null) {
2849                    mSearchDropTargetBar.hideSearchBar(false);
2850                }
2851            }
2852            dispatchOnLauncherTransitionPrepare(fromView, animated, false);
2853            dispatchOnLauncherTransitionStart(fromView, animated, false);
2854            dispatchOnLauncherTransitionEnd(fromView, animated, false);
2855            dispatchOnLauncherTransitionPrepare(toView, animated, false);
2856            dispatchOnLauncherTransitionStart(toView, animated, false);
2857            dispatchOnLauncherTransitionEnd(toView, animated, false);
2858            updateWallpaperVisibility(false);
2859        }
2860    }
2861
2862    /**
2863     * Zoom the camera back into the workspace, hiding 'fromView'.
2864     * This is the opposite of showAppsCustomizeHelper.
2865     * @param animated If true, the transition will be animated.
2866     */
2867    private void hideAppsCustomizeHelper(State toState, final boolean animated,
2868            final boolean springLoaded, final Runnable onCompleteRunnable) {
2869
2870        if (mStateAnimation != null) {
2871            mStateAnimation.setDuration(0);
2872            mStateAnimation.cancel();
2873            mStateAnimation = null;
2874        }
2875        Resources res = getResources();
2876
2877        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2878        final int fadeOutDuration =
2879                res.getInteger(R.integer.config_appsCustomizeFadeOutTime);
2880        final float scaleFactor = (float)
2881                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2882        final View fromView = mAppsCustomizeTabHost;
2883        final View toView = mWorkspace;
2884        Animator workspaceAnim = null;
2885        if (toState == State.WORKSPACE) {
2886            int stagger = res.getInteger(R.integer.config_appsCustomizeWorkspaceAnimationStagger);
2887            workspaceAnim = mWorkspace.getChangeStateAnimation(
2888                    Workspace.State.NORMAL, animated, stagger, -1);
2889        } else if (toState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2890            workspaceAnim = mWorkspace.getChangeStateAnimation(
2891                    Workspace.State.SPRING_LOADED, animated);
2892        }
2893
2894        setPivotsForZoom(fromView, scaleFactor);
2895        updateWallpaperVisibility(true);
2896        showHotseat(animated);
2897        if (animated) {
2898            final LauncherViewPropertyAnimator scaleAnim =
2899                    new LauncherViewPropertyAnimator(fromView);
2900            scaleAnim.
2901                scaleX(scaleFactor).scaleY(scaleFactor).
2902                setDuration(duration).
2903                setInterpolator(new Workspace.ZoomInInterpolator());
2904
2905            final ObjectAnimator alphaAnim = LauncherAnimUtils
2906                .ofFloat(fromView, "alpha", 1f, 0f)
2907                .setDuration(fadeOutDuration);
2908            alphaAnim.setInterpolator(new AccelerateDecelerateInterpolator());
2909            alphaAnim.addUpdateListener(new AnimatorUpdateListener() {
2910                @Override
2911                public void onAnimationUpdate(ValueAnimator animation) {
2912                    float t = 1f - (Float) animation.getAnimatedValue();
2913                    dispatchOnLauncherTransitionStep(fromView, t);
2914                    dispatchOnLauncherTransitionStep(toView, t);
2915                }
2916            });
2917
2918            mStateAnimation = LauncherAnimUtils.createAnimatorSet();
2919
2920            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2921            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2922            mAppsCustomizeContent.pauseScrolling();
2923
2924            mStateAnimation.addListener(new AnimatorListenerAdapter() {
2925                @Override
2926                public void onAnimationEnd(Animator animation) {
2927                    updateWallpaperVisibility(true);
2928                    fromView.setVisibility(View.GONE);
2929                    dispatchOnLauncherTransitionEnd(fromView, animated, true);
2930                    dispatchOnLauncherTransitionEnd(toView, animated, true);
2931                    if (onCompleteRunnable != null) {
2932                        onCompleteRunnable.run();
2933                    }
2934                    mAppsCustomizeContent.updateCurrentPageScroll();
2935                    mAppsCustomizeContent.resumeScrolling();
2936                }
2937            });
2938
2939            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2940            if (workspaceAnim != null) {
2941                mStateAnimation.play(workspaceAnim);
2942            }
2943            dispatchOnLauncherTransitionStart(fromView, animated, true);
2944            dispatchOnLauncherTransitionStart(toView, animated, true);
2945            LauncherAnimUtils.startAnimationAfterNextDraw(mStateAnimation, toView);
2946        } else {
2947            fromView.setVisibility(View.GONE);
2948            dispatchOnLauncherTransitionPrepare(fromView, animated, true);
2949            dispatchOnLauncherTransitionStart(fromView, animated, true);
2950            dispatchOnLauncherTransitionEnd(fromView, animated, true);
2951            dispatchOnLauncherTransitionPrepare(toView, animated, true);
2952            dispatchOnLauncherTransitionStart(toView, animated, true);
2953            dispatchOnLauncherTransitionEnd(toView, animated, true);
2954        }
2955    }
2956
2957    @Override
2958    public void onTrimMemory(int level) {
2959        super.onTrimMemory(level);
2960        if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
2961            mAppsCustomizeTabHost.onTrimMemory();
2962        }
2963    }
2964
2965    @Override
2966    public void onWindowFocusChanged(boolean hasFocus) {
2967        if (!hasFocus) {
2968            // When another window occludes launcher (like the notification shade, or recents),
2969            // ensure that we enable the wallpaper flag so that transitions are done correctly.
2970            updateWallpaperVisibility(true);
2971        } else {
2972            // When launcher has focus again, disable the wallpaper if we are in AllApps
2973            mWorkspace.postDelayed(new Runnable() {
2974                @Override
2975                public void run() {
2976                    disableWallpaperIfInAllApps();
2977                }
2978            }, 500);
2979        }
2980    }
2981
2982    void showWorkspace(boolean animated) {
2983        showWorkspace(animated, null);
2984    }
2985
2986    void showWorkspace(boolean animated, Runnable onCompleteRunnable) {
2987        if (mState != State.WORKSPACE) {
2988            boolean wasInSpringLoadedMode = (mState == State.APPS_CUSTOMIZE_SPRING_LOADED);
2989            mWorkspace.setVisibility(View.VISIBLE);
2990            hideAppsCustomizeHelper(State.WORKSPACE, animated, false, onCompleteRunnable);
2991
2992            // Show the search bar (only animate if we were showing the drop target bar in spring
2993            // loaded mode)
2994            if (mSearchDropTargetBar != null) {
2995                mSearchDropTargetBar.showSearchBar(wasInSpringLoadedMode);
2996            }
2997
2998            // Set focus to the AppsCustomize button
2999            if (mAllAppsButton != null) {
3000                mAllAppsButton.requestFocus();
3001            }
3002        }
3003
3004        // Change the state *after* we've called all the transition code
3005        mState = State.WORKSPACE;
3006
3007        // Resume the auto-advance of widgets
3008        mUserPresent = true;
3009        updateRunning();
3010
3011        // Send an accessibility event to announce the context change
3012        getWindow().getDecorView()
3013                .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3014
3015        onWorkspaceShown(animated);
3016    }
3017
3018    public void onWorkspaceShown(boolean animated) {
3019    }
3020
3021    void showAllApps(boolean animated) {
3022        if (mState != State.WORKSPACE) return;
3023
3024        showAppsCustomizeHelper(animated, false);
3025        mAppsCustomizeTabHost.requestFocus();
3026
3027        // Change the state *after* we've called all the transition code
3028        mState = State.APPS_CUSTOMIZE;
3029
3030        // Pause the auto-advance of widgets until we are out of AllApps
3031        mUserPresent = false;
3032        updateRunning();
3033        closeFolder();
3034
3035        // Send an accessibility event to announce the context change
3036        getWindow().getDecorView()
3037                .sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
3038    }
3039
3040    void enterSpringLoadedDragMode() {
3041        if (isAllAppsVisible()) {
3042            hideAppsCustomizeHelper(State.APPS_CUSTOMIZE_SPRING_LOADED, true, true, null);
3043            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
3044        }
3045    }
3046
3047    void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay,
3048            final Runnable onCompleteRunnable) {
3049        if (mState != State.APPS_CUSTOMIZE_SPRING_LOADED) return;
3050
3051        mHandler.postDelayed(new Runnable() {
3052            @Override
3053            public void run() {
3054                if (successfulDrop) {
3055                    // Before we show workspace, hide all apps again because
3056                    // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
3057                    // clean up our state transition functions
3058                    mAppsCustomizeTabHost.setVisibility(View.GONE);
3059                    showWorkspace(true, onCompleteRunnable);
3060                } else {
3061                    exitSpringLoadedDragMode();
3062                }
3063            }
3064        }, (extendedDelay ?
3065                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
3066                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
3067    }
3068
3069    void exitSpringLoadedDragMode() {
3070        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
3071            final boolean animated = true;
3072            final boolean springLoaded = true;
3073            showAppsCustomizeHelper(animated, springLoaded);
3074            mState = State.APPS_CUSTOMIZE;
3075        }
3076        // Otherwise, we are not in spring loaded mode, so don't do anything.
3077    }
3078
3079    void lockAllApps() {
3080        // TODO
3081    }
3082
3083    void unlockAllApps() {
3084        // TODO
3085    }
3086
3087    /**
3088     * Shows the hotseat area.
3089     */
3090    void showHotseat(boolean animated) {
3091        if (!LauncherAppState.getInstance().isScreenLarge()) {
3092            if (animated) {
3093                if (mHotseat.getAlpha() != 1f) {
3094                    int duration = 0;
3095                    if (mSearchDropTargetBar != null) {
3096                        duration = mSearchDropTargetBar.getTransitionInDuration();
3097                    }
3098                    mHotseat.animate().alpha(1f).setDuration(duration);
3099                }
3100            } else {
3101                mHotseat.setAlpha(1f);
3102            }
3103        }
3104    }
3105
3106    /**
3107     * Hides the hotseat area.
3108     */
3109    void hideHotseat(boolean animated) {
3110        if (!LauncherAppState.getInstance().isScreenLarge()) {
3111            if (animated) {
3112                if (mHotseat.getAlpha() != 0f) {
3113                    int duration = 0;
3114                    if (mSearchDropTargetBar != null) {
3115                        duration = mSearchDropTargetBar.getTransitionOutDuration();
3116                    }
3117                    mHotseat.animate().alpha(0f).setDuration(duration);
3118                }
3119            } else {
3120                mHotseat.setAlpha(0f);
3121            }
3122        }
3123    }
3124
3125    /**
3126     * Add an item from all apps or customize onto the given workspace screen.
3127     * If layout is null, add to the current screen.
3128     */
3129    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
3130        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
3131            showOutOfSpaceMessage(isHotseatLayout(layout));
3132        }
3133    }
3134
3135    /** Maps the current orientation to an index for referencing orientation correct global icons */
3136    private int getCurrentOrientationIndexForGlobalIcons() {
3137        // default - 0, landscape - 1
3138        switch (getResources().getConfiguration().orientation) {
3139        case Configuration.ORIENTATION_LANDSCAPE:
3140            return 1;
3141        default:
3142            return 0;
3143        }
3144    }
3145
3146    private Drawable getExternalPackageToolbarIcon(ComponentName activityName, String resourceName) {
3147        try {
3148            PackageManager packageManager = getPackageManager();
3149            // Look for the toolbar icon specified in the activity meta-data
3150            Bundle metaData = packageManager.getActivityInfo(
3151                    activityName, PackageManager.GET_META_DATA).metaData;
3152            if (metaData != null) {
3153                int iconResId = metaData.getInt(resourceName);
3154                if (iconResId != 0) {
3155                    Resources res = packageManager.getResourcesForActivity(activityName);
3156                    return res.getDrawable(iconResId);
3157                }
3158            }
3159        } catch (NameNotFoundException e) {
3160            // This can happen if the activity defines an invalid drawable
3161            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
3162                    " not found", e);
3163        } catch (Resources.NotFoundException nfe) {
3164            // This can happen if the activity defines an invalid drawable
3165            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
3166                    nfe);
3167        }
3168        return null;
3169    }
3170
3171    // if successful in getting icon, return it; otherwise, set button to use default drawable
3172    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
3173            int buttonId, ComponentName activityName, int fallbackDrawableId,
3174            String toolbarResourceName) {
3175        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
3176        Resources r = getResources();
3177        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
3178        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
3179
3180        TextView button = (TextView) findViewById(buttonId);
3181        // If we were unable to find the icon via the meta-data, use a generic one
3182        if (toolbarIcon == null) {
3183            toolbarIcon = r.getDrawable(fallbackDrawableId);
3184            toolbarIcon.setBounds(0, 0, w, h);
3185            if (button != null) {
3186                button.setCompoundDrawables(toolbarIcon, null, null, null);
3187            }
3188            return null;
3189        } else {
3190            toolbarIcon.setBounds(0, 0, w, h);
3191            if (button != null) {
3192                button.setCompoundDrawables(toolbarIcon, null, null, null);
3193            }
3194            return toolbarIcon.getConstantState();
3195        }
3196    }
3197
3198    // if successful in getting icon, return it; otherwise, set button to use default drawable
3199    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
3200            int buttonId, ComponentName activityName, int fallbackDrawableId,
3201            String toolbarResourceName) {
3202        ImageView button = (ImageView) findViewById(buttonId);
3203        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName, toolbarResourceName);
3204
3205        if (button != null) {
3206            // If we were unable to find the icon via the meta-data, use a
3207            // generic one
3208            if (toolbarIcon == null) {
3209                button.setImageResource(fallbackDrawableId);
3210            } else {
3211                button.setImageDrawable(toolbarIcon);
3212            }
3213        }
3214
3215        return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
3216
3217    }
3218
3219    private void updateTextButtonWithDrawable(int buttonId, Drawable d) {
3220        TextView button = (TextView) findViewById(buttonId);
3221        button.setCompoundDrawables(d, null, null, null);
3222    }
3223
3224    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
3225        ImageView button = (ImageView) findViewById(buttonId);
3226        button.setImageDrawable(d.newDrawable(getResources()));
3227    }
3228
3229    private void invalidatePressedFocusedStates(View container, View button) {
3230        if (container instanceof HolographicLinearLayout) {
3231            HolographicLinearLayout layout = (HolographicLinearLayout) container;
3232            layout.invalidatePressedFocusedStates();
3233        } else if (button instanceof HolographicImageView) {
3234            HolographicImageView view = (HolographicImageView) button;
3235            view.invalidatePressedFocusedStates();
3236        }
3237    }
3238
3239    public View getQsbBar() {
3240        if (mQsbBar == null) {
3241            mQsbBar = mInflater.inflate(R.layout.qsb_bar, mSearchDropTargetBar);
3242        }
3243        return mQsbBar;
3244    }
3245
3246    protected boolean updateGlobalSearchIcon() {
3247        final View searchButtonContainer = findViewById(R.id.search_button_container);
3248        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
3249        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3250        final View voiceButton = findViewById(R.id.voice_button);
3251
3252        final SearchManager searchManager =
3253                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3254        ComponentName activityName = searchManager.getGlobalSearchActivity();
3255        if (activityName != null) {
3256            int coi = getCurrentOrientationIndexForGlobalIcons();
3257            sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3258                    R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3259                    TOOLBAR_SEARCH_ICON_METADATA_NAME);
3260            if (sGlobalSearchIcon[coi] == null) {
3261                sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3262                        R.id.search_button, activityName, R.drawable.ic_home_search_normal_holo,
3263                        TOOLBAR_ICON_METADATA_NAME);
3264            }
3265
3266            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.VISIBLE);
3267            searchButton.setVisibility(View.VISIBLE);
3268            invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3269            return true;
3270        } else {
3271            // We disable both search and voice search when there is no global search provider
3272            if (searchButtonContainer != null) searchButtonContainer.setVisibility(View.GONE);
3273            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3274            searchButton.setVisibility(View.GONE);
3275            voiceButton.setVisibility(View.GONE);
3276            setVoiceButtonProxyVisible(false);
3277            return false;
3278        }
3279    }
3280
3281    protected void updateGlobalSearchIcon(Drawable.ConstantState d) {
3282        final View searchButtonContainer = findViewById(R.id.search_button_container);
3283        final View searchButton = (ImageView) findViewById(R.id.search_button);
3284        updateButtonWithDrawable(R.id.search_button, d);
3285        invalidatePressedFocusedStates(searchButtonContainer, searchButton);
3286    }
3287
3288    protected boolean updateVoiceSearchIcon(boolean searchVisible) {
3289        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3290        final View voiceButton = findViewById(R.id.voice_button);
3291
3292        // We only show/update the voice search icon if the search icon is enabled as well
3293        final SearchManager searchManager =
3294                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3295        ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
3296
3297        ComponentName activityName = null;
3298        if (globalSearchActivity != null) {
3299            // Check if the global search activity handles voice search
3300            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3301            intent.setPackage(globalSearchActivity.getPackageName());
3302            activityName = intent.resolveActivity(getPackageManager());
3303        }
3304
3305        if (activityName == null) {
3306            // Fallback: check if an activity other than the global search activity
3307            // resolves this
3308            Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3309            activityName = intent.resolveActivity(getPackageManager());
3310        }
3311        if (searchVisible && activityName != null) {
3312            int coi = getCurrentOrientationIndexForGlobalIcons();
3313            sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3314                    R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3315                    TOOLBAR_VOICE_SEARCH_ICON_METADATA_NAME);
3316            if (sVoiceSearchIcon[coi] == null) {
3317                sVoiceSearchIcon[coi] = updateButtonWithIconFromExternalActivity(
3318                        R.id.voice_button, activityName, R.drawable.ic_home_voice_search_holo,
3319                        TOOLBAR_ICON_METADATA_NAME);
3320            }
3321            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.VISIBLE);
3322            voiceButton.setVisibility(View.VISIBLE);
3323            setVoiceButtonProxyVisible(true);
3324            invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3325            return true;
3326        } else {
3327            if (voiceButtonContainer != null) voiceButtonContainer.setVisibility(View.GONE);
3328            voiceButton.setVisibility(View.GONE);
3329            setVoiceButtonProxyVisible(false);
3330            return false;
3331        }
3332    }
3333
3334    protected void updateVoiceSearchIcon(Drawable.ConstantState d) {
3335        final View voiceButtonContainer = findViewById(R.id.voice_button_container);
3336        final View voiceButton = findViewById(R.id.voice_button);
3337        updateButtonWithDrawable(R.id.voice_button, d);
3338        invalidatePressedFocusedStates(voiceButtonContainer, voiceButton);
3339    }
3340
3341    public void setVoiceButtonProxyVisible(boolean visible) {
3342        final View voiceButtonProxy = findViewById(R.id.voice_button_proxy);
3343        if (voiceButtonProxy != null) {
3344            voiceButtonProxy.setVisibility(visible ? View.VISIBLE : View.GONE);
3345        }
3346    }
3347    /**
3348     * Sets the app market icon
3349     */
3350    private void updateAppMarketIcon() {
3351        final View marketButton = findViewById(R.id.market_button);
3352        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
3353        // Find the app market activity by resolving an intent.
3354        // (If multiple app markets are installed, it will return the ResolverActivity.)
3355        ComponentName activityName = intent.resolveActivity(getPackageManager());
3356        if (activityName != null) {
3357            int coi = getCurrentOrientationIndexForGlobalIcons();
3358            mAppMarketIntent = intent;
3359            sAppMarketIcon[coi] = updateTextButtonWithIconFromExternalActivity(
3360                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo,
3361                    TOOLBAR_ICON_METADATA_NAME);
3362            marketButton.setVisibility(View.VISIBLE);
3363        } else {
3364            // We should hide and disable the view so that we don't try and restore the visibility
3365            // of it when we swap between drag & normal states from IconDropTarget subclasses.
3366            marketButton.setVisibility(View.GONE);
3367            marketButton.setEnabled(false);
3368        }
3369    }
3370
3371    private void updateAppMarketIcon(Drawable.ConstantState d) {
3372        // Ensure that the new drawable we are creating has the approprate toolbar icon bounds
3373        Resources r = getResources();
3374        Drawable marketIconDrawable = d.newDrawable(r);
3375        int w = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_width);
3376        int h = r.getDimensionPixelSize(R.dimen.toolbar_external_icon_height);
3377        marketIconDrawable.setBounds(0, 0, w, h);
3378
3379        updateTextButtonWithDrawable(R.id.market_button, marketIconDrawable);
3380    }
3381
3382    @Override
3383    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
3384        final boolean result = super.dispatchPopulateAccessibilityEvent(event);
3385        final List<CharSequence> text = event.getText();
3386        text.clear();
3387        // Populate event with a fake title based on the current state.
3388        if (mState == State.APPS_CUSTOMIZE) {
3389            text.add(getString(R.string.all_apps_button_label));
3390        } else {
3391            text.add(getString(R.string.all_apps_home_button_label));
3392        }
3393        return result;
3394    }
3395
3396    /**
3397     * Receives notifications when system dialogs are to be closed.
3398     */
3399    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3400        @Override
3401        public void onReceive(Context context, Intent intent) {
3402            closeSystemDialogs();
3403        }
3404    }
3405
3406    /**
3407     * Receives notifications whenever the appwidgets are reset.
3408     */
3409    private class AppWidgetResetObserver extends ContentObserver {
3410        public AppWidgetResetObserver() {
3411            super(new Handler());
3412        }
3413
3414        @Override
3415        public void onChange(boolean selfChange) {
3416            onAppWidgetReset();
3417        }
3418    }
3419
3420    /**
3421     * If the activity is currently paused, signal that we need to run the passed Runnable
3422     * in onResume.
3423     *
3424     * This needs to be called from incoming places where resources might have been loaded
3425     * while we are paused.  That is becaues the Configuration might be wrong
3426     * when we're not running, and if it comes back to what it was when we
3427     * were paused, we are not restarted.
3428     *
3429     * Implementation of the method from LauncherModel.Callbacks.
3430     *
3431     * @return true if we are currently paused.  The caller might be able to
3432     * skip some work in that case since we will come back again.
3433     */
3434    private boolean waitUntilResume(Runnable run, boolean deletePreviousRunnables) {
3435        if (mPaused) {
3436            Log.i(TAG, "Deferring update until onResume");
3437            if (deletePreviousRunnables) {
3438                while (mBindOnResumeCallbacks.remove(run)) {
3439                }
3440            }
3441            mBindOnResumeCallbacks.add(run);
3442            return true;
3443        } else {
3444            return false;
3445        }
3446    }
3447
3448    private boolean waitUntilResume(Runnable run) {
3449        return waitUntilResume(run, false);
3450    }
3451
3452    public void addOnResumeCallback(Runnable run) {
3453        mOnResumeCallbacks.add(run);
3454    }
3455
3456    /**
3457     * If the activity is currently paused, signal that we need to re-run the loader
3458     * in onResume.
3459     *
3460     * This needs to be called from incoming places where resources might have been loaded
3461     * while we are paused.  That is becaues the Configuration might be wrong
3462     * when we're not running, and if it comes back to what it was when we
3463     * were paused, we are not restarted.
3464     *
3465     * Implementation of the method from LauncherModel.Callbacks.
3466     *
3467     * @return true if we are currently paused.  The caller might be able to
3468     * skip some work in that case since we will come back again.
3469     */
3470    public boolean setLoadOnResume() {
3471        if (mPaused) {
3472            Log.i(TAG, "setLoadOnResume");
3473            mOnResumeNeedsLoad = true;
3474            return true;
3475        } else {
3476            return false;
3477        }
3478    }
3479
3480    /**
3481     * Implementation of the method from LauncherModel.Callbacks.
3482     */
3483    public int getCurrentWorkspaceScreen() {
3484        if (mWorkspace != null) {
3485            return mWorkspace.getCurrentPage();
3486        } else {
3487            return SCREEN_COUNT / 2;
3488        }
3489    }
3490
3491    /**
3492     * Refreshes the shortcuts shown on the workspace.
3493     *
3494     * Implementation of the method from LauncherModel.Callbacks.
3495     */
3496    public void startBinding() {
3497        // If we're starting binding all over again, clear any bind calls we'd postponed in
3498        // the past (see waitUntilResume) -- we don't need them since we're starting binding
3499        // from scratch again
3500        mBindOnResumeCallbacks.clear();
3501
3502        // Clear the workspace because it's going to be rebound
3503        mWorkspace.clearDropTargets();
3504        mWorkspace.removeAllWorkspaceScreens();
3505
3506        mWidgetsToAdvance.clear();
3507        if (mHotseat != null) {
3508            mHotseat.resetLayout();
3509        }
3510    }
3511
3512    @Override
3513    public void bindScreens(ArrayList<Long> orderedScreenIds) {
3514        bindAddScreens(orderedScreenIds);
3515
3516        // Create the new empty page
3517        mWorkspace.addExtraEmptyScreen();
3518
3519        // Create the custom content page (this call updates mDefaultScreen which calls
3520        // setCurrentPage() so ensure that all pages are added before calling this)
3521        if (!mWorkspace.hasCustomContent() && hasCustomContentToLeft()) {
3522            mWorkspace.createCustomContentPage();
3523        }
3524    }
3525
3526    @Override
3527    public void bindAddScreens(ArrayList<Long> orderedScreenIds) {
3528        int count = orderedScreenIds.size();
3529        for (int i = 0; i < count; i++) {
3530            Log.w(TAG, "10249126 - bindAddScreens(" + orderedScreenIds.get(i) + ")");
3531            mWorkspace.insertNewWorkspaceScreenBeforeEmptyScreen(orderedScreenIds.get(i));
3532        }
3533    }
3534
3535    private boolean shouldShowWeightWatcher() {
3536        String spKey = LauncherAppState.getSharedPreferencesKey();
3537        SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3538        boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, SHOW_WEIGHT_WATCHER_DEFAULT);
3539
3540        return show;
3541    }
3542
3543    private void toggleShowWeightWatcher() {
3544        String spKey = LauncherAppState.getSharedPreferencesKey();
3545        SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_PRIVATE);
3546        boolean show = sp.getBoolean(SHOW_WEIGHT_WATCHER, true);
3547
3548        show = !show;
3549
3550        SharedPreferences.Editor editor = sp.edit();
3551        editor.putBoolean(SHOW_WEIGHT_WATCHER, show);
3552        editor.commit();
3553
3554        if (mWeightWatcher != null) {
3555            mWeightWatcher.setVisibility(show ? View.VISIBLE : View.GONE);
3556        }
3557    }
3558
3559    public void bindAppsAdded(final ArrayList<Long> newScreens,
3560                              final ArrayList<ItemInfo> addNotAnimated,
3561                              final ArrayList<ItemInfo> addAnimated) {
3562        Runnable r = new Runnable() {
3563            public void run() {
3564                bindAppsAdded(newScreens, addNotAnimated, addAnimated);
3565            }
3566        };
3567        if (waitUntilResume(r)) {
3568            return;
3569        }
3570
3571        Log.w(TAG, "10249126 - bindAppsAdded(" + newScreens.size() + ")");
3572
3573        // Add the new screens
3574        bindAddScreens(newScreens);
3575
3576        // We add the items without animation on non-visible pages, and with
3577        // animations on the new page (which we will try and snap to).
3578        if (!addNotAnimated.isEmpty()) {
3579            bindItems(addNotAnimated, 0,
3580                    addNotAnimated.size(), false);
3581        }
3582        if (!addAnimated.isEmpty()) {
3583            bindItems(addAnimated, 0,
3584                    addAnimated.size(), true);
3585        }
3586    }
3587
3588    /**
3589     * Bind the items start-end from the list.
3590     *
3591     * Implementation of the method from LauncherModel.Callbacks.
3592     */
3593    public void bindItems(final ArrayList<ItemInfo> shortcuts, final int start, final int end,
3594                          final boolean forceAnimateIcons) {
3595        Runnable r = new Runnable() {
3596            public void run() {
3597                bindItems(shortcuts, start, end, forceAnimateIcons);
3598            }
3599        };
3600        if (waitUntilResume(r)) {
3601            return;
3602        }
3603
3604        // Get the list of added shortcuts and intersect them with the set of shortcuts here
3605        final AnimatorSet anim = LauncherAnimUtils.createAnimatorSet();
3606        final Collection<Animator> bounceAnims = new ArrayList<Animator>();
3607        final boolean animateIcons = forceAnimateIcons && canRunNewAppsAnimation();
3608        Workspace workspace = mWorkspace;
3609        long newShortcutsScreenId = -1;
3610        for (int i = start; i < end; i++) {
3611            final ItemInfo item = shortcuts.get(i);
3612
3613            // Short circuit if we are loading dock items for a configuration which has no dock
3614            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
3615                    mHotseat == null) {
3616                continue;
3617            }
3618
3619            switch (item.itemType) {
3620                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3621                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3622                    ShortcutInfo info = (ShortcutInfo) item;
3623                    View shortcut = createShortcut(info);
3624
3625                    /*
3626                     * TODO: FIX collision case
3627                     */
3628                    if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) {
3629                        CellLayout cl = mWorkspace.getScreenWithId(item.screenId);
3630                        if (cl != null && cl.isOccupied(item.cellX, item.cellY)) {
3631                            throw new RuntimeException("OCCUPIED");
3632                        }
3633                    }
3634
3635                    workspace.addInScreenFromBind(shortcut, item.container, item.screenId, item.cellX,
3636                            item.cellY, 1, 1);
3637                    if (animateIcons) {
3638                        // Animate all the applications up now
3639                        shortcut.setAlpha(0f);
3640                        shortcut.setScaleX(0f);
3641                        shortcut.setScaleY(0f);
3642                        bounceAnims.add(createNewAppBounceAnimation(shortcut, i));
3643                        newShortcutsScreenId = item.screenId;
3644                    }
3645                    break;
3646                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3647                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3648                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3649                            (FolderInfo) item, mIconCache);
3650                    workspace.addInScreenFromBind(newFolder, item.container, item.screenId, item.cellX,
3651                            item.cellY, 1, 1);
3652                    break;
3653                default:
3654                    throw new RuntimeException("Invalid Item Type");
3655            }
3656        }
3657
3658        if (animateIcons) {
3659            // Animate to the correct page
3660            if (newShortcutsScreenId > -1) {
3661                long currentScreenId = mWorkspace.getScreenIdForPageIndex(mWorkspace.getNextPage());
3662                int newScreenIndex = mWorkspace.getPageIndexForScreenId(newShortcutsScreenId);
3663                if (newShortcutsScreenId != currentScreenId) {
3664                    mWorkspace.snapToPage(newScreenIndex);
3665                }
3666            }
3667
3668            // We post the animation slightly delayed to prevent slowdowns when we are loading
3669            // right after we return to launcher.
3670            mWorkspace.postDelayed(new Runnable() {
3671                public void run() {
3672                    anim.playTogether(bounceAnims);
3673                    anim.start();
3674                }
3675            }, NEW_APPS_ANIMATION_DELAY);
3676        }
3677        workspace.requestLayout();
3678    }
3679
3680    /**
3681     * Implementation of the method from LauncherModel.Callbacks.
3682     */
3683    public void bindFolders(final HashMap<Long, FolderInfo> folders) {
3684        Runnable r = new Runnable() {
3685            public void run() {
3686                bindFolders(folders);
3687            }
3688        };
3689        if (waitUntilResume(r)) {
3690            return;
3691        }
3692        sFolders.clear();
3693        sFolders.putAll(folders);
3694    }
3695
3696    /**
3697     * Add the views for a widget to the workspace.
3698     *
3699     * Implementation of the method from LauncherModel.Callbacks.
3700     */
3701    public void bindAppWidget(final LauncherAppWidgetInfo item) {
3702        Runnable r = new Runnable() {
3703            public void run() {
3704                bindAppWidget(item);
3705            }
3706        };
3707        if (waitUntilResume(r)) {
3708            return;
3709        }
3710
3711        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3712        if (DEBUG_WIDGETS) {
3713            Log.d(TAG, "bindAppWidget: " + item);
3714        }
3715        final Workspace workspace = mWorkspace;
3716
3717        final int appWidgetId = item.appWidgetId;
3718        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3719        if (DEBUG_WIDGETS) {
3720            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3721        }
3722
3723        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3724
3725        item.hostView.setTag(item);
3726        item.onBindAppWidget(this);
3727
3728        workspace.addInScreen(item.hostView, item.container, item.screenId, item.cellX,
3729                item.cellY, item.spanX, item.spanY, false);
3730        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3731
3732        workspace.requestLayout();
3733
3734        if (DEBUG_WIDGETS) {
3735            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3736                    + (SystemClock.uptimeMillis()-start) + "ms");
3737        }
3738    }
3739
3740    public void onPageBoundSynchronously(int page) {
3741        mSynchronouslyBoundPages.add(page);
3742    }
3743
3744    /**
3745     * Callback saying that there aren't any more items to bind.
3746     *
3747     * Implementation of the method from LauncherModel.Callbacks.
3748     */
3749    public void finishBindingItems(final boolean upgradePath) {
3750        Runnable r = new Runnable() {
3751            public void run() {
3752                finishBindingItems(upgradePath);
3753            }
3754        };
3755        if (waitUntilResume(r)) {
3756            return;
3757        }
3758        if (mSavedState != null) {
3759            if (!mWorkspace.hasFocus()) {
3760                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3761            }
3762            mSavedState = null;
3763        }
3764
3765        mWorkspace.restoreInstanceStateForRemainingPages();
3766
3767        // If we received the result of any pending adds while the loader was running (e.g. the
3768        // widget configuration forced an orientation change), process them now.
3769        for (int i = 0; i < sPendingAddList.size(); i++) {
3770            completeAdd(sPendingAddList.get(i));
3771        }
3772        sPendingAddList.clear();
3773
3774        // Update the market app icon as necessary (the other icons will be managed in response to
3775        // package changes in bindSearchablesChanged()
3776        updateAppMarketIcon();
3777
3778        mWorkspaceLoading = false;
3779        if (upgradePath) {
3780            mWorkspace.stripDuplicateApps();
3781            mIntentsOnWorkspaceFromUpgradePath = mWorkspace.stripDuplicateApps();
3782        }
3783
3784        mWorkspace.post(new Runnable() {
3785            @Override
3786            public void run() {
3787                onFinishBindingItems();
3788            }
3789        });
3790    }
3791
3792    private boolean canRunNewAppsAnimation() {
3793        long diff = System.currentTimeMillis() - mDragController.getLastGestureUpTime();
3794        return diff > (NEW_APPS_ANIMATION_INACTIVE_TIMEOUT_SECONDS * 1000);
3795    }
3796
3797    private ValueAnimator createNewAppBounceAnimation(View v, int i) {
3798        ValueAnimator bounceAnim = LauncherAnimUtils.ofPropertyValuesHolder(v,
3799                PropertyValuesHolder.ofFloat("alpha", 1f),
3800                PropertyValuesHolder.ofFloat("scaleX", 1f),
3801                PropertyValuesHolder.ofFloat("scaleY", 1f));
3802        bounceAnim.setDuration(InstallShortcutReceiver.NEW_SHORTCUT_BOUNCE_DURATION);
3803        bounceAnim.setStartDelay(i * InstallShortcutReceiver.NEW_SHORTCUT_STAGGER_DELAY);
3804        bounceAnim.setInterpolator(new SmoothPagedView.OvershootInterpolator());
3805        return bounceAnim;
3806    }
3807
3808    @Override
3809    public void bindSearchablesChanged() {
3810        boolean searchVisible = updateGlobalSearchIcon();
3811        boolean voiceVisible = updateVoiceSearchIcon(searchVisible);
3812        if (mSearchDropTargetBar != null) {
3813            mSearchDropTargetBar.onSearchPackagesChanged(searchVisible, voiceVisible);
3814        }
3815    }
3816
3817    /**
3818     * Add the icons for all apps.
3819     *
3820     * Implementation of the method from LauncherModel.Callbacks.
3821     */
3822    public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
3823        if (mIntentsOnWorkspaceFromUpgradePath != null) {
3824            if (LauncherModel.UPGRADE_USE_MORE_APPS_FOLDER) {
3825                getHotseat().addAllAppsFolder(mIconCache, apps,
3826                        mIntentsOnWorkspaceFromUpgradePath, Launcher.this, mWorkspace);
3827            }
3828            mIntentsOnWorkspaceFromUpgradePath = null;
3829        }
3830    }
3831
3832    /**
3833     * A package was updated.
3834     *
3835     * Implementation of the method from LauncherModel.Callbacks.
3836     */
3837    public void bindAppsUpdated(final ArrayList<ApplicationInfo> apps) {
3838        Runnable r = new Runnable() {
3839            public void run() {
3840                bindAppsUpdated(apps);
3841            }
3842        };
3843        if (waitUntilResume(r)) {
3844            return;
3845        }
3846
3847        if (mWorkspace != null) {
3848            mWorkspace.updateShortcuts(apps);
3849        }
3850    }
3851
3852    /**
3853     * A package was uninstalled.  We take both the super set of packageNames
3854     * in addition to specific applications to remove, the reason being that
3855     * this can be called when a package is updated as well.  In that scenario,
3856     * we only remove specific components from the workspace, where as
3857     * package-removal should clear all items by package name.
3858     *
3859     * Implementation of the method from LauncherModel.Callbacks.
3860     */
3861    public void bindComponentsRemoved(final ArrayList<String> packageNames,
3862                                      final ArrayList<ApplicationInfo> appInfos,
3863                                      final boolean packageRemoved) {
3864        Runnable r = new Runnable() {
3865            public void run() {
3866                bindComponentsRemoved(packageNames, appInfos, packageRemoved);
3867            }
3868        };
3869        if (waitUntilResume(r)) {
3870            return;
3871        }
3872
3873        if (packageRemoved) {
3874            mWorkspace.removeItemsByPackageName(packageNames);
3875        } else {
3876            mWorkspace.removeItemsByApplicationInfo(appInfos);
3877        }
3878
3879        // Notify the drag controller
3880        mDragController.onAppsRemoved(appInfos, this);
3881    }
3882
3883    /**
3884     * A number of packages were updated.
3885     */
3886    private ArrayList<Object> mWidgetsAndShortcuts;
3887    private Runnable mBindPackagesUpdatedRunnable = new Runnable() {
3888            public void run() {
3889                bindPackagesUpdated(mWidgetsAndShortcuts);
3890                mWidgetsAndShortcuts = null;
3891            }
3892        };
3893
3894    public void bindPackagesUpdated(final ArrayList<Object> widgetsAndShortcuts) {
3895        if (waitUntilResume(mBindPackagesUpdatedRunnable, true)) {
3896            mWidgetsAndShortcuts = widgetsAndShortcuts;
3897            return;
3898        }
3899
3900        // Update the widgets pane
3901        if (mAppsCustomizeContent != null) {
3902            mAppsCustomizeContent.onPackagesUpdated(widgetsAndShortcuts);
3903        }
3904    }
3905
3906    private int mapConfigurationOriActivityInfoOri(int configOri) {
3907        final Display d = getWindowManager().getDefaultDisplay();
3908        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3909        switch (d.getRotation()) {
3910        case Surface.ROTATION_0:
3911        case Surface.ROTATION_180:
3912            // We are currently in the same basic orientation as the natural orientation
3913            naturalOri = configOri;
3914            break;
3915        case Surface.ROTATION_90:
3916        case Surface.ROTATION_270:
3917            // We are currently in the other basic orientation to the natural orientation
3918            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3919                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3920            break;
3921        }
3922
3923        int[] oriMap = {
3924                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3925                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3926                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3927                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3928        };
3929        // Since the map starts at portrait, we need to offset if this device's natural orientation
3930        // is landscape.
3931        int indexOffset = 0;
3932        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3933            indexOffset = 1;
3934        }
3935        return oriMap[(d.getRotation() + indexOffset) % 4];
3936    }
3937
3938    public boolean isRotationEnabled() {
3939        boolean enableRotation = sForceEnableRotation ||
3940                getResources().getBoolean(R.bool.allow_rotation);
3941        return enableRotation;
3942    }
3943    public void lockScreenOrientation() {
3944        if (isRotationEnabled()) {
3945            setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3946                    .getConfiguration().orientation));
3947        }
3948    }
3949    public void unlockScreenOrientation(boolean immediate) {
3950        if (isRotationEnabled()) {
3951            if (immediate) {
3952                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3953            } else {
3954                mHandler.postDelayed(new Runnable() {
3955                    public void run() {
3956                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3957                    }
3958                }, mRestoreScreenOrientationDelay);
3959            }
3960        }
3961    }
3962
3963    /* Cling related */
3964    private boolean isClingsEnabled() {
3965        if (DISABLE_CLINGS) {
3966            return false;
3967        }
3968
3969        // disable clings when running in a test harness
3970        if(ActivityManager.isRunningInTestHarness()) return false;
3971
3972        // Restricted secondary users (child mode) will potentially have very few apps
3973        // seeded when they start up for the first time. Clings won't work well with that
3974//        boolean supportsLimitedUsers =
3975//                android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2;
3976//        Account[] accounts = AccountManager.get(this).getAccounts();
3977//        if (supportsLimitedUsers && accounts.length == 0) {
3978//            UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
3979//            Bundle restrictions = um.getUserRestrictions();
3980//            if (restrictions.getBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, false)) {
3981//               return false;
3982//            }
3983//        }
3984        return true;
3985    }
3986
3987    private Cling initCling(int clingId, int[] positionData, boolean animate, int delay) {
3988        final Cling cling = (Cling) findViewById(clingId);
3989        if (cling != null) {
3990            cling.init(this, positionData);
3991            cling.setVisibility(View.VISIBLE);
3992            cling.setLayerType(View.LAYER_TYPE_HARDWARE, null);
3993            if (animate) {
3994                cling.buildLayer();
3995                cling.setAlpha(0f);
3996                cling.animate()
3997                    .alpha(1f)
3998                    .setInterpolator(new AccelerateInterpolator())
3999                    .setDuration(SHOW_CLING_DURATION)
4000                    .setStartDelay(delay)
4001                    .start();
4002            } else {
4003                cling.setAlpha(1f);
4004            }
4005            cling.setFocusableInTouchMode(true);
4006            cling.post(new Runnable() {
4007                public void run() {
4008                    cling.setFocusable(true);
4009                    cling.requestFocus();
4010                }
4011            });
4012            mHideFromAccessibilityHelper.setImportantForAccessibilityToNo(
4013                    mDragLayer, clingId == R.id.all_apps_cling);
4014        }
4015        return cling;
4016    }
4017
4018    private void dismissCling(final Cling cling, final String flag, int duration) {
4019        // To catch cases where siblings of top-level views are made invisible, just check whether
4020        // the cling is directly set to GONE before dismissing it.
4021        if (cling != null && cling.getVisibility() != View.GONE) {
4022            ObjectAnimator anim = LauncherAnimUtils.ofFloat(cling, "alpha", 0f);
4023            anim.setDuration(duration);
4024            anim.addListener(new AnimatorListenerAdapter() {
4025                public void onAnimationEnd(Animator animation) {
4026                    cling.setVisibility(View.GONE);
4027                    cling.cleanup();
4028                    // We should update the shared preferences on a background thread
4029                    new Thread("dismissClingThread") {
4030                        public void run() {
4031                            SharedPreferences.Editor editor = mSharedPrefs.edit();
4032                            editor.putBoolean(flag, true);
4033                            editor.commit();
4034                        }
4035                    }.start();
4036                };
4037            });
4038            anim.start();
4039            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
4040        }
4041    }
4042
4043    private void removeCling(int id) {
4044        final View cling = findViewById(id);
4045        if (cling != null) {
4046            final ViewGroup parent = (ViewGroup) cling.getParent();
4047            parent.post(new Runnable() {
4048                @Override
4049                public void run() {
4050                    parent.removeView(cling);
4051                }
4052            });
4053            mHideFromAccessibilityHelper.restoreImportantForAccessibility(mDragLayer);
4054        }
4055    }
4056
4057    private boolean skipCustomClingIfNoAccounts() {
4058        Cling cling = (Cling) findViewById(R.id.workspace_cling);
4059        boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
4060        if (customCling) {
4061            AccountManager am = AccountManager.get(this);
4062            if (am == null) return false;
4063            Account[] accounts = am.getAccountsByType("com.google");
4064            return accounts.length == 0;
4065        }
4066        return false;
4067    }
4068
4069    public void showFirstRunWorkspaceCling() {
4070        // Enable the clings only if they have not been dismissed before
4071        if (isClingsEnabled() &&
4072                !mSharedPrefs.getBoolean(Cling.WORKSPACE_CLING_DISMISSED_KEY, false) &&
4073                !skipCustomClingIfNoAccounts() ) {
4074            // If we're not using the default workspace layout, replace workspace cling
4075            // with a custom workspace cling (usually specified in an overlay)
4076            // For now, only do this on tablets
4077            if (mSharedPrefs.getInt(LauncherProvider.DEFAULT_WORKSPACE_RESOURCE_ID, 0) != 0 &&
4078                    getResources().getBoolean(R.bool.config_useCustomClings)) {
4079                // Use a custom cling
4080                View cling = findViewById(R.id.workspace_cling);
4081                ViewGroup clingParent = (ViewGroup) cling.getParent();
4082                int clingIndex = clingParent.indexOfChild(cling);
4083                clingParent.removeViewAt(clingIndex);
4084                View customCling = mInflater.inflate(R.layout.custom_workspace_cling, clingParent, false);
4085                clingParent.addView(customCling, clingIndex);
4086                customCling.setId(R.id.workspace_cling);
4087            }
4088            initCling(R.id.workspace_cling, null, false, 0);
4089        } else {
4090            removeCling(R.id.workspace_cling);
4091        }
4092    }
4093    public void showFirstRunAllAppsCling(int[] position) {
4094        // Enable the clings only if they have not been dismissed before
4095        if (isClingsEnabled() &&
4096                !mSharedPrefs.getBoolean(Cling.ALLAPPS_CLING_DISMISSED_KEY, false)) {
4097            initCling(R.id.all_apps_cling, position, true, 0);
4098        } else {
4099            removeCling(R.id.all_apps_cling);
4100        }
4101    }
4102    public Cling showFirstRunFoldersCling() {
4103        // Enable the clings only if they have not been dismissed before
4104        if (isClingsEnabled() &&
4105                !mSharedPrefs.getBoolean(Cling.FOLDER_CLING_DISMISSED_KEY, false)) {
4106            return initCling(R.id.folder_cling, null, true, 0);
4107        } else {
4108            removeCling(R.id.folder_cling);
4109            return null;
4110        }
4111    }
4112    protected SharedPreferences getSharedPrefs() {
4113        return mSharedPrefs;
4114    }
4115    public boolean isFolderClingVisible() {
4116        Cling cling = (Cling) findViewById(R.id.folder_cling);
4117        if (cling != null) {
4118            return cling.getVisibility() == View.VISIBLE;
4119        }
4120        return false;
4121    }
4122    public void dismissWorkspaceCling(View v) {
4123        Cling cling = (Cling) findViewById(R.id.workspace_cling);
4124        dismissCling(cling, Cling.WORKSPACE_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4125    }
4126    public void dismissAllAppsCling(View v) {
4127        Cling cling = (Cling) findViewById(R.id.all_apps_cling);
4128        dismissCling(cling, Cling.ALLAPPS_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4129    }
4130    public void dismissFolderCling(View v) {
4131        Cling cling = (Cling) findViewById(R.id.folder_cling);
4132        dismissCling(cling, Cling.FOLDER_CLING_DISMISSED_KEY, DISMISS_CLING_DURATION);
4133    }
4134
4135    /**
4136     * Prints out out state for debugging.
4137     */
4138    public void dumpState() {
4139        Log.d(TAG, "BEGIN launcher3 dump state for launcher " + this);
4140        Log.d(TAG, "mSavedState=" + mSavedState);
4141        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
4142        Log.d(TAG, "mRestoring=" + mRestoring);
4143        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
4144        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
4145        Log.d(TAG, "sFolders.size=" + sFolders.size());
4146        mModel.dumpState();
4147
4148        if (mAppsCustomizeContent != null) {
4149            mAppsCustomizeContent.dumpState();
4150        }
4151        Log.d(TAG, "END launcher3 dump state");
4152    }
4153
4154    @Override
4155    public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
4156        super.dump(prefix, fd, writer, args);
4157        writer.println(" ");
4158        writer.println("Debug logs: ");
4159        for (int i = 0; i < sDumpLogs.size(); i++) {
4160            writer.println("  " + sDumpLogs.get(i));
4161        }
4162    }
4163
4164    public static void dumpDebugLogsToConsole() {
4165        Log.d(TAG, "");
4166        Log.d(TAG, "*********************");
4167        Log.d(TAG, "Launcher debug logs: ");
4168        for (int i = 0; i < sDumpLogs.size(); i++) {
4169            Log.d(TAG, "  " + sDumpLogs.get(i));
4170        }
4171        Log.d(TAG, "*********************");
4172        Log.d(TAG, "");
4173    }
4174}
4175
4176interface LauncherTransitionable {
4177    View getContent();
4178    void onLauncherTransitionPrepare(Launcher l, boolean animated, boolean toWorkspace);
4179    void onLauncherTransitionStart(Launcher l, boolean animated, boolean toWorkspace);
4180    void onLauncherTransitionStep(Launcher l, float t);
4181    void onLauncherTransitionEnd(Launcher l, boolean animated, boolean toWorkspace);
4182}
4183