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