Launcher.java revision e50adee3d54978840036bb3a814771ce498aee18
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.app.Activity;
27import android.app.AlertDialog;
28import android.app.Dialog;
29import android.app.SearchManager;
30import android.app.StatusBarManager;
31import android.appwidget.AppWidgetManager;
32import android.appwidget.AppWidgetProviderInfo;
33import android.content.ActivityNotFoundException;
34import android.content.BroadcastReceiver;
35import android.content.ClipData;
36import android.content.ClipDescription;
37import android.content.ComponentName;
38import android.content.ContentResolver;
39import android.content.Context;
40import android.content.DialogInterface;
41import android.content.Intent;
42import android.content.IntentFilter;
43import android.content.Intent.ShortcutIconResource;
44import android.content.pm.ActivityInfo;
45import android.content.pm.PackageManager;
46import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.res.Configuration;
48import android.content.res.Resources;
49import android.database.ContentObserver;
50import android.graphics.Rect;
51import android.graphics.drawable.Drawable;
52import android.net.Uri;
53import android.os.AsyncTask;
54import android.os.Build;
55import android.os.Bundle;
56import android.os.Environment;
57import android.os.Handler;
58import android.os.Message;
59import android.os.SystemClock;
60import android.os.SystemProperties;
61import android.provider.Settings;
62import android.speech.RecognizerIntent;
63import android.text.Selection;
64import android.text.SpannableStringBuilder;
65import android.text.TextUtils;
66import android.text.method.TextKeyListener;
67import android.util.Log;
68import android.view.Display;
69import android.view.HapticFeedbackConstants;
70import android.view.KeyEvent;
71import android.view.LayoutInflater;
72import android.view.Menu;
73import android.view.MenuItem;
74import android.view.MotionEvent;
75import android.view.Surface;
76import android.view.View;
77import android.view.ViewGroup;
78import android.view.View.OnLongClickListener;
79import android.view.accessibility.AccessibilityEvent;
80import android.view.animation.DecelerateInterpolator;
81import android.view.inputmethod.InputMethodManager;
82import android.widget.Advanceable;
83import android.widget.EditText;
84import android.widget.ImageView;
85import android.widget.TextView;
86import android.widget.Toast;
87
88import com.android.common.Search;
89import com.android.launcher.R;
90
91import java.io.DataInputStream;
92import java.io.DataOutputStream;
93import java.io.FileNotFoundException;
94import java.io.IOException;
95import java.util.ArrayList;
96import java.util.HashMap;
97
98/**
99 * Default launcher application.
100 */
101public final class Launcher extends Activity
102        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
103                   AllAppsView.Watcher, View.OnTouchListener {
104    static final String TAG = "Launcher";
105    static final boolean LOGD = false;
106
107    static final boolean PROFILE_STARTUP = false;
108    static final boolean DEBUG_WIDGETS = false;
109
110    private static final int MENU_GROUP_ADD = 1;
111    private static final int MENU_GROUP_WALLPAPER = MENU_GROUP_ADD + 1;
112
113    private static final int MENU_ADD = Menu.FIRST + 1;
114    private static final int MENU_MANAGE_APPS = MENU_ADD + 1;
115    private static final int MENU_WALLPAPER_SETTINGS = MENU_MANAGE_APPS + 1;
116    private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
117    private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
118    private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
119
120    private static final int REQUEST_CREATE_SHORTCUT = 1;
121    private static final int REQUEST_CREATE_APPWIDGET = 5;
122    private static final int REQUEST_PICK_APPLICATION = 6;
123    private static final int REQUEST_PICK_SHORTCUT = 7;
124    private static final int REQUEST_PICK_APPWIDGET = 9;
125    private static final int REQUEST_PICK_WALLPAPER = 10;
126
127    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
128
129    static final int SCREEN_COUNT = 5;
130    static final int DEFAULT_SCREEN = 2;
131
132    static final int DIALOG_CREATE_SHORTCUT = 1;
133    static final int DIALOG_RENAME_FOLDER = 2;
134
135    private static final String PREFERENCES = "launcher.preferences";
136
137    // Type: int
138    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
139    // Type: int
140    private static final String RUNTIME_STATE = "launcher.state";
141    // Type: int
142    private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container";
143    // Type: int
144    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
145    // Type: int
146    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x";
147    // Type: int
148    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y";
149    // Type: boolean
150    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
151    // Type: long
152    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
153
154    private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon";
155
156    /** The different states that Launcher can be in. */
157    private enum State { WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED };
158    private State mState = State.WORKSPACE;
159    private AnimatorSet mStateAnimation;
160
161    static final int APPWIDGET_HOST_ID = 1024;
162    private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300;
163    private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600;
164
165    private static final Object sLock = new Object();
166    private static int sScreen = DEFAULT_SCREEN;
167
168    private final BroadcastReceiver mCloseSystemDialogsReceiver
169            = new CloseSystemDialogsIntentReceiver();
170    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
171
172    private LayoutInflater mInflater;
173
174    private DragController mDragController;
175    private Workspace mWorkspace;
176
177    private AppWidgetManager mAppWidgetManager;
178    private LauncherAppWidgetHost mAppWidgetHost;
179
180    private ItemInfo mPendingAddInfo = new ItemInfo();
181    private int[] mTmpAddItemCellCoordinates = new int[2];
182
183    private FolderInfo mFolderInfo;
184
185    private Hotseat mHotseat;
186    private View mAllAppsButton;
187
188    private SearchDropTargetBar mSearchDeleteBar;
189    private AppsCustomizeTabHost mAppsCustomizeTabHost;
190    private AppsCustomizePagedView mAppsCustomizeContent;
191    private boolean mAutoAdvanceRunning = false;
192
193    private Bundle mSavedState;
194
195    private SpannableStringBuilder mDefaultKeySsb = null;
196
197    private boolean mWorkspaceLoading = true;
198
199    private boolean mPaused = true;
200    private boolean mRestoring;
201    private boolean mWaitingForResult;
202    private boolean mOnResumeNeedsLoad;
203
204    private Bundle mSavedInstanceState;
205
206    private LauncherModel mModel;
207    private IconCache mIconCache;
208    private boolean mUserPresent = true;
209    private boolean mVisible = false;
210    private boolean mAttached = false;
211
212    private static LocaleConfiguration sLocaleConfiguration = null;
213
214    private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>();
215
216    private Intent mAppMarketIntent = null;
217
218    // Related to the auto-advancing of widgets
219    private final int ADVANCE_MSG = 1;
220    private final int mAdvanceInterval = 20000;
221    private final int mAdvanceStagger = 250;
222    private long mAutoAdvanceSentTime;
223    private long mAutoAdvanceTimeLeft = -1;
224    private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance =
225        new HashMap<View, AppWidgetProviderInfo>();
226
227    // Determines how long to wait after a rotation before restoring the screen orientation to
228    // match the sensor state.
229    private final int mRestoreScreenOrientationDelay = 500;
230
231    // External icons saved in case of resource changes, orientation, etc.
232    private static Drawable.ConstantState sGlobalSearchIcon;
233    private static Drawable.ConstantState sVoiceSearchIcon;
234    private static Drawable.ConstantState sAppMarketIcon;
235
236    private DragLayer mDragLayer;
237
238    private BubbleTextView mWaitingForResume;
239
240    private static ArrayList<PendingAddArguments> sPendingAddList
241            = new ArrayList<PendingAddArguments>();
242
243    private static class PendingAddArguments {
244        int requestCode;
245        Intent intent;
246        long container;
247        int screen;
248        int cellX;
249        int cellY;
250    }
251
252    @Override
253    protected void onCreate(Bundle savedInstanceState) {
254        super.onCreate(savedInstanceState);
255        LauncherApplication app = ((LauncherApplication)getApplication());
256        mModel = app.setLauncher(this);
257        mIconCache = app.getIconCache();
258        mDragController = new DragController(this);
259        mInflater = getLayoutInflater();
260
261        mAppWidgetManager = AppWidgetManager.getInstance(this);
262        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
263        mAppWidgetHost.startListening();
264
265        if (PROFILE_STARTUP) {
266            android.os.Debug.startMethodTracing(
267                    Environment.getExternalStorageDirectory() + "/launcher");
268        }
269
270        checkForLocaleChange();
271        setContentView(R.layout.launcher);
272        setupViews();
273
274        registerContentObservers();
275
276        lockAllApps();
277
278        mSavedState = savedInstanceState;
279        restoreState(mSavedState);
280
281        // Update customization drawer _after_ restoring the states
282        if (mAppsCustomizeContent != null) {
283            mAppsCustomizeContent.onPackagesUpdated();
284        }
285
286        if (PROFILE_STARTUP) {
287            android.os.Debug.stopMethodTracing();
288        }
289
290        if (!mRestoring) {
291            mModel.startLoader(this, true);
292        }
293
294        if (!mModel.isAllAppsLoaded()) {
295            ViewGroup appsCustomizeContentParent = (ViewGroup) mAppsCustomizeContent.getParent();
296            mInflater.inflate(R.layout.apps_customize_progressbar, appsCustomizeContentParent);
297        }
298
299        // For handling default keys
300        mDefaultKeySsb = new SpannableStringBuilder();
301        Selection.setSelection(mDefaultKeySsb, 0);
302
303        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
304        registerReceiver(mCloseSystemDialogsReceiver, filter);
305
306        // If we have a saved version of these external icons, we load them up immediately
307        if (sGlobalSearchIcon == null || sVoiceSearchIcon == null || sAppMarketIcon == null) {
308            updateIconsAffectedByPackageManagerChanges();
309            updateGlobalSearchIcon();
310        }
311        if (sGlobalSearchIcon != null) {
312             updateGlobalSearchIcon(sGlobalSearchIcon);
313        }
314        if (sVoiceSearchIcon != null) {
315            updateVoiceSearchIcon(sVoiceSearchIcon);
316        }
317        if (sAppMarketIcon != null) {
318            updateAppMarketIcon(sAppMarketIcon);
319        }
320    }
321
322    private void checkForLocaleChange() {
323        if (sLocaleConfiguration == null) {
324            new AsyncTask<Void, Void, LocaleConfiguration>() {
325                @Override
326                protected LocaleConfiguration doInBackground(Void... unused) {
327                    LocaleConfiguration localeConfiguration = new LocaleConfiguration();
328                    readConfiguration(Launcher.this, localeConfiguration);
329                    return localeConfiguration;
330                }
331
332                @Override
333                protected void onPostExecute(LocaleConfiguration result) {
334                    sLocaleConfiguration = result;
335                    checkForLocaleChange();  // recursive, but now with a locale configuration
336                }
337            }.execute();
338            return;
339        }
340
341        final Configuration configuration = getResources().getConfiguration();
342
343        final String previousLocale = sLocaleConfiguration.locale;
344        final String locale = configuration.locale.toString();
345
346        final int previousMcc = sLocaleConfiguration.mcc;
347        final int mcc = configuration.mcc;
348
349        final int previousMnc = sLocaleConfiguration.mnc;
350        final int mnc = configuration.mnc;
351
352        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
353
354        if (localeChanged) {
355            sLocaleConfiguration.locale = locale;
356            sLocaleConfiguration.mcc = mcc;
357            sLocaleConfiguration.mnc = mnc;
358
359            mIconCache.flush();
360
361            final LocaleConfiguration localeConfiguration = sLocaleConfiguration;
362            new Thread("WriteLocaleConfiguration") {
363                @Override
364                public void run() {
365                    writeConfiguration(Launcher.this, localeConfiguration);
366                }
367            }.start();
368        }
369    }
370
371    private static class LocaleConfiguration {
372        public String locale;
373        public int mcc = -1;
374        public int mnc = -1;
375    }
376
377    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
378        DataInputStream in = null;
379        try {
380            in = new DataInputStream(context.openFileInput(PREFERENCES));
381            configuration.locale = in.readUTF();
382            configuration.mcc = in.readInt();
383            configuration.mnc = in.readInt();
384        } catch (FileNotFoundException e) {
385            // Ignore
386        } catch (IOException e) {
387            // Ignore
388        } finally {
389            if (in != null) {
390                try {
391                    in.close();
392                } catch (IOException e) {
393                    // Ignore
394                }
395            }
396        }
397    }
398
399    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
400        DataOutputStream out = null;
401        try {
402            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
403            out.writeUTF(configuration.locale);
404            out.writeInt(configuration.mcc);
405            out.writeInt(configuration.mnc);
406            out.flush();
407        } catch (FileNotFoundException e) {
408            // Ignore
409        } catch (IOException e) {
410            //noinspection ResultOfMethodCallIgnored
411            context.getFileStreamPath(PREFERENCES).delete();
412        } finally {
413            if (out != null) {
414                try {
415                    out.close();
416                } catch (IOException e) {
417                    // Ignore
418                }
419            }
420        }
421    }
422
423    public DragLayer getDragLayer() {
424        return mDragLayer;
425    }
426
427    static int getScreen() {
428        synchronized (sLock) {
429            return sScreen;
430        }
431    }
432
433    static void setScreen(int screen) {
434        synchronized (sLock) {
435            sScreen = screen;
436        }
437    }
438
439    /**
440     * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have
441     * a configuration step, this allows the proper animations to run after other transitions.
442     */
443    private boolean completeAdd(PendingAddArguments args) {
444        boolean result = false;
445        switch (args.requestCode) {
446            case REQUEST_PICK_APPLICATION:
447                completeAddApplication(args.intent, args.container, args.screen, args.cellX,
448                        args.cellY);
449                break;
450            case REQUEST_PICK_SHORTCUT:
451                processShortcut(args.intent);
452                break;
453            case REQUEST_CREATE_SHORTCUT:
454                completeAddShortcut(args.intent, args.container, args.screen, args.cellX,
455                        args.cellY);
456                result = true;
457                break;
458            case REQUEST_PICK_APPWIDGET:
459                addAppWidgetFromPick(args.intent);
460                break;
461            case REQUEST_CREATE_APPWIDGET:
462                int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
463                completeAddAppWidget(appWidgetId, args.container, args.screen);
464                result = true;
465                break;
466            case REQUEST_PICK_WALLPAPER:
467                // We just wanted the activity result here so we can clear mWaitingForResult
468                break;
469        }
470        // In any situation where we have a multi-step drop, we should reset the add info only after
471        // we complete the drop
472        resetAddInfo();
473        return result;
474    }
475
476    @Override
477    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) {
478        boolean delayExitSpringLoadedMode = false;
479        mWaitingForResult = false;
480
481        // The pattern used here is that a user PICKs a specific application,
482        // which, depending on the target, might need to CREATE the actual target.
483
484        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
485        // launch over to the Music app to actually CREATE_SHORTCUT.
486        if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID) {
487            final PendingAddArguments args = new PendingAddArguments();
488            args.requestCode = requestCode;
489            args.intent = data;
490            args.container = mPendingAddInfo.container;
491            args.screen = mPendingAddInfo.screen;
492            args.cellX = mPendingAddInfo.cellX;
493            args.cellY = mPendingAddInfo.cellY;
494
495            // If the loader is still running, defer the add until it is done.
496            if (isWorkspaceLocked()) {
497                sPendingAddList.add(args);
498            } else {
499                delayExitSpringLoadedMode = completeAdd(args);
500            }
501        } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
502                requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED) {
503            if (data != null) {
504                // Clean up the appWidgetId if we canceled
505                int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
506                if (appWidgetId != -1) {
507                    mAppWidgetHost.deleteAppWidgetId(appWidgetId);
508                }
509            }
510        }
511
512        // Exit spring loaded mode if necessary after cancelling the configuration of a widget
513        exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode);
514    }
515
516    @Override
517    protected void onResume() {
518        super.onResume();
519        mPaused = false;
520        if (mRestoring || mOnResumeNeedsLoad) {
521            mWorkspaceLoading = true;
522            mModel.startLoader(this, true);
523            mRestoring = false;
524            mOnResumeNeedsLoad = false;
525        }
526        if (mWaitingForResume != null) {
527            mWaitingForResume.setStayPressed(false);
528        }
529        // When we resume Launcher, a different Activity might be responsible for the app
530        // market intent, so refresh the icon
531        updateAppMarketIcon();
532    }
533
534    @Override
535    protected void onPause() {
536        super.onPause();
537        mPaused = true;
538        mDragController.cancelDrag();
539    }
540
541    @Override
542    public Object onRetainNonConfigurationInstance() {
543        // Flag the loader to stop early before switching
544        mModel.stopLoader();
545        if (mAppsCustomizeContent != null) {
546            mAppsCustomizeContent.surrender();
547        }
548        return Boolean.TRUE;
549    }
550
551    // We can't hide the IME if it was forced open.  So don't bother
552    /*
553    @Override
554    public void onWindowFocusChanged(boolean hasFocus) {
555        super.onWindowFocusChanged(hasFocus);
556
557        if (hasFocus) {
558            final InputMethodManager inputManager = (InputMethodManager)
559                    getSystemService(Context.INPUT_METHOD_SERVICE);
560            WindowManager.LayoutParams lp = getWindow().getAttributes();
561            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
562                        android.os.Handler()) {
563                        protected void onReceiveResult(int resultCode, Bundle resultData) {
564                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
565                        }
566                    });
567            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
568        }
569    }
570    */
571
572    private boolean acceptFilter() {
573        final InputMethodManager inputManager = (InputMethodManager)
574                getSystemService(Context.INPUT_METHOD_SERVICE);
575        return !inputManager.isFullscreenMode();
576    }
577
578    @Override
579    public boolean onKeyDown(int keyCode, KeyEvent event) {
580        final int uniChar = event.getUnicodeChar();
581        final boolean handled = super.onKeyDown(keyCode, event);
582        final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar);
583        if (!handled && acceptFilter() && isKeyNotWhitespace) {
584            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
585                    keyCode, event);
586            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
587                // something usable has been typed - start a search
588                // the typed text will be retrieved and cleared by
589                // showSearchDialog()
590                // If there are multiple keystrokes before the search dialog takes focus,
591                // onSearchRequested() will be called for every keystroke,
592                // but it is idempotent, so it's fine.
593                return onSearchRequested();
594            }
595        }
596
597        // Eat the long press event so the keyboard doesn't come up.
598        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
599            return true;
600        }
601
602        return handled;
603    }
604
605    private String getTypedText() {
606        return mDefaultKeySsb.toString();
607    }
608
609    private void clearTypedText() {
610        mDefaultKeySsb.clear();
611        mDefaultKeySsb.clearSpans();
612        Selection.setSelection(mDefaultKeySsb, 0);
613    }
614
615    /**
616     * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type
617     * State
618     */
619    private static State intToState(int stateOrdinal) {
620        State state = State.WORKSPACE;
621        final State[] stateValues = State.values();
622        for (int i = 0; i < stateValues.length; i++) {
623            if (stateValues[i].ordinal() == stateOrdinal) {
624                state = stateValues[i];
625                break;
626            }
627        }
628        return state;
629    }
630
631    /**
632     * Restores the previous state, if it exists.
633     *
634     * @param savedState The previous state.
635     */
636    private void restoreState(Bundle savedState) {
637        if (savedState == null) {
638            return;
639        }
640
641        State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal()));
642        if (state == State.APPS_CUSTOMIZE) {
643            showAllApps(false);
644        }
645
646        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
647        if (currentScreen > -1) {
648            mWorkspace.setCurrentPage(currentScreen);
649        }
650
651        final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1);
652        final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
653
654        if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) {
655            mPendingAddInfo.container = pendingAddContainer;
656            mPendingAddInfo.screen = pendingAddScreen;
657            mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
658            mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
659            mRestoring = true;
660        }
661
662        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
663        if (renameFolder) {
664            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
665            mFolderInfo = mModel.getFolderById(this, sFolders, id);
666            mRestoring = true;
667        }
668
669
670        // Restore the AppsCustomize tab
671        if (mAppsCustomizeTabHost != null) {
672            String curTab = savedState.getString("apps_customize_currentTab");
673            if (curTab != null) {
674                // We set this directly so that there is no delay before the tab is set
675                mAppsCustomizeContent.setContentType(
676                        mAppsCustomizeTabHost.getContentTypeForTabTag(curTab));
677                mAppsCustomizeTabHost.setCurrentTabByTag(curTab);
678            }
679
680            // Note: currently we do not restore the page for the AppsCustomize pane because the
681            // change in layout can drastically affect the saved page index
682        }
683    }
684
685    /**
686     * Finds all the views we need and configure them properly.
687     */
688    private void setupViews() {
689        final DragController dragController = mDragController;
690
691        mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
692        mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
693
694        // Setup the drag layer
695        mDragLayer.setup(this, dragController);
696
697        // Setup the hotseat
698        mHotseat = (Hotseat) findViewById(R.id.hotseat);
699        if (mHotseat != null) {
700            mHotseat.setup(this);
701        }
702
703        // Setup the workspace
704        mWorkspace.setHapticFeedbackEnabled(false);
705        mWorkspace.setOnLongClickListener(this);
706        mWorkspace.setup(this, dragController);
707        dragController.addDragListener(mWorkspace);
708
709        // Get the search/delete bar
710        mSearchDeleteBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar);
711
712        // Setup AppsCustomize
713        mAppsCustomizeTabHost = (AppsCustomizeTabHost)
714                findViewById(R.id.apps_customize_pane);
715        mAppsCustomizeContent = (AppsCustomizePagedView)
716                mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content);
717        mAppsCustomizeContent.setup(this, dragController);
718
719
720
721        // Setup the drag controller (drop targets have to be added in reverse order in priority)
722        dragController.setDragScoller(mWorkspace);
723        dragController.setScrollView(mDragLayer);
724        dragController.setMoveTarget(mWorkspace);
725        dragController.addDropTarget(mWorkspace);
726        if (mSearchDeleteBar != null) {
727            mSearchDeleteBar.setup(this, dragController);
728        }
729    }
730
731
732
733    /**
734     * Creates a view representing a shortcut.
735     *
736     * @param info The data structure describing the shortcut.
737     *
738     * @return A View inflated from R.layout.application.
739     */
740    View createShortcut(ShortcutInfo info) {
741        return createShortcut(R.layout.application,
742                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info);
743    }
744
745    /**
746     * Creates a view representing a shortcut inflated from the specified resource.
747     *
748     * @param layoutResId The id of the XML layout used to create the shortcut.
749     * @param parent The group the shortcut belongs to.
750     * @param info The data structure describing the shortcut.
751     *
752     * @return A View inflated from layoutResId.
753     */
754    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
755        BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false);
756        favorite.applyFromShortcutInfo(info, mIconCache);
757        favorite.setOnClickListener(this);
758        return favorite;
759    }
760
761    /**
762     * Add an application shortcut to the workspace.
763     *
764     * @param data The intent describing the application.
765     * @param cellInfo The position on screen where to create the shortcut.
766     */
767    void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) {
768        final int[] cellXY = mTmpAddItemCellCoordinates;
769        final CellLayout layout = getCellLayout(container, screen);
770
771        // First we check if we already know the exact location where we want to add this item.
772        if (cellX >= 0 && cellY >= 0) {
773            cellXY[0] = cellX;
774            cellXY[1] = cellY;
775        } else if (!layout.findCellForSpan(cellXY, 1, 1)) {
776            showOutOfSpaceMessage();
777            return;
778        }
779
780        final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this);
781
782        if (info != null) {
783            info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
784                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
785            info.container = ItemInfo.NO_ID;
786            mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1],
787                    isWorkspaceLocked(), cellX, cellY);
788        } else {
789            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
790        }
791    }
792
793    /**
794     * Add a shortcut to the workspace.
795     *
796     * @param data The intent describing the shortcut.
797     * @param cellInfo The position on screen where to create the shortcut.
798     */
799    private void completeAddShortcut(Intent data, long container, int screen, int cellX,
800            int cellY) {
801        int[] cellXY = mTmpAddItemCellCoordinates;
802        int[] touchXY = mPendingAddInfo.dropPos;
803        CellLayout layout = getCellLayout(container, screen);
804
805        boolean foundCellSpan = false;
806
807        // First we check if we already know the exact location where we want to add this item.
808        if (cellX >= 0 && cellY >= 0) {
809            cellXY[0] = cellX;
810            cellXY[1] = cellY;
811            foundCellSpan = true;
812        } else if (touchXY != null) {
813            // when dragging and dropping, just find the closest free spot
814            int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY);
815            foundCellSpan = (result != null);
816        } else {
817            foundCellSpan = layout.findCellForSpan(cellXY, 1, 1);
818        }
819
820        if (!foundCellSpan) {
821            showOutOfSpaceMessage();
822            return;
823        }
824
825        final ShortcutInfo info = mModel.addShortcut(
826                this, data, container, screen, cellXY[0], cellXY[1], false);
827
828        if (!mRestoring) {
829            final View view = createShortcut(info);
830            mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1,
831                    isWorkspaceLocked());
832        }
833    }
834
835    /**
836     * Add a widget to the workspace.
837     *
838     * @param appWidgetId The app widget id
839     * @param cellInfo The position on screen where to create the widget.
840     */
841    private void completeAddAppWidget(final int appWidgetId, long container, int screen) {
842        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
843
844        // Calculate the grid spans needed to fit this widget
845        CellLayout layout = getCellLayout(container, screen);
846
847        // We want to account for the extra amount of padding that we are adding to the widget
848        // to ensure that it gets the full amount of space that it has requested
849        Resources r = getResources();
850        int requiredWidth = appWidgetInfo.minWidth +
851                r.getDimensionPixelSize(R.dimen.app_widget_padding_left) +
852                r.getDimensionPixelSize(R.dimen.app_widget_padding_right);
853        int requiredHeight = appWidgetInfo.minHeight +
854                r.getDimensionPixelSize(R.dimen.app_widget_padding_top) +
855                r.getDimensionPixelSize(R.dimen.app_widget_padding_bottom);
856        int[] spanXY = layout.rectToCell(requiredWidth, requiredHeight, null);
857
858        // Try finding open space on Launcher screen
859        // We have saved the position to which the widget was dragged-- this really only matters
860        // if we are placing widgets on a "spring-loaded" screen
861        int[] cellXY = mTmpAddItemCellCoordinates;
862        int[] touchXY = mPendingAddInfo.dropPos;
863        boolean foundCellSpan = false;
864        if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) {
865            cellXY[0] = mPendingAddInfo.cellX;
866            cellXY[1] = mPendingAddInfo.cellY;
867            foundCellSpan = true;
868        } else if (touchXY != null) {
869            // when dragging and dropping, just find the closest free spot
870            int[] result = layout.findNearestVacantArea(
871                    touchXY[0], touchXY[1], spanXY[0], spanXY[1], cellXY);
872            foundCellSpan = (result != null);
873        } else {
874            foundCellSpan = layout.findCellForSpan(cellXY, spanXY[0], spanXY[1]);
875        }
876
877        if (!foundCellSpan) {
878            if (appWidgetId != -1) {
879                // Deleting an app widget ID is a void call but writes to disk before returning
880                // to the caller...
881                new Thread("deleteAppWidgetId") {
882                    public void run() {
883                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
884                    }
885                }.start();
886            }
887            showOutOfSpaceMessage();
888            return;
889        }
890
891        // Build Launcher-specific widget info and save to database
892        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
893        launcherInfo.spanX = spanXY[0];
894        launcherInfo.spanY = spanXY[1];
895
896        LauncherModel.addItemToDatabase(this, launcherInfo,
897                container, screen, cellXY[0], cellXY[1], false);
898
899        if (!mRestoring) {
900            // Perform actual inflation because we're live
901            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
902
903            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
904            launcherInfo.hostView.setTag(launcherInfo);
905
906            mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1],
907                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
908
909            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
910        }
911    }
912
913    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
914        @Override
915        public void onReceive(Context context, Intent intent) {
916            final String action = intent.getAction();
917            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
918                mUserPresent = false;
919                mDragLayer.clearAllResizeFrames();
920                updateRunning();
921
922                // Reset AllApps to its initial state only if we are not in the middle of
923                // processing a multi-step drop
924                if (mAppsCustomizeTabHost != null && mPendingAddInfo.container == ItemInfo.NO_ID) {
925                    mAppsCustomizeTabHost.reset();
926                    showWorkspace(false);
927                }
928            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
929                mUserPresent = true;
930                updateRunning();
931            }
932        }
933    };
934
935    @Override
936    public void onAttachedToWindow() {
937        super.onAttachedToWindow();
938
939        // Listen for broadcasts related to user-presence
940        final IntentFilter filter = new IntentFilter();
941        filter.addAction(Intent.ACTION_SCREEN_OFF);
942        filter.addAction(Intent.ACTION_USER_PRESENT);
943        registerReceiver(mReceiver, filter);
944
945        mAttached = true;
946        mVisible = true;
947    }
948
949    @Override
950    public void onDetachedFromWindow() {
951        super.onDetachedFromWindow();
952        mVisible = false;
953        mDragLayer.clearAllResizeFrames();
954
955        if (mAttached) {
956            unregisterReceiver(mReceiver);
957            mAttached = false;
958        }
959        updateRunning();
960    }
961
962    public void onWindowVisibilityChanged(int visibility) {
963        mVisible = visibility == View.VISIBLE;
964        updateRunning();
965    }
966
967    private void sendAdvanceMessage(long delay) {
968        mHandler.removeMessages(ADVANCE_MSG);
969        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
970        mHandler.sendMessageDelayed(msg, delay);
971        mAutoAdvanceSentTime = System.currentTimeMillis();
972    }
973
974    private void updateRunning() {
975        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
976        if (autoAdvanceRunning != mAutoAdvanceRunning) {
977            mAutoAdvanceRunning = autoAdvanceRunning;
978            if (autoAdvanceRunning) {
979                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
980                sendAdvanceMessage(delay);
981            } else {
982                if (!mWidgetsToAdvance.isEmpty()) {
983                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
984                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
985                }
986                mHandler.removeMessages(ADVANCE_MSG);
987                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
988            }
989        }
990    }
991
992    private final Handler mHandler = new Handler() {
993        @Override
994        public void handleMessage(Message msg) {
995            if (msg.what == ADVANCE_MSG) {
996                int i = 0;
997                for (View key: mWidgetsToAdvance.keySet()) {
998                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
999                    final int delay = mAdvanceStagger * i;
1000                    if (v instanceof Advanceable) {
1001                       postDelayed(new Runnable() {
1002                           public void run() {
1003                               ((Advanceable) v).advance();
1004                           }
1005                       }, delay);
1006                    }
1007                    i++;
1008                }
1009                sendAdvanceMessage(mAdvanceInterval);
1010            }
1011        }
1012    };
1013
1014    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1015        if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return;
1016        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1017        if (v instanceof Advanceable) {
1018            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1019            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1020            updateRunning();
1021        }
1022    }
1023
1024    void removeWidgetToAutoAdvance(View hostView) {
1025        if (mWidgetsToAdvance.containsKey(hostView)) {
1026            mWidgetsToAdvance.remove(hostView);
1027            updateRunning();
1028        }
1029    }
1030
1031    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1032        removeWidgetToAutoAdvance(launcherInfo.hostView);
1033        launcherInfo.hostView = null;
1034    }
1035
1036    void showOutOfSpaceMessage() {
1037        Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1038    }
1039
1040    public LauncherAppWidgetHost getAppWidgetHost() {
1041        return mAppWidgetHost;
1042    }
1043
1044    public LauncherModel getModel() {
1045        return mModel;
1046    }
1047
1048    void closeSystemDialogs() {
1049        getWindow().closeAllPanels();
1050
1051        try {
1052            dismissDialog(DIALOG_CREATE_SHORTCUT);
1053            // Unlock the workspace if the dialog was showing
1054        } catch (Exception e) {
1055            // An exception is thrown if the dialog is not visible, which is fine
1056        }
1057
1058        try {
1059            dismissDialog(DIALOG_RENAME_FOLDER);
1060            // Unlock the workspace if the dialog was showing
1061        } catch (Exception e) {
1062            // An exception is thrown if the dialog is not visible, which is fine
1063        }
1064
1065        // Whatever we were doing is hereby canceled.
1066        mWaitingForResult = false;
1067    }
1068
1069    @Override
1070    protected void onNewIntent(Intent intent) {
1071        super.onNewIntent(intent);
1072
1073        // Close the menu
1074        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1075            // also will cancel mWaitingForResult.
1076            closeSystemDialogs();
1077
1078            closeFolder();
1079
1080            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1081                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1082
1083            // In all these cases, only animate if we're already on home
1084            mWorkspace.exitWidgetResizeMode();
1085            if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive()) {
1086                mWorkspace.moveToDefaultScreen(true);
1087            }
1088            exitSpringLoadedDragMode();
1089            showWorkspace(alreadyOnHome);
1090
1091            final View v = getWindow().peekDecorView();
1092            if (v != null && v.getWindowToken() != null) {
1093                InputMethodManager imm = (InputMethodManager)getSystemService(
1094                        INPUT_METHOD_SERVICE);
1095                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1096            }
1097
1098            // Reset AllApps to its initial state
1099            if (mAppsCustomizeTabHost != null) {
1100                mAppsCustomizeTabHost.reset();
1101            }
1102        }
1103    }
1104
1105    @Override
1106    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1107        // Do not call super here
1108        mSavedInstanceState = savedInstanceState;
1109    }
1110
1111    @Override
1112    protected void onSaveInstanceState(Bundle outState) {
1113        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage());
1114        super.onSaveInstanceState(outState);
1115
1116        outState.putInt(RUNTIME_STATE, mState.ordinal());
1117        // We close any open folder since it will not be re-opened, and we need to make sure
1118        // this state is reflected.
1119        closeFolder();
1120
1121        if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 &&
1122                mWaitingForResult) {
1123            outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container);
1124            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen);
1125            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX);
1126            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY);
1127        }
1128
1129        if (mFolderInfo != null && mWaitingForResult) {
1130            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1131            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1132        }
1133
1134        // Save the current AppsCustomize tab
1135        if (mAppsCustomizeTabHost != null) {
1136            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1137            if (currentTabTag != null) {
1138                outState.putString("apps_customize_currentTab", currentTabTag);
1139            }
1140        }
1141    }
1142
1143    @Override
1144    public void onDestroy() {
1145        super.onDestroy();
1146
1147        // Remove all pending runnables
1148        mHandler.removeMessages(ADVANCE_MSG);
1149        mHandler.removeMessages(0);
1150
1151        // Stop callbacks from LauncherModel
1152        LauncherApplication app = ((LauncherApplication) getApplication());
1153        mModel.stopLoader();
1154        app.setLauncher(null);
1155
1156        try {
1157            mAppWidgetHost.stopListening();
1158        } catch (NullPointerException ex) {
1159            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1160        }
1161        mAppWidgetHost = null;
1162
1163        mWidgetsToAdvance.clear();
1164
1165        TextKeyListener.getInstance().release();
1166
1167
1168        unbindWorkspaceAndHotseatItems();
1169
1170        getContentResolver().unregisterContentObserver(mWidgetObserver);
1171        unregisterReceiver(mCloseSystemDialogsReceiver);
1172
1173        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1174        mWorkspace.removeAllViews();
1175        mWorkspace = null;
1176        mDragController = null;
1177
1178        ValueAnimator.clearAllAnimations();
1179    }
1180
1181    public DragController getDragController() {
1182        return mDragController;
1183    }
1184
1185    @Override
1186    public void startActivityForResult(Intent intent, int requestCode) {
1187        if (requestCode >= 0) mWaitingForResult = true;
1188        super.startActivityForResult(intent, requestCode);
1189    }
1190
1191    @Override
1192    public void startSearch(String initialQuery, boolean selectInitialQuery,
1193            Bundle appSearchData, boolean globalSearch) {
1194
1195        showWorkspace(true);
1196
1197        if (initialQuery == null) {
1198            // Use any text typed in the launcher as the initial query
1199            initialQuery = getTypedText();
1200            clearTypedText();
1201        }
1202        if (appSearchData == null) {
1203            appSearchData = new Bundle();
1204            appSearchData.putString(Search.SOURCE, "launcher-search");
1205        }
1206
1207        final SearchManager searchManager =
1208                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1209        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1210            appSearchData, globalSearch);
1211    }
1212
1213    /**
1214     * Indicates that we want global search for this activity by setting the globalSearch
1215     * argument for {@link #startSearch} to true.
1216     */
1217
1218    @Override
1219    public boolean onSearchRequested() {
1220        startSearch(null, false, null, true);
1221        // Use a custom animation for launching search
1222        overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
1223        return true;
1224    }
1225
1226    public boolean isWorkspaceLocked() {
1227        return mWorkspaceLoading || mWaitingForResult;
1228    }
1229
1230    private void addItems() {
1231        showWorkspace(true);
1232        showAddDialog();
1233    }
1234
1235    private void resetAddInfo() {
1236        mPendingAddInfo.container = ItemInfo.NO_ID;
1237        mPendingAddInfo.screen = -1;
1238        mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1;
1239        mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1;
1240        mPendingAddInfo.dropPos = null;
1241    }
1242
1243    private void manageApps() {
1244        startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS));
1245    }
1246
1247    void addAppWidgetFromPick(Intent data) {
1248        // TODO: catch bad widget exception when sent
1249        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1250        // TODO: Is this log message meaningful?
1251        if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras());
1252        addAppWidgetImpl(appWidgetId, null);
1253    }
1254
1255    void addAppWidgetImpl(int appWidgetId, PendingAddWidgetInfo info) {
1256        AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1257
1258        if (appWidget.configure != null) {
1259            // Launch over to configure widget, if needed
1260            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1261            intent.setComponent(appWidget.configure);
1262            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1263            if (info != null) {
1264                if (info.mimeType != null && !info.mimeType.isEmpty()) {
1265                    intent.putExtra(
1266                            InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA_MIME_TYPE,
1267                            info.mimeType);
1268
1269                    final String mimeType = info.mimeType;
1270                    final ClipData clipData = (ClipData) info.configurationData;
1271                    final ClipDescription clipDesc = clipData.getDescription();
1272                    for (int i = 0; i < clipDesc.getMimeTypeCount(); ++i) {
1273                        if (clipDesc.getMimeType(i).equals(mimeType)) {
1274                            final ClipData.Item item = clipData.getItemAt(i);
1275                            final CharSequence stringData = item.getText();
1276                            final Uri uriData = item.getUri();
1277                            final Intent intentData = item.getIntent();
1278                            final String key =
1279                                InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA;
1280                            if (uriData != null) {
1281                                intent.putExtra(key, uriData);
1282                            } else if (intentData != null) {
1283                                intent.putExtra(key, intentData);
1284                            } else if (stringData != null) {
1285                                intent.putExtra(key, stringData);
1286                            }
1287                            break;
1288                        }
1289                    }
1290                }
1291            }
1292
1293            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1294        } else {
1295            // Otherwise just add it
1296            completeAddAppWidget(appWidgetId, info.container, info.screen);
1297
1298            // Exit spring loaded mode if necessary after adding the widget
1299            exitSpringLoadedDragModeDelayed(true, false);
1300        }
1301    }
1302
1303    /**
1304     * Process a shortcut drop.
1305     *
1306     * @param componentName The name of the component
1307     * @param screen The screen where it should be added
1308     * @param cell The cell it should be added to, optional
1309     * @param position The location on the screen where it was dropped, optional
1310     */
1311    void processShortcutFromDrop(ComponentName componentName, long container, int screen,
1312            int[] cell, int[] loc) {
1313        resetAddInfo();
1314        mPendingAddInfo.container = container;
1315        mPendingAddInfo.screen = screen;
1316        mPendingAddInfo.dropPos = loc;
1317
1318        if (cell != null) {
1319            mPendingAddInfo.cellX = cell[0];
1320            mPendingAddInfo.cellY = cell[1];
1321        }
1322
1323        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1324        createShortcutIntent.setComponent(componentName);
1325        processShortcut(createShortcutIntent);
1326    }
1327
1328    /**
1329     * Process a widget drop.
1330     *
1331     * @param info The PendingAppWidgetInfo of the widget being added.
1332     * @param screen The screen where it should be added
1333     * @param cell The cell it should be added to, optional
1334     * @param position The location on the screen where it was dropped, optional
1335     */
1336    void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen,
1337            int[] cell, int[] loc) {
1338        resetAddInfo();
1339        mPendingAddInfo.container = info.container = container;
1340        mPendingAddInfo.screen = info.screen = screen;
1341        mPendingAddInfo.dropPos = loc;
1342        if (cell != null) {
1343            mPendingAddInfo.cellX = cell[0];
1344            mPendingAddInfo.cellY = cell[1];
1345        }
1346
1347        int appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1348        AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, info.componentName);
1349        addAppWidgetImpl(appWidgetId, info);
1350    }
1351
1352    void processShortcut(Intent intent) {
1353        // Handle case where user selected "Applications"
1354        String applicationName = getResources().getString(R.string.group_applications);
1355        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1356
1357        if (applicationName != null && applicationName.equals(shortcutName)) {
1358            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1359            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1360
1361            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1362            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1363            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
1364            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1365        } else {
1366            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1367        }
1368    }
1369
1370    void processWallpaper(Intent intent) {
1371        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
1372    }
1373
1374    FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX,
1375            int cellY) {
1376        final FolderInfo folderInfo = new FolderInfo();
1377        folderInfo.title = getText(R.string.folder_name);
1378
1379        // Update the model
1380        LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY,
1381                false);
1382        sFolders.put(folderInfo.id, folderInfo);
1383
1384        // Create the view
1385        FolderIcon newFolder =
1386            FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache);
1387        mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1,
1388                isWorkspaceLocked());
1389        return newFolder;
1390    }
1391
1392    void removeFolder(FolderInfo folder) {
1393        sFolders.remove(folder.id);
1394    }
1395
1396    private void showNotifications() {
1397        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1398        if (statusBar != null) {
1399            statusBar.expand();
1400        }
1401    }
1402
1403    private void startWallpaper() {
1404        showWorkspace(true);
1405        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1406        Intent chooser = Intent.createChooser(pickWallpaper,
1407                getText(R.string.chooser_wallpaper));
1408        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1409        //       Removed in Eclair MR1
1410//        WallpaperManager wm = (WallpaperManager)
1411//                getSystemService(Context.WALLPAPER_SERVICE);
1412//        WallpaperInfo wi = wm.getWallpaperInfo();
1413//        if (wi != null && wi.getSettingsActivity() != null) {
1414//            LabeledIntent li = new LabeledIntent(getPackageName(),
1415//                    R.string.configure_wallpaper, 0);
1416//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1417//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1418//        }
1419        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1420    }
1421
1422    /**
1423     * Registers various content observers. The current implementation registers
1424     * only a favorites observer to keep track of the favorites applications.
1425     */
1426    private void registerContentObservers() {
1427        ContentResolver resolver = getContentResolver();
1428        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1429                true, mWidgetObserver);
1430    }
1431
1432    @Override
1433    public boolean dispatchKeyEvent(KeyEvent event) {
1434        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1435            switch (event.getKeyCode()) {
1436                case KeyEvent.KEYCODE_HOME:
1437                    return true;
1438                case KeyEvent.KEYCODE_VOLUME_DOWN:
1439                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1440                        dumpState();
1441                        return true;
1442                    }
1443                    break;
1444            }
1445        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1446            switch (event.getKeyCode()) {
1447                case KeyEvent.KEYCODE_HOME:
1448                    return true;
1449            }
1450        }
1451
1452        return super.dispatchKeyEvent(event);
1453    }
1454
1455    @Override
1456    public void onBackPressed() {
1457        if (mState == State.APPS_CUSTOMIZE) {
1458            showWorkspace(true);
1459        } else if (mWorkspace.getOpenFolder() != null) {
1460            Folder openFolder = mWorkspace.getOpenFolder();
1461            if (openFolder.isEditingName()) {
1462                openFolder.dismissEditingName();
1463            } else {
1464                closeFolder();
1465            }
1466        } else {
1467            mWorkspace.exitWidgetResizeMode();
1468
1469            // Back button is a no-op here, but give at least some feedback for the button press
1470            mWorkspace.showOutlinesTemporarily();
1471        }
1472    }
1473
1474    /**
1475     * Re-listen when widgets are reset.
1476     */
1477    private void onAppWidgetReset() {
1478        if (mAppWidgetHost != null) {
1479            mAppWidgetHost.startListening();
1480        }
1481    }
1482
1483    /**
1484     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1485     * leak the previous Home screen on orientation change.
1486     */
1487    private void unbindWorkspaceAndHotseatItems() {
1488        LauncherModel.unbindWorkspaceItems();
1489    }
1490
1491    /**
1492     * Launches the intent referred by the clicked shortcut.
1493     *
1494     * @param v The view representing the clicked shortcut.
1495     */
1496    public void onClick(View v) {
1497        // Make sure that rogue clicks don't get through while allapps is launching, or after the
1498        // view has detached (it's possible for this to happen if the view is removed mid touch).
1499        if (v.getWindowToken() == null) {
1500            return;
1501        }
1502
1503        if (mWorkspace.isSwitchingState()) {
1504            return;
1505        }
1506
1507        Object tag = v.getTag();
1508        if (tag instanceof ShortcutInfo) {
1509            // Open shortcut
1510            final Intent intent = ((ShortcutInfo) tag).intent;
1511            int[] pos = new int[2];
1512            v.getLocationOnScreen(pos);
1513            intent.setSourceBounds(new Rect(pos[0], pos[1],
1514                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1515            boolean success = startActivitySafely(intent, tag);
1516
1517            if (success && v instanceof BubbleTextView) {
1518                mWaitingForResume = (BubbleTextView) v;
1519                mWaitingForResume.setStayPressed(true);
1520            }
1521        } else if (tag instanceof FolderInfo) {
1522            if (v instanceof FolderIcon) {
1523                FolderIcon fi = (FolderIcon) v;
1524                handleFolderClick(fi);
1525            }
1526        } else if (v == mAllAppsButton) {
1527            if (mState == State.APPS_CUSTOMIZE) {
1528                showWorkspace(true);
1529            } else {
1530                showAllApps(true);
1531            }
1532        }
1533    }
1534
1535    public boolean onTouch(View v, MotionEvent event) {
1536        // this is an intercepted event being forwarded from mWorkspace;
1537        // clicking anywhere on the workspace causes the customization drawer to slide down
1538        showWorkspace(true);
1539        return false;
1540    }
1541
1542    /**
1543     * Event handler for the search button
1544     *
1545     * @param v The view that was clicked.
1546     */
1547    public void onClickSearchButton(View v) {
1548        onSearchRequested();
1549    }
1550
1551    /**
1552     * Event handler for the voice button
1553     *
1554     * @param v The view that was clicked.
1555     */
1556    public void onClickVoiceButton(View v) {
1557        startVoiceSearch();
1558    }
1559
1560    private void startVoiceSearch() {
1561        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1562        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1563        startActivity(intent);
1564    }
1565
1566    /**
1567     * Event handler for the "grid" button that appears on the home screen, which
1568     * enters all apps mode.
1569     *
1570     * @param v The view that was clicked.
1571     */
1572    public void onClickAllAppsButton(View v) {
1573        showAllApps(true);
1574    }
1575
1576    public void onClickAppMarketButton(View v) {
1577        if (mAppMarketIntent != null) {
1578            startActivitySafely(mAppMarketIntent, "app market");
1579        }
1580    }
1581
1582    void startApplicationDetailsActivity(ComponentName componentName) {
1583        String packageName = componentName.getPackageName();
1584        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
1585                Uri.fromParts("package", packageName, null));
1586        startActivity(intent);
1587    }
1588
1589    void startApplicationUninstallActivity(ApplicationInfo appInfo) {
1590        if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
1591            // System applications cannot be installed. For now, show a toast explaining that.
1592            // We may give them the option of disabling apps this way.
1593            int messageId = R.string.uninstall_system_app_text;
1594            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
1595        } else {
1596            String packageName = appInfo.componentName.getPackageName();
1597            String className = appInfo.componentName.getClassName();
1598            Intent intent = new Intent(
1599                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
1600            startActivity(intent);
1601        }
1602    }
1603
1604    boolean startActivitySafely(Intent intent, Object tag) {
1605        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1606        try {
1607            startActivity(intent);
1608            return true;
1609        } catch (ActivityNotFoundException e) {
1610            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1611            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1612        } catch (SecurityException e) {
1613            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1614            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1615                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1616                    "or use the exported attribute for this activity. "
1617                    + "tag="+ tag + " intent=" + intent, e);
1618        }
1619        return false;
1620    }
1621
1622    void startActivityForResultSafely(Intent intent, int requestCode) {
1623        try {
1624            startActivityForResult(intent, requestCode);
1625        } catch (ActivityNotFoundException e) {
1626            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1627        } catch (SecurityException e) {
1628            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1629            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1630                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1631                    "or use the exported attribute for this activity.", e);
1632        }
1633    }
1634
1635    private void handleFolderClick(FolderIcon folderIcon) {
1636        final FolderInfo info = folderIcon.mInfo;
1637        if (!info.opened) {
1638            // Close any open folder
1639            closeFolder();
1640            // Open the requested folder
1641            openFolder(folderIcon);
1642        } else {
1643            // Find the open folder...
1644            Folder openFolder = mWorkspace.getFolderForTag(info);
1645            int folderScreen;
1646            if (openFolder != null) {
1647                folderScreen = mWorkspace.getPageForView(openFolder);
1648                // .. and close it
1649                closeFolder(openFolder);
1650                if (folderScreen != mWorkspace.getCurrentPage()) {
1651                    // Close any folder open on the current screen
1652                    closeFolder();
1653                    // Pull the folder onto this screen
1654                    openFolder(folderIcon);
1655                }
1656            }
1657        }
1658    }
1659
1660    private void growAndFadeOutFolderIcon(FolderIcon fi) {
1661        if (fi == null) return;
1662        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
1663        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
1664        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
1665
1666        FolderInfo info = (FolderInfo) fi.getTag();
1667        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1668            CellLayout cl = (CellLayout) fi.getParent().getParent();
1669            CellLayout.LayoutParams lp = (CellLayout.LayoutParams) fi.getLayoutParams();
1670            cl.setFolderLeaveBehindCell(lp.cellX, lp.cellY);
1671        }
1672
1673        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
1674        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
1675        oa.start();
1676    }
1677
1678    private void shrinkAndFadeInFolderIcon(FolderIcon fi) {
1679        if (fi == null) return;
1680        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
1681        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
1682        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
1683
1684        FolderInfo info = (FolderInfo) fi.getTag();
1685        CellLayout cl = null;
1686        if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1687            cl = (CellLayout) fi.getParent().getParent();
1688        }
1689
1690        final CellLayout layout = cl;
1691        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
1692        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
1693        oa.addListener(new AnimatorListenerAdapter() {
1694            @Override
1695            public void onAnimationEnd(Animator animation) {
1696                if (layout != null) {
1697                    layout.clearFolderLeaveBehind();
1698                }
1699            }
1700        });
1701        oa.start();
1702    }
1703
1704    /**
1705     * Opens the user folder described by the specified tag. The opening of the folder
1706     * is animated relative to the specified View. If the View is null, no animation
1707     * is played.
1708     *
1709     * @param folderInfo The FolderInfo describing the folder to open.
1710     */
1711    public void openFolder(FolderIcon folderIcon) {
1712        Folder folder = folderIcon.mFolder;
1713        FolderInfo info = folder.mInfo;
1714
1715        growAndFadeOutFolderIcon(folderIcon);
1716        info.opened = true;
1717
1718        // Just verify that the folder hasn't already been added to the DragLayer.
1719        // There was a one-off crash where the folder had a parent already.
1720        if (folder.getParent() == null) {
1721            mDragLayer.addView(folder);
1722            mDragController.addDropTarget((DropTarget) folder);
1723        } else {
1724            Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" +
1725                    folder.getParent() + ").");
1726        }
1727        folder.animateOpen();
1728    }
1729
1730    public void closeFolder() {
1731        Folder folder = mWorkspace.getOpenFolder();
1732        if (folder != null) {
1733            closeFolder(folder);
1734        }
1735    }
1736
1737    void closeFolder(Folder folder) {
1738        folder.getInfo().opened = false;
1739
1740        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
1741        if (parent != null) {
1742            FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo);
1743            shrinkAndFadeInFolderIcon(fi);
1744        }
1745        folder.animateClosed();
1746    }
1747
1748    public boolean onLongClick(View v) {
1749        if (mState != State.WORKSPACE) {
1750            return false;
1751        }
1752
1753        if (isWorkspaceLocked()) {
1754            return false;
1755        }
1756
1757        if (!(v instanceof CellLayout)) {
1758            v = (View) v.getParent().getParent();
1759        }
1760
1761        resetAddInfo();
1762        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
1763        // This happens when long clicking an item with the dpad/trackball
1764        if (longClickCellInfo == null) {
1765            return true;
1766        }
1767
1768        // The hotseat touch handling does not go through Workspace, and we always allow long press
1769        // on hotseat items.
1770        final View itemUnderLongClick = longClickCellInfo.cell;
1771        boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress();
1772        if (allowLongPress && !mDragController.isDragging()) {
1773            if (itemUnderLongClick == null) {
1774                // User long pressed on empty space
1775                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1776                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1777                startWallpaper();
1778            } else {
1779                if (!(itemUnderLongClick instanceof Folder)) {
1780                    // User long pressed on an item
1781                    mWorkspace.startDrag(longClickCellInfo);
1782                }
1783            }
1784        }
1785        return true;
1786    }
1787
1788    boolean isHotseatLayout(View layout) {
1789        return mHotseat != null && layout != null &&
1790                (layout instanceof CellLayout) && (layout == mHotseat.getLayout());
1791    }
1792    Hotseat getHotseat() {
1793        return mHotseat;
1794    }
1795
1796    /**
1797     * Returns the CellLayout of the specified container at the specified screen.
1798     */
1799    CellLayout getCellLayout(long container, int screen) {
1800        if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) {
1801            if (mHotseat != null) {
1802                return mHotseat.getLayout();
1803            } else {
1804                return null;
1805            }
1806        } else {
1807            return (CellLayout) mWorkspace.getChildAt(screen);
1808        }
1809    }
1810
1811    Workspace getWorkspace() {
1812        return mWorkspace;
1813    }
1814
1815    @Override
1816    protected Dialog onCreateDialog(int id) {
1817        switch (id) {
1818            case DIALOG_CREATE_SHORTCUT:
1819                return new CreateShortcut().createDialog();
1820            case DIALOG_RENAME_FOLDER:
1821                return new RenameFolder().createDialog();
1822        }
1823
1824        return super.onCreateDialog(id);
1825    }
1826
1827    @Override
1828    protected void onPrepareDialog(int id, Dialog dialog) {
1829        switch (id) {
1830            case DIALOG_CREATE_SHORTCUT:
1831                break;
1832            case DIALOG_RENAME_FOLDER:
1833                if (mFolderInfo != null) {
1834                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1835                    final CharSequence text = mFolderInfo.title;
1836                    input.setText(text);
1837                    input.setSelection(0, text.length());
1838                }
1839                break;
1840        }
1841    }
1842
1843    void showRenameDialog(FolderInfo info) {
1844        mFolderInfo = info;
1845        mWaitingForResult = true;
1846        showDialog(DIALOG_RENAME_FOLDER);
1847    }
1848
1849    private void showAddDialog() {
1850        resetAddInfo();
1851        mPendingAddInfo.container = LauncherSettings.Favorites.CONTAINER_DESKTOP;
1852        mPendingAddInfo.screen = mWorkspace.getCurrentPage();
1853        mWaitingForResult = true;
1854        showDialog(DIALOG_CREATE_SHORTCUT);
1855    }
1856
1857    private class RenameFolder {
1858        private EditText mInput;
1859
1860        Dialog createDialog() {
1861            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1862            mInput = (EditText) layout.findViewById(R.id.folder_name);
1863
1864            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1865            builder.setIcon(0);
1866            builder.setTitle(getString(R.string.rename_folder_title));
1867            builder.setCancelable(true);
1868            builder.setOnCancelListener(new Dialog.OnCancelListener() {
1869                public void onCancel(DialogInterface dialog) {
1870                    cleanup();
1871                }
1872            });
1873            builder.setNegativeButton(getString(R.string.cancel_action),
1874                new Dialog.OnClickListener() {
1875                    public void onClick(DialogInterface dialog, int which) {
1876                        cleanup();
1877                    }
1878                }
1879            );
1880            builder.setPositiveButton(getString(R.string.rename_action),
1881                new Dialog.OnClickListener() {
1882                    public void onClick(DialogInterface dialog, int which) {
1883                        changeFolderName();
1884                    }
1885                }
1886            );
1887            builder.setView(layout);
1888
1889            final AlertDialog dialog = builder.create();
1890            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1891                public void onShow(DialogInterface dialog) {
1892                    mWaitingForResult = true;
1893                    mInput.requestFocus();
1894                    InputMethodManager inputManager = (InputMethodManager)
1895                            getSystemService(Context.INPUT_METHOD_SERVICE);
1896                    inputManager.showSoftInput(mInput, 0);
1897                }
1898            });
1899
1900            return dialog;
1901        }
1902
1903        private void changeFolderName() {
1904            final String name = mInput.getText().toString();
1905            if (!TextUtils.isEmpty(name)) {
1906                // Make sure we have the right folder info
1907                mFolderInfo = sFolders.get(mFolderInfo.id);
1908                mFolderInfo.title = name;
1909                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1910
1911                if (mWorkspaceLoading) {
1912                    lockAllApps();
1913                    mModel.startLoader(Launcher.this, false);
1914                } else {
1915                    final FolderIcon folderIcon = (FolderIcon)
1916                            mWorkspace.getViewForTag(mFolderInfo);
1917                    if (folderIcon != null) {
1918                        // TODO: At some point we'll probably want some version of setting
1919                        // the text for a folder icon.
1920                        //folderIcon.setText(name);
1921                        getWorkspace().requestLayout();
1922                    } else {
1923                        lockAllApps();
1924                        mWorkspaceLoading = true;
1925                        mModel.startLoader(Launcher.this, false);
1926                    }
1927                }
1928            }
1929            cleanup();
1930        }
1931
1932        private void cleanup() {
1933            dismissDialog(DIALOG_RENAME_FOLDER);
1934            mWaitingForResult = false;
1935            mFolderInfo = null;
1936        }
1937    }
1938
1939    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
1940    public boolean isAllAppsVisible() {
1941        return (mState == State.APPS_CUSTOMIZE);
1942    }
1943
1944    // AllAppsView.Watcher
1945    public void zoomed(float zoom) {
1946        if (zoom == 1.0f) {
1947            mWorkspace.setVisibility(View.GONE);
1948        }
1949    }
1950
1951    /**
1952     * Helper method for the cameraZoomIn/cameraZoomOut animations
1953     * @param view The view being animated
1954     * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
1955     * @param scaleFactor The scale factor used for the zoom
1956     */
1957    private void setPivotsForZoom(View view, State state, float scaleFactor) {
1958        final int height = view.getHeight();
1959
1960        view.setPivotX(view.getWidth() / 2.0f);
1961        // Set pivotY so that at the starting zoom factor, the view is partially
1962        // visible. Modifying initialHeightFactor changes how much of the view is
1963        // initially showing, and hence the perceived angle from which the view enters.
1964        if (state == State.APPS_CUSTOMIZE) {
1965            final float initialHeightFactor = 0.175f;
1966            view.setPivotY((1 - initialHeightFactor) * height);
1967        } else {
1968            final float initialHeightFactor = 0.2f;
1969            view.setPivotY(-initialHeightFactor * height);
1970        }
1971    }
1972
1973    /**
1974     * Zoom the camera out from the workspace to reveal 'toView'.
1975     * Assumes that the view to show is anchored at either the very top or very bottom
1976     * of the screen.
1977     * @param toState The state to zoom out to. Must be APPS_CUSTOMIZE.
1978     */
1979    private void cameraZoomOut(State toState, boolean animated, final boolean springLoaded) {
1980        final Resources res = getResources();
1981
1982        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
1983        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
1984        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
1985        final View toView = mAppsCustomizeTabHost;
1986
1987        setPivotsForZoom(toView, toState, scale);
1988
1989        // Shrink workspaces away if going to AppsCustomize from workspace
1990        mWorkspace.shrink(Workspace.State.SMALL, animated);
1991        hideHotseat(animated);
1992
1993        if (animated) {
1994            final ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
1995            scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
1996            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
1997                public void onAnimationUpdate(float a, float b) {
1998                    ((View) toView.getParent()).fastInvalidate();
1999                    toView.setFastScaleX(a * scale + b * 1f);
2000                    toView.setFastScaleY(a * scale + b * 1f);
2001                }
2002            });
2003
2004            toView.setVisibility(View.VISIBLE);
2005            toView.setFastAlpha(0f);
2006            ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(fadeDuration);
2007            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2008            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2009                public void onAnimationUpdate(float a, float b) {
2010                    // don't need to invalidate because we do so above
2011                    toView.setFastAlpha(a * 0f + b * 1f);
2012                }
2013            });
2014            alphaAnim.start();
2015
2016            if (toView instanceof LauncherTransitionable) {
2017                ((LauncherTransitionable) toView).onLauncherTransitionStart(scaleAnim, false);
2018            }
2019            scaleAnim.addListener(new AnimatorListenerAdapter() {
2020                @Override
2021                public void onAnimationStart(Animator animation) {
2022                    // Prepare the position
2023                    toView.setTranslationX(0.0f);
2024                    toView.setTranslationY(0.0f);
2025                    toView.setVisibility(View.VISIBLE);
2026                    toView.bringToFront();
2027                }
2028                @Override
2029                public void onAnimationEnd(Animator animation) {
2030                    // If we don't set the final scale values here, if this animation is cancelled
2031                    // it will have the wrong scale value and subsequent cameraPan animations will
2032                    // not fix that
2033                    toView.setScaleX(1.0f);
2034                    toView.setScaleY(1.0f);
2035                    if (toView instanceof LauncherTransitionable) {
2036                        ((LauncherTransitionable) toView).onLauncherTransitionEnd(scaleAnim, false);
2037                    }
2038
2039                    if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2040                        // Hide the workspace scrollbar
2041                        mWorkspace.hideScrollingIndicator(true);
2042                        mWorkspace.hideDockDivider(true);
2043                    }
2044                }
2045            });
2046
2047            // toView should appear right at the end of the workspace shrink animation
2048            final int startDelay = 0;
2049
2050            if (mStateAnimation != null) mStateAnimation.cancel();
2051            mStateAnimation = new AnimatorSet();
2052            mStateAnimation.play(scaleAnim).after(startDelay);
2053            mStateAnimation.start();
2054        } else {
2055            toView.setTranslationX(0.0f);
2056            toView.setTranslationY(0.0f);
2057            toView.setScaleX(1.0f);
2058            toView.setScaleY(1.0f);
2059            toView.setVisibility(View.VISIBLE);
2060            toView.bringToFront();
2061            if (toView instanceof LauncherTransitionable) {
2062                ((LauncherTransitionable) toView).onLauncherTransitionStart(null, false);
2063                ((LauncherTransitionable) toView).onLauncherTransitionEnd(null, false);
2064
2065                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2066                    // Hide the workspace scrollbar
2067                    mWorkspace.hideScrollingIndicator(true);
2068                    mWorkspace.hideDockDivider(true);
2069                }
2070            }
2071        }
2072    }
2073
2074    /**
2075     * Zoom the camera back into the workspace, hiding 'fromView'.
2076     * This is the opposite of cameraZoomOut.
2077     * @param fromState The current state (must be APPS_CUSTOMIZE).
2078     * @param animated If true, the transition will be animated.
2079     */
2080    private void cameraZoomIn(State fromState, boolean animated, final boolean springLoaded) {
2081        Resources res = getResources();
2082
2083        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2084        final float scaleFactor = (float)
2085                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2086        final View fromView = mAppsCustomizeTabHost;
2087
2088        setPivotsForZoom(fromView, fromState, scaleFactor);
2089
2090        if (!springLoaded) {
2091            mWorkspace.unshrink(animated);
2092        }
2093        showHotseat(animated);
2094        if (animated) {
2095            if (mStateAnimation != null) mStateAnimation.cancel();
2096            mStateAnimation = new AnimatorSet();
2097
2098            final float oldScaleX = fromView.getScaleX();
2099            final float oldScaleY = fromView.getScaleY();
2100
2101            ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2102            scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator());
2103            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2104                public void onAnimationUpdate(float a, float b) {
2105                    ((View)fromView.getParent()).fastInvalidate();
2106                    fromView.setFastScaleX(a * oldScaleX + b * scaleFactor);
2107                    fromView.setFastScaleY(a * oldScaleY + b * scaleFactor);
2108                }
2109            });
2110            final ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f);
2111            alphaAnim.setDuration(res.getInteger(R.integer.config_appsCustomizeFadeOutTime));
2112            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2113            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2114                public void onAnimationUpdate(float a, float b) {
2115                    // don't need to invalidate because we do so above
2116                    fromView.setFastAlpha(a * 1f + b * 0f);
2117                }
2118            });
2119            if (fromView instanceof LauncherTransitionable) {
2120                ((LauncherTransitionable) fromView).onLauncherTransitionStart(alphaAnim, true);
2121            }
2122            alphaAnim.addListener(new AnimatorListenerAdapter() {
2123                @Override
2124                public void onAnimationStart(android.animation.Animator animation) {
2125                    if (!springLoaded) {
2126                        mWorkspace.showDockDivider(false);
2127                    }
2128                    mWorkspace.showScrollingIndicator(false);
2129                }
2130                @Override
2131                public void onAnimationEnd(Animator animation) {
2132                    fromView.setVisibility(View.GONE);
2133                    if (fromView instanceof LauncherTransitionable) {
2134                        ((LauncherTransitionable) fromView).onLauncherTransitionEnd(alphaAnim,true);
2135                    }
2136                    mWorkspace.hideScrollingIndicator(false);
2137                }
2138            });
2139
2140            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2141            mStateAnimation.start();
2142        } else {
2143            fromView.setVisibility(View.GONE);
2144            if (fromView instanceof LauncherTransitionable) {
2145                ((LauncherTransitionable) fromView).onLauncherTransitionStart(null, true);
2146                ((LauncherTransitionable) fromView).onLauncherTransitionEnd(null, true);
2147
2148                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2149                    // Flash the workspace scrollbar
2150                    mWorkspace.showDockDivider(true);
2151                    mWorkspace.flashScrollingIndicator();
2152                }
2153            }
2154        }
2155    }
2156
2157    void showWorkspace(boolean animated) {
2158        showWorkspace(animated, null);
2159    }
2160
2161    void showWorkspace(boolean animated, CellLayout layout) {
2162        if (layout != null) {
2163            // always animated, but that's ok since we never specify a layout and
2164            // want no animation
2165            mWorkspace.unshrink(layout);
2166        } else {
2167            mWorkspace.unshrink(animated);
2168        }
2169        if (mState == State.APPS_CUSTOMIZE) {
2170            closeAllApps(animated);
2171        }
2172
2173        // Change the state *after* we've called all the transition code
2174        mState = State.WORKSPACE;
2175
2176        // Resume the auto-advance of widgets
2177        mUserPresent = true;
2178        updateRunning();
2179
2180        // send an accessibility event to announce the context change
2181        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2182    }
2183
2184    void enterSpringLoadedDragMode(CellLayout layout) {
2185        if (mState == State.APPS_CUSTOMIZE) {
2186            mWorkspace.enterSpringLoadedDragMode(layout);
2187            cameraZoomIn(State.APPS_CUSTOMIZE, true, true);
2188            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2189        }
2190        // Otherwise, we are not in spring loaded mode, so don't do anything.
2191    }
2192    void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay) {
2193        mHandler.postDelayed(new Runnable() {
2194            @Override
2195            public void run() {
2196                exitSpringLoadedDragMode();
2197
2198                if (successfulDrop) {
2199                    // Before we show workspace, hide all apps again because
2200                    // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should
2201                    // clean up our state transition functions
2202                    mAppsCustomizeTabHost.setVisibility(View.GONE);
2203                    showWorkspace(true);
2204                }
2205            }
2206        }, (extendedDelay ?
2207                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
2208                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
2209    }
2210    void exitSpringLoadedDragMode() {
2211        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2212            mWorkspace.exitSpringLoadedDragMode(Workspace.State.SMALL);
2213            cameraZoomOut(State.APPS_CUSTOMIZE, true, true);
2214            mState = State.APPS_CUSTOMIZE;
2215        }
2216        // Otherwise, we are not in spring loaded mode, so don't do anything.
2217    }
2218
2219    public boolean isAllAppsCustomizeOpen() {
2220        return mState == State.APPS_CUSTOMIZE;
2221    }
2222
2223    /**
2224     * Shows the hotseat area.
2225     */
2226    void showHotseat(boolean animated) {
2227        if (!LauncherApplication.isScreenLarge()) {
2228            if (animated) {
2229                int duration = mSearchDeleteBar.getTransitionInDuration();
2230                mHotseat.animate().alpha(1f).setDuration(duration);
2231            } else {
2232                mHotseat.setAlpha(1f);
2233            }
2234        }
2235    }
2236
2237    /**
2238     * Hides the hotseat area.
2239     */
2240    void hideHotseat(boolean animated) {
2241        if (!LauncherApplication.isScreenLarge()) {
2242            if (animated) {
2243                int duration = mSearchDeleteBar.getTransitionOutDuration();
2244                mHotseat.animate().alpha(0f).setDuration(duration);
2245            } else {
2246                mHotseat.setAlpha(0f);
2247            }
2248        }
2249    }
2250
2251    void showAllApps(boolean animated) {
2252        if (mState != State.WORKSPACE) return;
2253
2254        cameraZoomOut(State.APPS_CUSTOMIZE, animated, false);
2255        mAppsCustomizeTabHost.requestFocus();
2256
2257        // Hide the search bar and hotseat
2258        mSearchDeleteBar.hideSearchBar(animated);
2259
2260        // Change the state *after* we've called all the transition code
2261        mState = State.APPS_CUSTOMIZE;
2262
2263        // Pause the auto-advance of widgets until we are out of AllApps
2264        mUserPresent = false;
2265        updateRunning();
2266        closeFolder();
2267
2268        // Send an accessibility event to announce the context change
2269        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2270    }
2271
2272    /**
2273     * Things to test when changing this code.
2274     *   - Home from workspace
2275     *          - from center screen
2276     *          - from other screens
2277     *   - Home from all apps
2278     *          - from center screen
2279     *          - from other screens
2280     *   - Back from all apps
2281     *          - from center screen
2282     *          - from other screens
2283     *   - Launch app from workspace and quit
2284     *          - with back
2285     *          - with home
2286     *   - Launch app from all apps and quit
2287     *          - with back
2288     *          - with home
2289     *   - Go to a screen that's not the default, then all
2290     *     apps, and launch and app, and go back
2291     *          - with back
2292     *          -with home
2293     *   - On workspace, long press power and go back
2294     *          - with back
2295     *          - with home
2296     *   - On all apps, long press power and go back
2297     *          - with back
2298     *          - with home
2299     *   - On workspace, power off
2300     *   - On all apps, power off
2301     *   - Launch an app and turn off the screen while in that app
2302     *          - Go back with home key
2303     *          - Go back with back key  TODO: make this not go to workspace
2304     *          - From all apps
2305     *          - From workspace
2306     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2307     *          - From all apps
2308     *          - From the center workspace
2309     *          - From another workspace
2310     */
2311    void closeAllApps(boolean animated) {
2312        if (mState == State.APPS_CUSTOMIZE || mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2313            mWorkspace.setVisibility(View.VISIBLE);
2314            cameraZoomIn(State.APPS_CUSTOMIZE, animated, false);
2315
2316            // Show the search bar and hotseat
2317            mSearchDeleteBar.showSearchBar(animated);
2318
2319            // Set focus to the AppsCustomize button
2320            if (mAllAppsButton != null) {
2321                mAllAppsButton.requestFocus();
2322            }
2323        }
2324    }
2325
2326    void lockAllApps() {
2327        // TODO
2328    }
2329
2330    void unlockAllApps() {
2331        // TODO
2332    }
2333
2334    /**
2335     * Add an item from all apps or customize onto the given workspace screen.
2336     * If layout is null, add to the current screen.
2337     */
2338    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
2339        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2340            showOutOfSpaceMessage();
2341        } else {
2342            layout.animateDrop();
2343        }
2344    }
2345
2346    private Drawable getExternalPackageToolbarIcon(ComponentName activityName) {
2347        try {
2348            PackageManager packageManager = getPackageManager();
2349            // Look for the toolbar icon specified in the activity meta-data
2350            Bundle metaData = packageManager.getActivityInfo(
2351                    activityName, PackageManager.GET_META_DATA).metaData;
2352            if (metaData != null) {
2353                int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
2354                if (iconResId != 0) {
2355                    Resources res = packageManager.getResourcesForActivity(activityName);
2356                    return res.getDrawable(iconResId);
2357                }
2358            }
2359        } catch (NameNotFoundException e) {
2360            // This can happen if the activity defines an invalid drawable
2361            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
2362                    " not found", e);
2363        } catch (Resources.NotFoundException nfe) {
2364            // This can happen if the activity defines an invalid drawable
2365            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
2366                    nfe);
2367        }
2368        return null;
2369    }
2370
2371    // if successful in getting icon, return it; otherwise, set button to use default drawable
2372    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
2373            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2374        TextView button = (TextView) findViewById(buttonId);
2375        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2376
2377        // If we were unable to find the icon via the meta-data, use a generic one
2378        if (toolbarIcon == null) {
2379            button.setCompoundDrawablesWithIntrinsicBounds(fallbackDrawableId, 0, 0, 0);
2380            return null;
2381        } else {
2382            button.setCompoundDrawablesWithIntrinsicBounds(toolbarIcon, null, null, null);
2383            return toolbarIcon.getConstantState();
2384        }
2385    }
2386
2387    // if successful in getting icon, return it; otherwise, set button to use default drawable
2388    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
2389            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2390        ImageView button = (ImageView) findViewById(buttonId);
2391        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2392
2393        if (button != null) {
2394            // If we were unable to find the icon via the meta-data, use a
2395            // generic one
2396            if (toolbarIcon == null) {
2397                button.setImageResource(fallbackDrawableId);
2398            } else {
2399                button.setImageDrawable(toolbarIcon);
2400            }
2401        }
2402
2403        return toolbarIcon != null ? toolbarIcon.getConstantState() : null;
2404
2405    }
2406
2407    private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2408        TextView button = (TextView) findViewById(buttonId);
2409        button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
2410    }
2411
2412    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2413        ImageView button = (ImageView) findViewById(buttonId);
2414        button.setImageDrawable(d.newDrawable(getResources()));
2415    }
2416
2417    private void updateGlobalSearchIcon() {
2418        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
2419        final View searchDivider = findViewById(R.id.search_divider);
2420
2421        final SearchManager searchManager =
2422                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2423        ComponentName activityName = searchManager.getGlobalSearchActivity();
2424        if (activityName != null) {
2425            sGlobalSearchIcon = updateButtonWithIconFromExternalActivity(
2426                    R.id.search_button, activityName, R.drawable.ic_search_normal_holo);
2427            searchButton.setVisibility(View.VISIBLE);
2428            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2429        } else {
2430            searchButton.setVisibility(View.GONE);
2431            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2432        }
2433    }
2434
2435    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
2436        updateButtonWithDrawable(R.id.search_button, d);
2437    }
2438
2439    private void updateVoiceSearchIcon() {
2440        final View searchDivider = findViewById(R.id.search_divider);
2441        final View voiceButton = findViewById(R.id.voice_button);
2442
2443        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2444        ComponentName activityName = intent.resolveActivity(getPackageManager());
2445        if (activityName != null) {
2446            sVoiceSearchIcon = updateButtonWithIconFromExternalActivity(
2447                    R.id.voice_button, activityName, R.drawable.ic_voice_search_holo);
2448            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2449            voiceButton.setVisibility(View.VISIBLE);
2450        } else {
2451            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2452            voiceButton.setVisibility(View.GONE);
2453        }
2454    }
2455
2456    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
2457        updateButtonWithDrawable(R.id.voice_button, d);
2458    }
2459
2460    /**
2461     * Sets the app market icon
2462     */
2463    private void updateAppMarketIcon() {
2464        final View marketButton = findViewById(R.id.market_button);
2465        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
2466        // Find the app market activity by resolving an intent.
2467        // (If multiple app markets are installed, it will return the ResolverActivity.)
2468        ComponentName activityName = intent.resolveActivity(getPackageManager());
2469        if (activityName != null) {
2470            mAppMarketIntent = intent;
2471            sAppMarketIcon = updateTextButtonWithIconFromExternalActivity(
2472                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo);
2473            marketButton.setVisibility(View.VISIBLE);
2474        } else {
2475            // We should hide and disable the view so that we don't try and restore the visibility
2476            // of it when we swap between drag & normal states from IconDropTarget subclasses.
2477            marketButton.setVisibility(View.GONE);
2478            marketButton.setEnabled(false);
2479        }
2480    }
2481
2482    private void updateAppMarketIcon(Drawable.ConstantState d) {
2483        updateTextButtonWithDrawable(R.id.market_button, d);
2484    }
2485
2486    /**
2487     * Displays the shortcut creation dialog and launches, if necessary, the
2488     * appropriate activity.
2489     */
2490    private class CreateShortcut implements DialogInterface.OnClickListener,
2491            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
2492            DialogInterface.OnShowListener {
2493
2494        private AddAdapter mAdapter;
2495
2496        Dialog createDialog() {
2497            mAdapter = new AddAdapter(Launcher.this);
2498
2499            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this,
2500                    AlertDialog.THEME_HOLO_DARK);
2501            builder.setAdapter(mAdapter, this);
2502
2503            AlertDialog dialog = builder.create();
2504            dialog.setOnCancelListener(this);
2505            dialog.setOnDismissListener(this);
2506            dialog.setOnShowListener(this);
2507
2508            return dialog;
2509        }
2510
2511        public void onCancel(DialogInterface dialog) {
2512            mWaitingForResult = false;
2513            cleanup();
2514        }
2515
2516        public void onDismiss(DialogInterface dialog) {
2517            mWaitingForResult = false;
2518            cleanup();
2519        }
2520
2521        private void cleanup() {
2522            try {
2523                dismissDialog(DIALOG_CREATE_SHORTCUT);
2524            } catch (Exception e) {
2525                // An exception is thrown if the dialog is not visible, which is fine
2526            }
2527        }
2528
2529        /**
2530         * Handle the action clicked in the "Add to home" dialog.
2531         */
2532        public void onClick(DialogInterface dialog, int which) {
2533            cleanup();
2534
2535            AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which);
2536            switch (item.actionTag) {
2537                case AddAdapter.ITEM_APPLICATION: {
2538                    if (mAppsCustomizeTabHost != null) {
2539                        mAppsCustomizeTabHost.selectAppsTab();
2540                    }
2541                    showAllApps(true);
2542                    break;
2543                }
2544                case AddAdapter.ITEM_APPWIDGET: {
2545                    if (mAppsCustomizeTabHost != null) {
2546                        mAppsCustomizeTabHost.selectWidgetsTab();
2547                    }
2548                    showAllApps(true);
2549                    break;
2550                }
2551                case AddAdapter.ITEM_WALLPAPER: {
2552                    startWallpaper();
2553                    break;
2554                }
2555            }
2556        }
2557
2558        public void onShow(DialogInterface dialog) {
2559            mWaitingForResult = true;
2560        }
2561    }
2562
2563    /**
2564     * Receives notifications when system dialogs are to be closed.
2565     */
2566    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2567        @Override
2568        public void onReceive(Context context, Intent intent) {
2569            closeSystemDialogs();
2570        }
2571    }
2572
2573    /**
2574     * Receives notifications whenever the appwidgets are reset.
2575     */
2576    private class AppWidgetResetObserver extends ContentObserver {
2577        public AppWidgetResetObserver() {
2578            super(new Handler());
2579        }
2580
2581        @Override
2582        public void onChange(boolean selfChange) {
2583            onAppWidgetReset();
2584        }
2585    }
2586
2587    /**
2588     * If the activity is currently paused, signal that we need to re-run the loader
2589     * in onResume.
2590     *
2591     * This needs to be called from incoming places where resources might have been loaded
2592     * while we are paused.  That is becaues the Configuration might be wrong
2593     * when we're not running, and if it comes back to what it was when we
2594     * were paused, we are not restarted.
2595     *
2596     * Implementation of the method from LauncherModel.Callbacks.
2597     *
2598     * @return true if we are currently paused.  The caller might be able to
2599     * skip some work in that case since we will come back again.
2600     */
2601    public boolean setLoadOnResume() {
2602        if (mPaused) {
2603            Log.i(TAG, "setLoadOnResume");
2604            mOnResumeNeedsLoad = true;
2605            return true;
2606        } else {
2607            return false;
2608        }
2609    }
2610
2611    /**
2612     * Implementation of the method from LauncherModel.Callbacks.
2613     */
2614    public int getCurrentWorkspaceScreen() {
2615        if (mWorkspace != null) {
2616            return mWorkspace.getCurrentPage();
2617        } else {
2618            return SCREEN_COUNT / 2;
2619        }
2620    }
2621
2622
2623    /**
2624     * Refreshes the shortcuts shown on the workspace.
2625     *
2626     * Implementation of the method from LauncherModel.Callbacks.
2627     */
2628    public void startBinding() {
2629        final Workspace workspace = mWorkspace;
2630
2631        mWorkspace.clearDropTargets();
2632        int count = workspace.getChildCount();
2633        for (int i = 0; i < count; i++) {
2634            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
2635            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
2636            layoutParent.removeAllViewsInLayout();
2637        }
2638        if (mHotseat != null) {
2639            mHotseat.resetLayout();
2640        }
2641
2642        // This wasn't being called before which resulted in a leak of AppWidgetHostViews
2643        unbindWorkspaceAndHotseatItems();
2644    }
2645
2646    /**
2647     * Bind the items start-end from the list.
2648     *
2649     * Implementation of the method from LauncherModel.Callbacks.
2650     */
2651    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
2652        setLoadOnResume();
2653
2654        final Workspace workspace = mWorkspace;
2655        for (int i=start; i<end; i++) {
2656            final ItemInfo item = shortcuts.get(i);
2657
2658            // Short circuit if we are loading dock items for a configuration which has no dock
2659            if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT &&
2660                    mHotseat == null) {
2661                continue;
2662            }
2663
2664            switch (item.itemType) {
2665                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2666                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2667                    View shortcut = createShortcut((ShortcutInfo)item);
2668                    workspace.addInScreen(shortcut, item.container, item.screen, item.cellX,
2669                            item.cellY, 1, 1, false);
2670                    break;
2671                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
2672                    FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
2673                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
2674                            (FolderInfo) item, mIconCache);
2675                    workspace.addInScreen(newFolder, item.container, item.screen, item.cellX,
2676                            item.cellY, 1, 1, false);
2677                    break;
2678            }
2679        }
2680        workspace.requestLayout();
2681    }
2682
2683    /**
2684     * Implementation of the method from LauncherModel.Callbacks.
2685     */
2686    public void bindFolders(HashMap<Long, FolderInfo> folders) {
2687        setLoadOnResume();
2688        sFolders.clear();
2689        sFolders.putAll(folders);
2690    }
2691
2692    /**
2693     * Add the views for a widget to the workspace.
2694     *
2695     * Implementation of the method from LauncherModel.Callbacks.
2696     */
2697    public void bindAppWidget(LauncherAppWidgetInfo item) {
2698        setLoadOnResume();
2699
2700        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
2701        if (DEBUG_WIDGETS) {
2702            Log.d(TAG, "bindAppWidget: " + item);
2703        }
2704        final Workspace workspace = mWorkspace;
2705
2706        final int appWidgetId = item.appWidgetId;
2707        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
2708        if (DEBUG_WIDGETS) {
2709            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
2710        }
2711
2712        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
2713
2714        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
2715        item.hostView.setTag(item);
2716
2717        workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX,
2718                item.cellY, item.spanX, item.spanY, false);
2719
2720        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
2721
2722        workspace.requestLayout();
2723
2724        if (DEBUG_WIDGETS) {
2725            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
2726                    + (SystemClock.uptimeMillis()-start) + "ms");
2727        }
2728    }
2729
2730    /**
2731     * Callback saying that there aren't any more items to bind.
2732     *
2733     * Implementation of the method from LauncherModel.Callbacks.
2734     */
2735    public void finishBindingItems() {
2736        setLoadOnResume();
2737
2738        if (mSavedState != null) {
2739            if (!mWorkspace.hasFocus()) {
2740                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
2741            }
2742            mSavedState = null;
2743        }
2744
2745        if (mSavedInstanceState != null) {
2746            super.onRestoreInstanceState(mSavedInstanceState);
2747            mSavedInstanceState = null;
2748        }
2749
2750        mWorkspaceLoading = false;
2751
2752        // If we received the result of any pending adds while the loader was running (e.g. the
2753        // widget configuration forced an orientation change), process them now.
2754        for (int i = 0; i < sPendingAddList.size(); i++) {
2755            completeAdd(sPendingAddList.get(i));
2756        }
2757        sPendingAddList.clear();
2758    }
2759
2760    /**
2761     * Updates the icons on the launcher that are affected by changes to the package list
2762     * on the device.
2763     */
2764    private void updateIconsAffectedByPackageManagerChanges() {
2765        updateAppMarketIcon();
2766        updateVoiceSearchIcon();
2767    }
2768
2769    @Override
2770    public void bindSearchablesChanged() {
2771        updateGlobalSearchIcon();
2772    }
2773
2774    /**
2775     * Add the icons for all apps.
2776     *
2777     * Implementation of the method from LauncherModel.Callbacks.
2778     */
2779    public void bindAllApplications(final ArrayList<ApplicationInfo> apps) {
2780        // Remove the progress bar entirely; we could also make it GONE
2781        // but better to remove it since we know it's not going to be used
2782        View progressBar = mAppsCustomizeTabHost.
2783            findViewById(R.id.apps_customize_progress_bar);
2784        if (progressBar != null) {
2785            ((ViewGroup)progressBar.getParent()).removeView(progressBar);
2786        }
2787        // We just post the call to setApps so the user sees the progress bar
2788        // disappear-- otherwise, it just looks like the progress bar froze
2789        // which doesn't look great
2790        mAppsCustomizeTabHost.post(new Runnable() {
2791            public void run() {
2792                if (mAppsCustomizeContent != null) {
2793                    mAppsCustomizeContent.setApps(apps);
2794                }
2795            }
2796        });
2797
2798        updateIconsAffectedByPackageManagerChanges();
2799        updateGlobalSearchIcon();
2800    }
2801
2802    /**
2803     * A package was installed.
2804     *
2805     * Implementation of the method from LauncherModel.Callbacks.
2806     */
2807    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
2808        setLoadOnResume();
2809        removeDialog(DIALOG_CREATE_SHORTCUT);
2810
2811        if (mAppsCustomizeContent != null) {
2812            mAppsCustomizeContent.addApps(apps);
2813        }
2814        updateIconsAffectedByPackageManagerChanges();
2815    }
2816
2817    /**
2818     * A package was updated.
2819     *
2820     * Implementation of the method from LauncherModel.Callbacks.
2821     */
2822    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
2823        setLoadOnResume();
2824        removeDialog(DIALOG_CREATE_SHORTCUT);
2825        if (mWorkspace != null) {
2826            mWorkspace.updateShortcuts(apps);
2827        }
2828
2829        if (mAppsCustomizeContent != null) {
2830            mAppsCustomizeContent.updateApps(apps);
2831        }
2832        updateIconsAffectedByPackageManagerChanges();
2833    }
2834
2835    /**
2836     * A package was uninstalled.
2837     *
2838     * Implementation of the method from LauncherModel.Callbacks.
2839     */
2840    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
2841        removeDialog(DIALOG_CREATE_SHORTCUT);
2842        if (permanent) {
2843            mWorkspace.removeItems(apps);
2844        }
2845
2846        if (mAppsCustomizeContent != null) {
2847            mAppsCustomizeContent.removeApps(apps);
2848        }
2849        updateIconsAffectedByPackageManagerChanges();
2850    }
2851
2852    /**
2853     * A number of packages were updated.
2854     */
2855    public void bindPackagesUpdated() {
2856
2857        if (mAppsCustomizeContent != null) {
2858            mAppsCustomizeContent.onPackagesUpdated();
2859        }
2860    }
2861
2862    private int mapConfigurationOriActivityInfoOri(int configOri) {
2863        final Display d = getWindowManager().getDefaultDisplay();
2864        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
2865        switch (d.getRotation()) {
2866        case Surface.ROTATION_0:
2867        case Surface.ROTATION_180:
2868            // We are currently in the same basic orientation as the natural orientation
2869            naturalOri = configOri;
2870            break;
2871        case Surface.ROTATION_90:
2872        case Surface.ROTATION_270:
2873            // We are currently in the other basic orientation to the natural orientation
2874            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
2875                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
2876            break;
2877        }
2878
2879        int[] oriMap = {
2880                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
2881                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
2882                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
2883                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
2884        };
2885        // Since the map starts at portrait, we need to offset if this device's natural orientation
2886        // is landscape.
2887        int indexOffset = 0;
2888        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
2889            indexOffset = 1;
2890        }
2891        return oriMap[(d.getRotation() + indexOffset) % 4];
2892    }
2893    public void lockScreenOrientation() {
2894        setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
2895                .getConfiguration().orientation));
2896    }
2897    public void unlockScreenOrientation() {
2898        mHandler.postDelayed(new Runnable() {
2899            public void run() {
2900                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
2901            }
2902        }, mRestoreScreenOrientationDelay);
2903    }
2904
2905    /**
2906     * Prints out out state for debugging.
2907     */
2908    public void dumpState() {
2909        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
2910        Log.d(TAG, "mSavedState=" + mSavedState);
2911        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
2912        Log.d(TAG, "mRestoring=" + mRestoring);
2913        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
2914        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
2915        Log.d(TAG, "sFolders.size=" + sFolders.size());
2916        mModel.dumpState();
2917
2918        if (mAppsCustomizeContent != null) {
2919            mAppsCustomizeContent.dumpState();
2920        }
2921        Log.d(TAG, "END launcher2 dump state");
2922    }
2923}
2924
2925interface LauncherTransitionable {
2926    void onLauncherTransitionStart(Animator animation, boolean toWorkspace);
2927    void onLauncherTransitionEnd(Animator animation, boolean toWorkspace);
2928}
2929