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