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