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