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