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