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