Launcher.java revision 093538671bdbce2629dd0bf788e5d3489514631e
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.State;
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        dragController.addDragListener(mWorkspace);
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
1052        // We want to account for the extra amount of padding that we are adding to the widget
1053        // to ensure that it gets the full amount of space that it has requested
1054        Resources r = getResources();
1055        int requiredWidth = appWidgetInfo.minWidth +
1056                r.getDimensionPixelSize(R.dimen.app_widget_padding_left) +
1057                r.getDimensionPixelSize(R.dimen.app_widget_padding_right);
1058        int requiredHeight = appWidgetInfo.minHeight +
1059                r.getDimensionPixelSize(R.dimen.app_widget_padding_top) +
1060                r.getDimensionPixelSize(R.dimen.app_widget_padding_bottom);
1061        int[] spanXY = layout.rectToCell(requiredWidth, requiredHeight, null);
1062
1063        // Try finding open space on Launcher screen
1064        // We have saved the position to which the widget was dragged-- this really only matters
1065        // if we are placing widgets on a "spring-loaded" screen
1066        final int[] cellXY = mTmpAddItemCellCoordinates;
1067
1068        int[] touchXY = mAddDropPosition;
1069        boolean foundCellSpan = false;
1070        if (touchXY != null) {
1071            // when dragging and dropping, just find the closest free spot
1072            CellLayout screenLayout = (CellLayout) mWorkspace.getChildAt(screen);
1073            int[] result = screenLayout.findNearestVacantArea(
1074                    touchXY[0], touchXY[1], spanXY[0], spanXY[1], cellXY);
1075            foundCellSpan = (result != null);
1076        } else {
1077            // if we long pressed on an empty cell to bring up a menu,
1078            // make sure we intersect the empty cell
1079            // if mAddIntersectCellX/Y are -1 (e.g. we used menu -> add) then
1080            // findCellForSpanThatIntersects will just ignore them
1081            foundCellSpan = layout.findCellForSpanThatIntersects(cellXY, spanXY[0], spanXY[1],
1082                    mAddIntersectCellX, mAddIntersectCellY);
1083        }
1084
1085        if (!foundCellSpan) {
1086            if (appWidgetId != -1) {
1087                // Deleting an app widget ID is a void call but writes to disk before returning
1088                // to the caller...
1089                new Thread("deleteAppWidgetId") {
1090                    public void run() {
1091                        mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1092                    }
1093                }.start();
1094            }
1095            showOutOfSpaceMessage();
1096            return;
1097        }
1098
1099        // Build Launcher-specific widget info and save to database
1100        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
1101        launcherInfo.spanX = spanXY[0];
1102        launcherInfo.spanY = spanXY[1];
1103
1104        LauncherModel.addItemToDatabase(this, launcherInfo,
1105                LauncherSettings.Favorites.CONTAINER_DESKTOP,
1106                screen, cellXY[0], cellXY[1], false);
1107
1108        if (!mRestoring) {
1109            // Perform actual inflation because we're live
1110            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1111
1112            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1113            launcherInfo.hostView.setTag(launcherInfo);
1114
1115            mWorkspace.addInScreen(launcherInfo.hostView, screen, cellXY[0], cellXY[1],
1116                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
1117
1118            addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo);
1119        }
1120    }
1121
1122    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
1123        @Override
1124        public void onReceive(Context context, Intent intent) {
1125            final String action = intent.getAction();
1126            if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1127                mUserPresent = false;
1128                updateRunning();
1129
1130                // Reset AllApps to it's initial state
1131                if (mAppsCustomizeContent != null) {
1132                    mAppsCustomizeContent.reset();
1133                }
1134            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
1135                mUserPresent = true;
1136                updateRunning();
1137            }
1138        }
1139    };
1140
1141    @Override
1142    public void onAttachedToWindow() {
1143        super.onAttachedToWindow();
1144
1145        // Listen for broadcasts related to user-presence
1146        final IntentFilter filter = new IntentFilter();
1147        filter.addAction(Intent.ACTION_SCREEN_OFF);
1148        filter.addAction(Intent.ACTION_USER_PRESENT);
1149        registerReceiver(mReceiver, filter);
1150
1151        mAttached = true;
1152        mVisible = true;
1153    }
1154
1155    @Override
1156    public void onDetachedFromWindow() {
1157        super.onDetachedFromWindow();
1158        mVisible = false;
1159
1160        if (mAttached) {
1161            unregisterReceiver(mReceiver);
1162            mAttached = false;
1163        }
1164        updateRunning();
1165    }
1166
1167    public void onWindowVisibilityChanged(int visibility) {
1168        mVisible = visibility == View.VISIBLE;
1169        updateRunning();
1170    }
1171
1172    private void sendAdvanceMessage(long delay) {
1173        mHandler.removeMessages(ADVANCE_MSG);
1174        Message msg = mHandler.obtainMessage(ADVANCE_MSG);
1175        mHandler.sendMessageDelayed(msg, delay);
1176        mAutoAdvanceSentTime = System.currentTimeMillis();
1177    }
1178
1179    private void updateRunning() {
1180        boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty();
1181        if (autoAdvanceRunning != mAutoAdvanceRunning) {
1182            mAutoAdvanceRunning = autoAdvanceRunning;
1183            if (autoAdvanceRunning) {
1184                long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft;
1185                sendAdvanceMessage(delay);
1186            } else {
1187                if (!mWidgetsToAdvance.isEmpty()) {
1188                    mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval -
1189                            (System.currentTimeMillis() - mAutoAdvanceSentTime));
1190                }
1191                mHandler.removeMessages(ADVANCE_MSG);
1192                mHandler.removeMessages(0); // Remove messages sent using postDelayed()
1193            }
1194        }
1195    }
1196
1197    private final Handler mHandler = new Handler() {
1198        @Override
1199        public void handleMessage(Message msg) {
1200            if (msg.what == ADVANCE_MSG) {
1201                int i = 0;
1202                for (View key: mWidgetsToAdvance.keySet()) {
1203                    final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId);
1204                    final int delay = mAdvanceStagger * i;
1205                    if (v instanceof Advanceable) {
1206                       postDelayed(new Runnable() {
1207                           public void run() {
1208                               ((Advanceable) v).advance();
1209                           }
1210                       }, delay);
1211                    }
1212                    i++;
1213                }
1214                sendAdvanceMessage(mAdvanceInterval);
1215            }
1216        }
1217    };
1218
1219    void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) {
1220        if (appWidgetInfo.autoAdvanceViewId == -1) return;
1221        View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId);
1222        if (v instanceof Advanceable) {
1223            mWidgetsToAdvance.put(hostView, appWidgetInfo);
1224            ((Advanceable) v).fyiWillBeAdvancedByHostKThx();
1225            updateRunning();
1226        }
1227    }
1228
1229    void removeWidgetToAutoAdvance(View hostView) {
1230        if (mWidgetsToAdvance.containsKey(hostView)) {
1231            mWidgetsToAdvance.remove(hostView);
1232            updateRunning();
1233        }
1234    }
1235
1236    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
1237        removeWidgetToAutoAdvance(launcherInfo.hostView);
1238        launcherInfo.hostView = null;
1239    }
1240
1241    void showOutOfSpaceMessage() {
1242        Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1243    }
1244
1245    public LauncherAppWidgetHost getAppWidgetHost() {
1246        return mAppWidgetHost;
1247    }
1248
1249    public LauncherModel getModel() {
1250        return mModel;
1251    }
1252
1253    void closeSystemDialogs() {
1254        getWindow().closeAllPanels();
1255
1256        try {
1257            dismissDialog(DIALOG_CREATE_SHORTCUT);
1258            // Unlock the workspace if the dialog was showing
1259        } catch (Exception e) {
1260            // An exception is thrown if the dialog is not visible, which is fine
1261        }
1262
1263        try {
1264            dismissDialog(DIALOG_RENAME_FOLDER);
1265            // Unlock the workspace if the dialog was showing
1266        } catch (Exception e) {
1267            // An exception is thrown if the dialog is not visible, which is fine
1268        }
1269
1270        // Whatever we were doing is hereby canceled.
1271        mWaitingForResult = false;
1272    }
1273
1274    @Override
1275    protected void onNewIntent(Intent intent) {
1276        super.onNewIntent(intent);
1277
1278        // Close the menu
1279        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1280            // also will cancel mWaitingForResult.
1281            closeSystemDialogs();
1282
1283            closeFolder();
1284
1285            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1286                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1287
1288            // In all these cases, only animate if we're already on home
1289            mWorkspace.unshrink(alreadyOnHome);
1290            mWorkspace.exitWidgetResizeMode();
1291            if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive()) {
1292                mWorkspace.moveToDefaultScreen(true);
1293            }
1294            showWorkspace(alreadyOnHome);
1295
1296            final View v = getWindow().peekDecorView();
1297            if (v != null && v.getWindowToken() != null) {
1298                InputMethodManager imm = (InputMethodManager)getSystemService(
1299                        INPUT_METHOD_SERVICE);
1300                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1301            }
1302
1303            // Reset AllApps to its initial state
1304            if (mAppsCustomizeContent != null) {
1305                mAppsCustomizeContent.reset();
1306            }
1307        }
1308    }
1309
1310    @Override
1311    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1312        // Do not call super here
1313        mSavedInstanceState = savedInstanceState;
1314    }
1315
1316    @Override
1317    protected void onSaveInstanceState(Bundle outState) {
1318        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage());
1319        super.onSaveInstanceState(outState);
1320
1321        outState.putInt(RUNTIME_STATE, mState.ordinal());
1322        // We close any open folder since it will not be re-opened, and we need to make sure
1323        // this state is reflected.
1324        closeFolder();
1325
1326        if (mAddScreen > -1 && mWaitingForResult) {
1327            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mAddScreen);
1328            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mAddIntersectCellX);
1329            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mAddIntersectCellY);
1330        }
1331
1332        if (mFolderInfo != null && mWaitingForResult) {
1333            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1334            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1335        }
1336
1337        // Save the current AppsCustomize tab
1338        if (mAppsCustomizeTabHost != null) {
1339            String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag();
1340            if (currentTabTag != null) {
1341                outState.putString("apps_customize_currentTab", currentTabTag);
1342            }
1343        }
1344    }
1345
1346    @Override
1347    public void onDestroy() {
1348        super.onDestroy();
1349
1350        // Stop callbacks from LauncherModel
1351        LauncherApplication app = ((LauncherApplication) getApplication());
1352        mModel.stopLoader();
1353        app.setLauncher(null);
1354
1355        try {
1356            mAppWidgetHost.stopListening();
1357        } catch (NullPointerException ex) {
1358            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1359        }
1360        mAppWidgetHost = null;
1361
1362        mWidgetsToAdvance.clear();
1363
1364        TextKeyListener.getInstance().release();
1365
1366
1367        unbindWorkspaceItems();
1368
1369        getContentResolver().unregisterContentObserver(mWidgetObserver);
1370        unregisterReceiver(mCloseSystemDialogsReceiver);
1371
1372        ((ViewGroup) mWorkspace.getParent()).removeAllViews();
1373        mWorkspace.removeAllViews();
1374        mWorkspace = null;
1375        mDragController = null;
1376
1377        ValueAnimator.clearAllAnimations();
1378    }
1379
1380    public DragController getDragController() {
1381        return mDragController;
1382    }
1383
1384    @Override
1385    public void startActivityForResult(Intent intent, int requestCode) {
1386        if (requestCode >= 0) mWaitingForResult = true;
1387        super.startActivityForResult(intent, requestCode);
1388    }
1389
1390    @Override
1391    public void startSearch(String initialQuery, boolean selectInitialQuery,
1392            Bundle appSearchData, boolean globalSearch) {
1393
1394        showWorkspace(true);
1395
1396        if (initialQuery == null) {
1397            // Use any text typed in the launcher as the initial query
1398            initialQuery = getTypedText();
1399            clearTypedText();
1400        }
1401        if (appSearchData == null) {
1402            appSearchData = new Bundle();
1403            appSearchData.putString(Search.SOURCE, "launcher-search");
1404        }
1405
1406        final SearchManager searchManager =
1407                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1408        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1409            appSearchData, globalSearch);
1410    }
1411
1412    @Override
1413    public boolean onCreateOptionsMenu(Menu menu) {
1414        if (isWorkspaceLocked()) {
1415            return false;
1416        }
1417
1418        super.onCreateOptionsMenu(menu);
1419
1420        menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
1421                .setIcon(android.R.drawable.ic_menu_add)
1422                .setAlphabeticShortcut('A');
1423        menu.add(0, MENU_MANAGE_APPS, 0, R.string.menu_manage_apps)
1424                .setIcon(android.R.drawable.ic_menu_manage)
1425                .setAlphabeticShortcut('M');
1426        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1427                 .setIcon(android.R.drawable.ic_menu_gallery)
1428                 .setAlphabeticShortcut('W');
1429        menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
1430                .setIcon(android.R.drawable.ic_search_category_default)
1431                .setAlphabeticShortcut(SearchManager.MENU_KEY);
1432        menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
1433                .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
1434                .setAlphabeticShortcut('N');
1435
1436        final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1437        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1438                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1439
1440        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1441                .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1442                .setIntent(settings);
1443
1444        return true;
1445    }
1446
1447    @Override
1448    public boolean onPrepareOptionsMenu(Menu menu) {
1449        super.onPrepareOptionsMenu(menu);
1450
1451        // TODO-APPS_CUSTOMIZE: Remove this for the phone UI at some point, along with all the menu
1452        // related code?
1453        if (mAppsCustomizeContent != null && mAppsCustomizeContent.isAnimating()) return false;
1454
1455        return true;
1456    }
1457
1458    @Override
1459    public boolean onOptionsItemSelected(MenuItem item) {
1460        switch (item.getItemId()) {
1461            case MENU_ADD:
1462                addItems();
1463                return true;
1464            case MENU_MANAGE_APPS:
1465                manageApps();
1466                return true;
1467            case MENU_WALLPAPER_SETTINGS:
1468                startWallpaper();
1469                return true;
1470            case MENU_SEARCH:
1471                onSearchRequested();
1472                return true;
1473            case MENU_NOTIFICATIONS:
1474                showNotifications();
1475                return true;
1476        }
1477
1478        return super.onOptionsItemSelected(item);
1479    }
1480
1481    /**
1482     * Indicates that we want global search for this activity by setting the globalSearch
1483     * argument for {@link #startSearch} to true.
1484     */
1485
1486    @Override
1487    public boolean onSearchRequested() {
1488        startSearch(null, false, null, true);
1489        return true;
1490    }
1491
1492    public boolean isWorkspaceLocked() {
1493        return mWorkspaceLoading || mWaitingForResult;
1494    }
1495
1496    private void addItems() {
1497        showWorkspace(true);
1498        showAddDialog(-1, -1);
1499    }
1500
1501    private void resetAddInfo() {
1502        mAddScreen = -1;
1503        mAddIntersectCellX = -1;
1504        mAddIntersectCellY = -1;
1505        mAddDropPosition = null;
1506    }
1507
1508    void addAppWidgetFromDrop(PendingAddWidgetInfo info, int screen, int[] position) {
1509        resetAddInfo();
1510        mAddScreen = screen;
1511        mAddDropPosition = position;
1512
1513        int appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1514        AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, info.componentName);
1515        addAppWidgetImpl(appWidgetId, info);
1516    }
1517
1518    private void manageApps() {
1519        startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS));
1520    }
1521
1522    void addAppWidgetFromPick(Intent data) {
1523        // TODO: catch bad widget exception when sent
1524        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1525        // TODO: Is this log message meaningful?
1526        if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras());
1527        addAppWidgetImpl(appWidgetId, null);
1528    }
1529
1530    void addAppWidgetImpl(int appWidgetId, PendingAddWidgetInfo info) {
1531        AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1532
1533        if (appWidget.configure != null) {
1534            // Launch over to configure widget, if needed
1535            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1536            intent.setComponent(appWidget.configure);
1537            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1538            if (info != null) {
1539                if (info.mimeType != null && !info.mimeType.isEmpty()) {
1540                    intent.putExtra(
1541                            InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA_MIME_TYPE,
1542                            info.mimeType);
1543
1544                    final String mimeType = info.mimeType;
1545                    final ClipData clipData = (ClipData) info.configurationData;
1546                    final ClipDescription clipDesc = clipData.getDescription();
1547                    for (int i = 0; i < clipDesc.getMimeTypeCount(); ++i) {
1548                        if (clipDesc.getMimeType(i).equals(mimeType)) {
1549                            final ClipData.Item item = clipData.getItemAt(i);
1550                            final CharSequence stringData = item.getText();
1551                            final Uri uriData = item.getUri();
1552                            final Intent intentData = item.getIntent();
1553                            final String key =
1554                                InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA;
1555                            if (uriData != null) {
1556                                intent.putExtra(key, uriData);
1557                            } else if (intentData != null) {
1558                                intent.putExtra(key, intentData);
1559                            } else if (stringData != null) {
1560                                intent.putExtra(key, stringData);
1561                            }
1562                            break;
1563                        }
1564                    }
1565                }
1566            }
1567
1568            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1569        } else {
1570            // Otherwise just add it
1571            completeAddAppWidget(appWidgetId, mAddScreen);
1572
1573            // Exit spring loaded mode if necessary after adding the widget
1574            exitSpringLoadedDragModeDelayed(false);
1575        }
1576    }
1577
1578    void processShortcutFromDrop(ComponentName componentName, int screen, int[] position) {
1579        resetAddInfo();
1580        mAddScreen = screen;
1581        mAddDropPosition = position;
1582
1583        Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1584        createShortcutIntent.setComponent(componentName);
1585        processShortcut(createShortcutIntent);
1586    }
1587
1588    void processShortcut(Intent intent) {
1589        // Handle case where user selected "Applications"
1590        String applicationName = getResources().getString(R.string.group_applications);
1591        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1592
1593        if (applicationName != null && applicationName.equals(shortcutName)) {
1594            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1595            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1596
1597            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1598            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1599            pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application));
1600            startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION);
1601        } else {
1602            startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT);
1603        }
1604    }
1605
1606    void processWallpaper(Intent intent) {
1607        startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
1608    }
1609
1610    FolderIcon addFolder(final int screen, int intersectCellX, int intersectCellY) {
1611        final FolderInfo folderInfo = new FolderInfo();
1612        folderInfo.title = getText(R.string.folder_name);
1613
1614        final CellLayout layout = (CellLayout) mWorkspace.getChildAt(screen);
1615        final int[] cellXY = mTmpAddItemCellCoordinates;
1616        if (!layout.findCellForSpanThatIntersects(cellXY, 1, 1,
1617                intersectCellX, intersectCellY)) {
1618            showOutOfSpaceMessage();
1619            return null;
1620        }
1621
1622        // Update the model
1623        LauncherModel.addItemToDatabase(Launcher.this, folderInfo,
1624                LauncherSettings.Favorites.CONTAINER_DESKTOP,
1625                screen, cellXY[0], cellXY[1], false);
1626        sFolders.put(folderInfo.id, folderInfo);
1627
1628        // Create the view
1629        FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1630                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()),
1631                folderInfo, mIconCache);
1632        mWorkspace.addInScreen(newFolder, screen, cellXY[0], cellXY[1], 1, 1, isWorkspaceLocked());
1633        return newFolder;
1634    }
1635
1636    void removeFolder(FolderInfo folder) {
1637        sFolders.remove(folder.id);
1638    }
1639
1640    private void showNotifications() {
1641        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1642        if (statusBar != null) {
1643            statusBar.expand();
1644        }
1645    }
1646
1647    private void startWallpaper() {
1648        showWorkspace(true);
1649        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1650        Intent chooser = Intent.createChooser(pickWallpaper,
1651                getText(R.string.chooser_wallpaper));
1652        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1653        //       Removed in Eclair MR1
1654//        WallpaperManager wm = (WallpaperManager)
1655//                getSystemService(Context.WALLPAPER_SERVICE);
1656//        WallpaperInfo wi = wm.getWallpaperInfo();
1657//        if (wi != null && wi.getSettingsActivity() != null) {
1658//            LabeledIntent li = new LabeledIntent(getPackageName(),
1659//                    R.string.configure_wallpaper, 0);
1660//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1661//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1662//        }
1663        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1664    }
1665
1666    /**
1667     * Registers various content observers. The current implementation registers
1668     * only a favorites observer to keep track of the favorites applications.
1669     */
1670    private void registerContentObservers() {
1671        ContentResolver resolver = getContentResolver();
1672        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1673                true, mWidgetObserver);
1674    }
1675
1676    @Override
1677    public boolean dispatchKeyEvent(KeyEvent event) {
1678        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1679            switch (event.getKeyCode()) {
1680                case KeyEvent.KEYCODE_HOME:
1681                    return true;
1682                case KeyEvent.KEYCODE_VOLUME_DOWN:
1683                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1684                        dumpState();
1685                        return true;
1686                    }
1687                    break;
1688            }
1689        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1690            switch (event.getKeyCode()) {
1691                case KeyEvent.KEYCODE_HOME:
1692                    return true;
1693            }
1694        }
1695
1696        return super.dispatchKeyEvent(event);
1697    }
1698
1699    @Override
1700    public void onBackPressed() {
1701        if (mState == State.APPS_CUSTOMIZE) {
1702            showWorkspace(true);
1703        } else if (mWorkspace.getOpenFolder() != null) {
1704            Folder openFolder = mWorkspace.getOpenFolder();
1705            if (openFolder.isEditingName()) {
1706                openFolder.dismissEditingName();
1707            } else {
1708                closeFolder();
1709            }
1710        } else {
1711            mWorkspace.exitWidgetResizeMode();
1712
1713            // Back button is a no-op here, but give at least some feedback for the button press
1714            mWorkspace.showOutlinesTemporarily();
1715        }
1716    }
1717
1718    public void closeFolder() {
1719        Folder folder = mWorkspace.getOpenFolder();
1720        if (folder != null) {
1721            closeFolder(folder);
1722        }
1723    }
1724
1725    void closeFolder(Folder folder) {
1726        folder.getInfo().opened = false;
1727
1728        ViewGroup parent = (ViewGroup) folder.getParent().getParent();
1729        if (parent != null) {
1730            CellLayout cl = (CellLayout) mWorkspace.getChildAt(folder.mInfo.screen);
1731            FolderIcon fi = (FolderIcon) cl.getChildAt(folder.mInfo.cellX, folder.mInfo.cellY);
1732            shrinkAndFadeInFolderIcon(fi);
1733            mDragController.removeDropTarget((DropTarget)folder);
1734        }
1735        folder.animateClosed();
1736    }
1737
1738    /**
1739     * Re-listen when widgets are reset.
1740     */
1741    private void onAppWidgetReset() {
1742        if (mAppWidgetHost != null) {
1743            mAppWidgetHost.startListening();
1744        }
1745    }
1746
1747    /**
1748     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1749     * leak the previous Home screen on orientation change.
1750     */
1751    private void unbindWorkspaceItems() {
1752        LauncherModel.unbindWorkspaceItems();
1753    }
1754
1755    /**
1756     * Launches the intent referred by the clicked shortcut.
1757     *
1758     * @param v The view representing the clicked shortcut.
1759     */
1760    public void onClick(View v) {
1761        Object tag = v.getTag();
1762        if (tag instanceof ShortcutInfo) {
1763            // Open shortcut
1764            final Intent intent = ((ShortcutInfo) tag).intent;
1765            int[] pos = new int[2];
1766            v.getLocationOnScreen(pos);
1767            intent.setSourceBounds(new Rect(pos[0], pos[1],
1768                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1769            boolean success = startActivitySafely(intent, tag);
1770
1771            if (success && v instanceof BubbleTextView) {
1772                mWaitingForResume = (BubbleTextView) v;
1773                mWaitingForResume.setStayPressed(true);
1774            }
1775        } else if (tag instanceof FolderInfo) {
1776            if (v instanceof FolderIcon) {
1777                FolderIcon fi = (FolderIcon) v;
1778                handleFolderClick(fi);
1779            }
1780        } else if (v == mAllAppsButton) {
1781            if (mState == State.APPS_CUSTOMIZE) {
1782                showWorkspace(true);
1783            } else {
1784                showAllApps(true);
1785            }
1786        }
1787    }
1788
1789    public boolean onTouch(View v, MotionEvent event) {
1790        // this is an intercepted event being forwarded from mWorkspace;
1791        // clicking anywhere on the workspace causes the customization drawer to slide down
1792        showWorkspace(true);
1793        return false;
1794    }
1795
1796    /**
1797     * Event handler for the search button
1798     *
1799     * @param v The view that was clicked.
1800     */
1801    public void onClickSearchButton(View v) {
1802        startSearch(null, false, null, true);
1803        // Use a custom animation for launching search
1804        overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
1805    }
1806
1807    /**
1808     * Event handler for the voice button
1809     *
1810     * @param v The view that was clicked.
1811     */
1812    public void onClickVoiceButton(View v) {
1813        startVoiceSearch();
1814    }
1815
1816    private void startVoiceSearch() {
1817        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
1818        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1819        startActivity(intent);
1820    }
1821
1822    /**
1823     * Event handler for the "gear" button that appears on the home screen, which
1824     * enters home screen customization mode.
1825     *
1826     * @param v The view that was clicked.
1827     */
1828    public void onClickConfigureButton(View v) {
1829        addItems();
1830    }
1831
1832    /**
1833     * Event handler for the "grid" button that appears on the home screen, which
1834     * enters all apps mode.
1835     *
1836     * @param v The view that was clicked.
1837     */
1838    public void onClickAllAppsButton(View v) {
1839        showAllApps(true);
1840    }
1841
1842    public void onClickAppMarketButton(View v) {
1843        if (mAppMarketIntent != null) {
1844            startActivitySafely(mAppMarketIntent, "app market");
1845        }
1846    }
1847
1848    void startApplicationDetailsActivity(ComponentName componentName) {
1849        String packageName = componentName.getPackageName();
1850        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
1851                Uri.fromParts("package", packageName, null));
1852        startActivity(intent);
1853    }
1854
1855    void startApplicationUninstallActivity(ApplicationInfo appInfo) {
1856        if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) {
1857            // System applications cannot be installed. For now, show a toast explaining that.
1858            // We may give them the option of disabling apps this way.
1859            int messageId = R.string.uninstall_system_app_text;
1860            Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show();
1861        } else {
1862            String packageName = appInfo.componentName.getPackageName();
1863            String className = appInfo.componentName.getClassName();
1864            Intent intent = new Intent(
1865                    Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className));
1866            startActivity(intent);
1867        }
1868    }
1869
1870    boolean startActivitySafely(Intent intent, Object tag) {
1871        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1872        try {
1873            startActivity(intent);
1874            return true;
1875        } catch (ActivityNotFoundException e) {
1876            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1877            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1878        } catch (SecurityException e) {
1879            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1880            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1881                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1882                    "or use the exported attribute for this activity. "
1883                    + "tag="+ tag + " intent=" + intent, e);
1884        }
1885        return false;
1886    }
1887
1888    void startActivityForResultSafely(Intent intent, int requestCode) {
1889        try {
1890            startActivityForResult(intent, requestCode);
1891        } catch (ActivityNotFoundException e) {
1892            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1893        } catch (SecurityException e) {
1894            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1895            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1896                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1897                    "or use the exported attribute for this activity.", e);
1898        }
1899    }
1900
1901    private void handleFolderClick(FolderIcon folderIcon) {
1902        final FolderInfo info = folderIcon.mInfo;
1903        if (!info.opened) {
1904            // Close any open folder
1905            closeFolder();
1906            // Open the requested folder
1907            openFolder(folderIcon);
1908        } else {
1909            // Find the open folder...
1910            Folder openFolder = mWorkspace.getFolderForTag(info);
1911            int folderScreen;
1912            if (openFolder != null) {
1913                folderScreen = mWorkspace.getPageForView(openFolder);
1914                // .. and close it
1915                closeFolder(openFolder);
1916                if (folderScreen != mWorkspace.getCurrentPage()) {
1917                    // Close any folder open on the current screen
1918                    closeFolder();
1919                    // Pull the folder onto this screen
1920                    openFolder(folderIcon);
1921                }
1922            }
1923        }
1924    }
1925
1926    private void growAndFadeOutFolderIcon(FolderIcon fi) {
1927        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0);
1928        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f);
1929        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f);
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    private void shrinkAndFadeInFolderIcon(FolderIcon fi) {
1937        PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f);
1938        PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f);
1939        PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f);
1940
1941        ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY);
1942        oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration));
1943        oa.start();
1944    }
1945
1946    /**
1947     * Opens the user folder described by the specified tag. The opening of the folder
1948     * is animated relative to the specified View. If the View is null, no animation
1949     * is played.
1950     *
1951     * @param folderInfo The FolderInfo describing the folder to open.
1952     */
1953    public void openFolder(FolderIcon folderIcon) {
1954        Folder folder = folderIcon.mFolder;
1955        FolderInfo info = folder.mInfo;
1956
1957        growAndFadeOutFolderIcon(folderIcon);
1958        info.opened = true;
1959
1960        mDragLayer.addView(folder);
1961        mDragController.addDropTarget((DropTarget) folder);
1962
1963        folder.animateOpen();
1964        folder.onOpen();
1965    }
1966
1967    public boolean onLongClick(View v) {
1968        if (mState != State.WORKSPACE) {
1969            return false;
1970        }
1971
1972        switch (v.getId()) {
1973            case R.id.all_apps_button:
1974                if (mState != State.APPS_CUSTOMIZE) {
1975                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1976                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1977                    showPreviews(v);
1978                }
1979                return true;
1980        }
1981
1982        if (isWorkspaceLocked()) {
1983            return false;
1984        }
1985
1986        if (!(v instanceof CellLayout)) {
1987            v = (View) v.getParent().getParent();
1988        }
1989
1990        resetAddInfo();
1991        CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag();
1992        // This happens when long clicking an item with the dpad/trackball
1993        if (longClickCellInfo == null || !longClickCellInfo.valid) {
1994            return true;
1995        }
1996
1997        final View itemUnderLongClick = longClickCellInfo.cell;
1998
1999        if (mWorkspace.allowLongPress() && !mDragController.isDragging()) {
2000            if (itemUnderLongClick == null) {
2001                // User long pressed on empty space
2002                mWorkspace.setAllowLongPress(false);
2003                mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2004                        HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2005                addItems();
2006            } else {
2007                if (!(itemUnderLongClick instanceof Folder)) {
2008                    // User long pressed on an item
2009                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
2010                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
2011                    mAddIntersectCellX = longClickCellInfo.cellX;
2012                    mAddIntersectCellY = longClickCellInfo.cellY;
2013                    mWorkspace.startDrag(longClickCellInfo);
2014                }
2015            }
2016        }
2017        return true;
2018    }
2019
2020    @SuppressWarnings({"unchecked"})
2021    private void dismissPreview(final View v) {
2022        final PopupWindow window = (PopupWindow) v.getTag();
2023        if (window != null) {
2024            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
2025                public void onDismiss() {
2026                    ViewGroup group = (ViewGroup) v.getTag(R.id.workspace);
2027                    int count = group.getChildCount();
2028                    for (int i = 0; i < count; i++) {
2029                        ((ImageView) group.getChildAt(i)).setImageDrawable(null);
2030                    }
2031                    ArrayList<Bitmap> bitmaps =
2032                        (ArrayList<Bitmap>) v.getTag(R.id.all_apps_button_cluster);
2033                    for (Bitmap bitmap : bitmaps) bitmap.recycle();
2034
2035                    v.setTag(R.id.workspace, null);
2036                    v.setTag(R.id.all_apps_button_cluster, null);
2037                    window.setOnDismissListener(null);
2038                }
2039            });
2040            window.dismiss();
2041        }
2042        v.setTag(null);
2043    }
2044
2045    private void showPreviews(View anchor) {
2046        showPreviews(anchor, 0, mWorkspace.getChildCount());
2047    }
2048
2049    private void showPreviews(final View anchor, int start, int end) {
2050        final Resources resources = getResources();
2051        final Workspace workspace = mWorkspace;
2052
2053        CellLayout cell = ((CellLayout) workspace.getChildAt(start));
2054
2055        float max = workspace.getChildCount();
2056
2057        final Rect r = new Rect();
2058        resources.getDrawable(R.drawable.preview_background).getPadding(r);
2059        int extraW = (int) ((r.left + r.right) * max);
2060        int extraH = r.top + r.bottom;
2061
2062        int aW = cell.getWidth() - extraW;
2063        float w = aW / max;
2064
2065        int width = cell.getWidth();
2066        int height = cell.getHeight();
2067        int x = cell.getPaddingLeft();
2068        int y = cell.getPaddingTop();
2069        width -= (x + cell.getPaddingRight());
2070        height -= (y + cell.getPaddingBottom());
2071
2072        float scale = w / width;
2073
2074        int count = end - start;
2075
2076        final float sWidth = width * scale;
2077        float sHeight = height * scale;
2078
2079        LinearLayout preview = new LinearLayout(this);
2080
2081        PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
2082        ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);
2083
2084        for (int i = start; i < end; i++) {
2085            ImageView image = new ImageView(this);
2086            cell = (CellLayout) workspace.getChildAt(i);
2087
2088            final Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
2089                    Bitmap.Config.ARGB_8888);
2090
2091            final Canvas c = new Canvas(bitmap);
2092            c.scale(scale, scale);
2093            c.translate(-cell.getPaddingLeft(), -cell.getPaddingTop());
2094            cell.drawChildren(c);
2095
2096            image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
2097            image.setImageBitmap(bitmap);
2098            image.setTag(i);
2099            image.setOnClickListener(handler);
2100            image.setOnFocusChangeListener(handler);
2101            image.setFocusable(true);
2102            if (i == mWorkspace.getCurrentPage()) image.requestFocus();
2103
2104            preview.addView(image,
2105                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
2106
2107            bitmaps.add(bitmap);
2108        }
2109
2110        final PopupWindow p = new PopupWindow(this);
2111        p.setContentView(preview);
2112        p.setWidth((int) (sWidth * count + extraW));
2113        p.setHeight((int) (sHeight + extraH));
2114        p.setAnimationStyle(R.style.AnimationPreview);
2115        p.setOutsideTouchable(true);
2116        p.setFocusable(true);
2117        p.setBackgroundDrawable(new ColorDrawable(0));
2118        p.showAsDropDown(anchor, 0, 0);
2119
2120        p.setOnDismissListener(new PopupWindow.OnDismissListener() {
2121            public void onDismiss() {
2122                dismissPreview(anchor);
2123            }
2124        });
2125
2126        anchor.setTag(p);
2127        anchor.setTag(R.id.workspace, preview);
2128        anchor.setTag(R.id.all_apps_button_cluster, bitmaps);
2129    }
2130
2131    class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener {
2132        private final View mAnchor;
2133
2134        public PreviewTouchHandler(View anchor) {
2135            mAnchor = anchor;
2136        }
2137
2138        public void onClick(View v) {
2139            mWorkspace.snapToPage((Integer) v.getTag());
2140            v.post(this);
2141        }
2142
2143        public void run() {
2144            dismissPreview(mAnchor);
2145        }
2146
2147        public void onFocusChange(View v, boolean hasFocus) {
2148            if (hasFocus) {
2149                mWorkspace.snapToPage((Integer) v.getTag());
2150            }
2151        }
2152    }
2153
2154    Workspace getWorkspace() {
2155        return mWorkspace;
2156    }
2157
2158    @Override
2159    protected Dialog onCreateDialog(int id) {
2160        switch (id) {
2161            case DIALOG_CREATE_SHORTCUT:
2162                return new CreateShortcut().createDialog();
2163            case DIALOG_RENAME_FOLDER:
2164                return new RenameFolder().createDialog();
2165        }
2166
2167        return super.onCreateDialog(id);
2168    }
2169
2170    @Override
2171    protected void onPrepareDialog(int id, Dialog dialog) {
2172        switch (id) {
2173            case DIALOG_CREATE_SHORTCUT:
2174                break;
2175            case DIALOG_RENAME_FOLDER:
2176                if (mFolderInfo != null) {
2177                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
2178                    final CharSequence text = mFolderInfo.title;
2179                    input.setText(text);
2180                    input.setSelection(0, text.length());
2181                }
2182                break;
2183        }
2184    }
2185
2186    void showRenameDialog(FolderInfo info) {
2187        mFolderInfo = info;
2188        mWaitingForResult = true;
2189        showDialog(DIALOG_RENAME_FOLDER);
2190    }
2191
2192    private void showAddDialog(int intersectX, int intersectY) {
2193        resetAddInfo();
2194        mAddIntersectCellX = intersectX;
2195        mAddIntersectCellY = intersectY;
2196        mAddScreen = mWorkspace.getCurrentPage();
2197        mWaitingForResult = true;
2198        showDialog(DIALOG_CREATE_SHORTCUT);
2199    }
2200
2201    private void pickShortcut() {
2202        // Insert extra item to handle picking application
2203        Bundle bundle = new Bundle();
2204
2205        ArrayList<String> shortcutNames = new ArrayList<String>();
2206        shortcutNames.add(getString(R.string.group_applications));
2207        bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
2208
2209        ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
2210        shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
2211                        R.drawable.ic_launcher_application));
2212        bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
2213
2214        Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
2215        pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
2216        pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_shortcut));
2217        pickIntent.putExtras(bundle);
2218
2219        startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
2220    }
2221
2222    private class RenameFolder {
2223        private EditText mInput;
2224
2225        Dialog createDialog() {
2226            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
2227            mInput = (EditText) layout.findViewById(R.id.folder_name);
2228
2229            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
2230            builder.setIcon(0);
2231            builder.setTitle(getString(R.string.rename_folder_title));
2232            builder.setCancelable(true);
2233            builder.setOnCancelListener(new Dialog.OnCancelListener() {
2234                public void onCancel(DialogInterface dialog) {
2235                    cleanup();
2236                }
2237            });
2238            builder.setNegativeButton(getString(R.string.cancel_action),
2239                new Dialog.OnClickListener() {
2240                    public void onClick(DialogInterface dialog, int which) {
2241                        cleanup();
2242                    }
2243                }
2244            );
2245            builder.setPositiveButton(getString(R.string.rename_action),
2246                new Dialog.OnClickListener() {
2247                    public void onClick(DialogInterface dialog, int which) {
2248                        changeFolderName();
2249                    }
2250                }
2251            );
2252            builder.setView(layout);
2253
2254            final AlertDialog dialog = builder.create();
2255            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
2256                public void onShow(DialogInterface dialog) {
2257                    mWaitingForResult = true;
2258                    mInput.requestFocus();
2259                    InputMethodManager inputManager = (InputMethodManager)
2260                            getSystemService(Context.INPUT_METHOD_SERVICE);
2261                    inputManager.showSoftInput(mInput, 0);
2262                }
2263            });
2264
2265            return dialog;
2266        }
2267
2268        private void changeFolderName() {
2269            final String name = mInput.getText().toString();
2270            if (!TextUtils.isEmpty(name)) {
2271                // Make sure we have the right folder info
2272                mFolderInfo = sFolders.get(mFolderInfo.id);
2273                mFolderInfo.title = name;
2274                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
2275
2276                if (mWorkspaceLoading) {
2277                    lockAllApps();
2278                    mModel.startLoader(Launcher.this, false);
2279                } else {
2280                    final FolderIcon folderIcon = (FolderIcon)
2281                            mWorkspace.getViewForTag(mFolderInfo);
2282                    if (folderIcon != null) {
2283                        // TODO: At some point we'll probably want some version of setting
2284                        // the text for a folder icon.
2285                        //folderIcon.setText(name);
2286                        getWorkspace().requestLayout();
2287                    } else {
2288                        lockAllApps();
2289                        mWorkspaceLoading = true;
2290                        mModel.startLoader(Launcher.this, false);
2291                    }
2292                }
2293            }
2294            cleanup();
2295        }
2296
2297        private void cleanup() {
2298            dismissDialog(DIALOG_RENAME_FOLDER);
2299            mWaitingForResult = false;
2300            mFolderInfo = null;
2301        }
2302    }
2303
2304    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
2305    public boolean isAllAppsVisible() {
2306        return (mState == State.APPS_CUSTOMIZE);
2307    }
2308
2309    // AllAppsView.Watcher
2310    public void zoomed(float zoom) {
2311        if (zoom == 1.0f) {
2312            mWorkspace.setVisibility(View.GONE);
2313        }
2314    }
2315
2316    /**
2317     * Helper method for the cameraZoomIn/cameraZoomOut animations
2318     * @param view The view being animated
2319     * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE)
2320     * @param scaleFactor The scale factor used for the zoom
2321     */
2322    private void setPivotsForZoom(View view, State state, float scaleFactor) {
2323        final int height = view.getHeight();
2324
2325        view.setPivotX(view.getWidth() / 2.0f);
2326        // Set pivotY so that at the starting zoom factor, the view is partially
2327        // visible. Modifying initialHeightFactor changes how much of the view is
2328        // initially showing, and hence the perceived angle from which the view enters.
2329        if (state == State.APPS_CUSTOMIZE) {
2330            final float initialHeightFactor = 0.175f;
2331            view.setPivotY((1 - initialHeightFactor) * height);
2332        } else {
2333            final float initialHeightFactor = 0.2f;
2334            view.setPivotY(-initialHeightFactor * height);
2335        }
2336    }
2337
2338    /**
2339     * Zoom the camera out from the workspace to reveal 'toView'.
2340     * Assumes that the view to show is anchored at either the very top or very bottom
2341     * of the screen.
2342     * @param toState The state to zoom out to. Must be APPS_CUSTOMIZE.
2343     */
2344    private void cameraZoomOut(State toState, boolean animated, final boolean springLoaded) {
2345        final Resources res = getResources();
2346
2347        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime);
2348        final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime);
2349        final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2350        final View toView = mAppsCustomizeTabHost;
2351
2352        setPivotsForZoom(toView, toState, scale);
2353
2354        // Shrink workspaces away if going to AppsCustomize from workspace
2355        mWorkspace.shrink(Workspace.State.SMALL, animated);
2356
2357        if (animated) {
2358            final ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2359            scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
2360            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2361                public void onAnimationUpdate(float a, float b) {
2362                    ((View) toView.getParent()).fastInvalidate();
2363                    toView.setFastScaleX(a * scale + b * 1f);
2364                    toView.setFastScaleY(a * scale + b * 1f);
2365                }
2366            });
2367
2368            toView.setVisibility(View.VISIBLE);
2369            toView.setFastAlpha(0f);
2370            ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(fadeDuration);
2371            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2372            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2373                public void onAnimationUpdate(float a, float b) {
2374                    // don't need to invalidate because we do so above
2375                    toView.setFastAlpha(a * 0f + b * 1f);
2376                }
2377            });
2378            alphaAnim.start();
2379
2380            if (toView instanceof LauncherTransitionable) {
2381                ((LauncherTransitionable) toView).onLauncherTransitionStart(scaleAnim);
2382            }
2383            scaleAnim.addListener(new AnimatorListenerAdapter() {
2384                @Override
2385                public void onAnimationStart(Animator animation) {
2386                    // Prepare the position
2387                    toView.setTranslationX(0.0f);
2388                    toView.setTranslationY(0.0f);
2389                    toView.setVisibility(View.VISIBLE);
2390                    toView.bringToFront();
2391
2392                    if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2393                        // Hide the workspace scrollbar
2394                        mWorkspace.hideScrollingIndicator(true);
2395                        mWorkspace.hideScrollIndicatorTrack();
2396                    }
2397                }
2398                @Override
2399                public void onAnimationEnd(Animator animation) {
2400                    // If we don't set the final scale values here, if this animation is cancelled
2401                    // it will have the wrong scale value and subsequent cameraPan animations will
2402                    // not fix that
2403                    toView.setScaleX(1.0f);
2404                    toView.setScaleY(1.0f);
2405                    if (toView instanceof LauncherTransitionable) {
2406                        ((LauncherTransitionable) toView).onLauncherTransitionEnd(scaleAnim);
2407                    }
2408                }
2409            });
2410
2411            // toView should appear right at the end of the workspace shrink animation
2412            final int startDelay = 0;
2413
2414            if (mStateAnimation != null) mStateAnimation.cancel();
2415            mStateAnimation = new AnimatorSet();
2416            mStateAnimation.play(scaleAnim).after(startDelay);
2417            mStateAnimation.start();
2418        } else {
2419            toView.setTranslationX(0.0f);
2420            toView.setTranslationY(0.0f);
2421            toView.setScaleX(1.0f);
2422            toView.setScaleY(1.0f);
2423            toView.setVisibility(View.VISIBLE);
2424            toView.bringToFront();
2425            if (toView instanceof LauncherTransitionable) {
2426                ((LauncherTransitionable) toView).onLauncherTransitionStart(null);
2427                ((LauncherTransitionable) toView).onLauncherTransitionEnd(null);
2428
2429                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2430                    // Hide the workspace scrollbar
2431                    mWorkspace.hideScrollingIndicator(true);
2432                    mWorkspace.hideScrollIndicatorTrack();
2433                }
2434            }
2435        }
2436    }
2437
2438    /**
2439     * Zoom the camera back into the workspace, hiding 'fromView'.
2440     * This is the opposite of cameraZoomOut.
2441     * @param fromState The current state (must be APPS_CUSTOMIZE).
2442     * @param animated If true, the transition will be animated.
2443     */
2444    private void cameraZoomIn(State fromState, boolean animated, final boolean springLoaded) {
2445        Resources res = getResources();
2446
2447        final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime);
2448        final float scaleFactor = (float)
2449                res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor);
2450        final View fromView = mAppsCustomizeTabHost;
2451
2452        setPivotsForZoom(fromView, fromState, scaleFactor);
2453
2454        if (!springLoaded) {
2455            mWorkspace.unshrink(animated);
2456        }
2457        if (animated) {
2458            if (mStateAnimation != null) mStateAnimation.cancel();
2459            mStateAnimation = new AnimatorSet();
2460
2461            final float oldScaleX = fromView.getScaleX();
2462            final float oldScaleY = fromView.getScaleY();
2463
2464            ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2465            scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator());
2466            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2467                public void onAnimationUpdate(float a, float b) {
2468                    ((View)fromView.getParent()).fastInvalidate();
2469                    fromView.setFastScaleX(a * oldScaleX + b * scaleFactor);
2470                    fromView.setFastScaleY(a * oldScaleY + b * scaleFactor);
2471                }
2472            });
2473            final ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f);
2474            alphaAnim.setDuration(res.getInteger(R.integer.config_appsCustomizeFadeOutTime));
2475            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2476            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2477                public void onAnimationUpdate(float a, float b) {
2478                    // don't need to invalidate because we do so above
2479                    fromView.setFastAlpha(a * 1f + b * 0f);
2480                }
2481            });
2482            if (fromView instanceof LauncherTransitionable) {
2483                ((LauncherTransitionable) fromView).onLauncherTransitionStart(alphaAnim);
2484            }
2485            alphaAnim.addListener(new AnimatorListenerAdapter() {
2486                @Override
2487                public void onAnimationEnd(Animator animation) {
2488                    fromView.setVisibility(View.GONE);
2489                    if (fromView instanceof LauncherTransitionable) {
2490                        ((LauncherTransitionable) fromView).onLauncherTransitionEnd(alphaAnim);
2491
2492                        if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2493                            // Show the workspace scrollbar
2494                            mWorkspace.showScrollIndicatorTrack();
2495                            mWorkspace.flashScrollingIndicator();
2496                        }
2497                    }
2498                }
2499            });
2500
2501            mStateAnimation.playTogether(scaleAnim, alphaAnim);
2502            mStateAnimation.start();
2503        } else {
2504            fromView.setVisibility(View.GONE);
2505            if (fromView instanceof LauncherTransitionable) {
2506                ((LauncherTransitionable) fromView).onLauncherTransitionStart(null);
2507                ((LauncherTransitionable) fromView).onLauncherTransitionEnd(null);
2508
2509                if (!springLoaded && !LauncherApplication.isScreenLarge()) {
2510                    // Show the workspace scrollbar
2511                    mWorkspace.showScrollIndicatorTrack();
2512                    mWorkspace.flashScrollingIndicator();
2513                }
2514            }
2515        }
2516    }
2517
2518    void showWorkspace(boolean animated) {
2519        showWorkspace(animated, null);
2520    }
2521
2522    void showWorkspace(boolean animated, CellLayout layout) {
2523        if (layout != null) {
2524            // always animated, but that's ok since we never specify a layout and
2525            // want no animation
2526            mWorkspace.unshrink(layout);
2527        } else {
2528            mWorkspace.unshrink(animated);
2529        }
2530        if (mState == State.APPS_CUSTOMIZE) {
2531            closeAllApps(animated);
2532        }
2533
2534        // Change the state *after* we've called all the transition code
2535        mState = State.WORKSPACE;
2536
2537        // Resume the auto-advance of widgets
2538        mUserPresent = true;
2539        updateRunning();
2540
2541        // send an accessibility event to announce the context change
2542        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2543    }
2544
2545    void enterSpringLoadedDragMode(CellLayout layout) {
2546        if (mState == State.APPS_CUSTOMIZE) {
2547            mWorkspace.enterSpringLoadedDragMode(layout);
2548            cameraZoomIn(State.APPS_CUSTOMIZE, true, true);
2549            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2550        }
2551        // Otherwise, we are not in spring loaded mode, so don't do anything.
2552    }
2553    void exitSpringLoadedDragModeDelayed(boolean extendedDelay) {
2554        mWorkspace.postDelayed(new Runnable() {
2555            @Override
2556            public void run() {
2557                exitSpringLoadedDragMode();
2558            }
2559        }, (extendedDelay ?
2560                EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT :
2561                EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT));
2562    }
2563    void exitSpringLoadedDragMode() {
2564        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2565            mWorkspace.exitSpringLoadedDragMode(Workspace.State.SMALL);
2566            cameraZoomOut(State.APPS_CUSTOMIZE, true, true);
2567            mState = State.APPS_CUSTOMIZE;
2568        }
2569        // Otherwise, we are not in spring loaded mode, so don't do anything.
2570    }
2571
2572    /**
2573     * Shows the dock/hotseat area.
2574     */
2575    void showDock(boolean animated) {
2576        if (!LauncherApplication.isScreenLarge()) {
2577            if (animated) {
2578                int duration = mSearchDeleteBar.getTransitionInDuration();
2579                mButtonCluster.animate().alpha(1f).setDuration(duration);
2580            } else {
2581                mButtonCluster.setAlpha(1f);
2582            }
2583        }
2584    }
2585
2586    /**
2587     * Hides the dock/hotseat area.
2588     */
2589    void hideDock(boolean animated) {
2590        if (!LauncherApplication.isScreenLarge()) {
2591            if (animated) {
2592                int duration = mSearchDeleteBar.getTransitionOutDuration();
2593                mButtonCluster.animate().alpha(0f).setDuration(duration);
2594            } else {
2595                mButtonCluster.setAlpha(0f);
2596            }
2597        }
2598    }
2599
2600    void showAllApps(boolean animated) {
2601        if (mState != State.WORKSPACE) return;
2602
2603        cameraZoomOut(State.APPS_CUSTOMIZE, animated, false);
2604        mAppsCustomizeTabHost.requestFocus();
2605
2606        // Hide the search bar and dock
2607        mSearchDeleteBar.hideSearchBar(animated);
2608        hideDock(animated);
2609
2610        // Change the state *after* we've called all the transition code
2611        mState = State.APPS_CUSTOMIZE;
2612
2613        // Pause the auto-advance of widgets until we are out of AllApps
2614        mUserPresent = false;
2615        updateRunning();
2616
2617        // Send an accessibility event to announce the context change
2618        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2619    }
2620
2621    /**
2622     * Things to test when changing this code.
2623     *   - Home from workspace
2624     *          - from center screen
2625     *          - from other screens
2626     *   - Home from all apps
2627     *          - from center screen
2628     *          - from other screens
2629     *   - Back from all apps
2630     *          - from center screen
2631     *          - from other screens
2632     *   - Launch app from workspace and quit
2633     *          - with back
2634     *          - with home
2635     *   - Launch app from all apps and quit
2636     *          - with back
2637     *          - with home
2638     *   - Go to a screen that's not the default, then all
2639     *     apps, and launch and app, and go back
2640     *          - with back
2641     *          -with home
2642     *   - On workspace, long press power and go back
2643     *          - with back
2644     *          - with home
2645     *   - On all apps, long press power and go back
2646     *          - with back
2647     *          - with home
2648     *   - On workspace, power off
2649     *   - On all apps, power off
2650     *   - Launch an app and turn off the screen while in that app
2651     *          - Go back with home key
2652     *          - Go back with back key  TODO: make this not go to workspace
2653     *          - From all apps
2654     *          - From workspace
2655     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2656     *          - From all apps
2657     *          - From the center workspace
2658     *          - From another workspace
2659     */
2660    void closeAllApps(boolean animated) {
2661        if (mState == State.APPS_CUSTOMIZE || mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2662            mWorkspace.setVisibility(View.VISIBLE);
2663            cameraZoomIn(State.APPS_CUSTOMIZE, animated, false);
2664
2665            // Show the search bar and dock
2666            mSearchDeleteBar.showSearchBar(animated);
2667            showDock(animated);
2668
2669            // Set focus to the AppsCustomize button
2670            findViewById(R.id.all_apps_button).requestFocus();
2671        }
2672    }
2673
2674    void lockAllApps() {
2675        // TODO
2676    }
2677
2678    void unlockAllApps() {
2679        // TODO
2680    }
2681
2682    /**
2683     * Add an item from all apps or customize onto the given workspace screen.
2684     * If layout is null, add to the current screen.
2685     */
2686    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
2687        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
2688            showOutOfSpaceMessage();
2689        } else {
2690            layout.animateDrop();
2691        }
2692    }
2693
2694    private Drawable getExternalPackageToolbarIcon(ComponentName activityName) {
2695        try {
2696            PackageManager packageManager = getPackageManager();
2697            // Look for the toolbar icon specified in the activity meta-data
2698            Bundle metaData = packageManager.getActivityInfo(
2699                    activityName, PackageManager.GET_META_DATA).metaData;
2700            if (metaData != null) {
2701                int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
2702                if (iconResId != 0) {
2703                    Resources res = packageManager.getResourcesForActivity(activityName);
2704                    return res.getDrawable(iconResId);
2705                }
2706            }
2707        } catch (NameNotFoundException e) {
2708            // This can happen if the activity defines an invalid drawable
2709            Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() +
2710                    " not found", e);
2711        } catch (Resources.NotFoundException nfe) {
2712            // This can happen if the activity defines an invalid drawable
2713            Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(),
2714                    nfe);
2715        }
2716        return null;
2717    }
2718
2719    // if successful in getting icon, return it; otherwise, set button to use default drawable
2720    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
2721            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2722        TextView button = (TextView) findViewById(buttonId);
2723        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2724
2725        // If we were unable to find the icon via the meta-data, use a generic one
2726        if (toolbarIcon == null) {
2727            button.setCompoundDrawablesWithIntrinsicBounds(fallbackDrawableId, 0, 0, 0);
2728            return null;
2729        } else {
2730            button.setCompoundDrawablesWithIntrinsicBounds(toolbarIcon, null, null, null);
2731            return toolbarIcon.getConstantState();
2732        }
2733    }
2734
2735    // if successful in getting icon, return it; otherwise, set button to use default drawable
2736    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
2737            int buttonId, ComponentName activityName, int fallbackDrawableId) {
2738        ImageView button = (ImageView) findViewById(buttonId);
2739        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
2740
2741        // If we were unable to find the icon via the meta-data, use a generic one
2742        if (toolbarIcon == null) {
2743            button.setImageResource(fallbackDrawableId);
2744            return null;
2745        } else {
2746            button.setImageDrawable(toolbarIcon);
2747            return toolbarIcon.getConstantState();
2748        }
2749    }
2750
2751    private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2752        TextView button = (TextView) findViewById(buttonId);
2753        button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
2754    }
2755
2756    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
2757        ImageView button = (ImageView) findViewById(buttonId);
2758        button.setImageDrawable(d.newDrawable(getResources()));
2759    }
2760
2761    private void updateGlobalSearchIcon() {
2762        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
2763        final View searchDivider = findViewById(R.id.search_divider);
2764
2765        final SearchManager searchManager =
2766                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
2767        ComponentName activityName = searchManager.getGlobalSearchActivity();
2768        if (activityName != null) {
2769            sGlobalSearchIcon = updateButtonWithIconFromExternalActivity(
2770                    R.id.search_button, activityName, R.drawable.ic_search_normal_holo);
2771            searchButton.setVisibility(View.VISIBLE);
2772            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2773        } else {
2774            searchButton.setVisibility(View.GONE);
2775            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2776        }
2777    }
2778
2779    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
2780        updateButtonWithDrawable(R.id.search_button, d);
2781    }
2782
2783    private void updateVoiceSearchIcon() {
2784        final View searchDivider = findViewById(R.id.search_divider);
2785        final View voiceButton = findViewById(R.id.voice_button);
2786
2787        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
2788        ComponentName activityName = intent.resolveActivity(getPackageManager());
2789        if (activityName != null) {
2790            sVoiceSearchIcon = updateButtonWithIconFromExternalActivity(
2791                    R.id.voice_button, activityName, R.drawable.ic_voice_search_holo);
2792            if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE);
2793            voiceButton.setVisibility(View.VISIBLE);
2794        } else {
2795            if (searchDivider != null) searchDivider.setVisibility(View.GONE);
2796            voiceButton.setVisibility(View.GONE);
2797        }
2798    }
2799
2800    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
2801        updateButtonWithDrawable(R.id.voice_button, d);
2802    }
2803
2804    /**
2805     * Sets the app market icon
2806     */
2807    private void updateAppMarketIcon() {
2808        final View marketButton = findViewById(R.id.market_button);
2809        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
2810        // Find the app market activity by resolving an intent.
2811        // (If multiple app markets are installed, it will return the ResolverActivity.)
2812        ComponentName activityName = intent.resolveActivity(getPackageManager());
2813        if (activityName != null) {
2814            mAppMarketIntent = intent;
2815            sAppMarketIcon = updateTextButtonWithIconFromExternalActivity(
2816                    R.id.market_button, activityName, R.drawable.ic_launcher_market_holo);
2817            marketButton.setVisibility(View.VISIBLE);
2818
2819            // Remove the shop icon text in the Phone UI
2820            if (!LauncherApplication.isScreenLarge()) {
2821                ((TextView) marketButton).setText("");
2822            }
2823        } else {
2824            // We should hide and disable the view so that we don't try and restore the visibility
2825            // of it when we swap between drag & normal states from IconDropTarget subclasses.
2826            marketButton.setVisibility(View.GONE);
2827            marketButton.setEnabled(false);
2828        }
2829    }
2830
2831    private void updateAppMarketIcon(Drawable.ConstantState d) {
2832        updateTextButtonWithDrawable(R.id.market_button, d);
2833    }
2834
2835    /**
2836     * Displays the shortcut creation dialog and launches, if necessary, the
2837     * appropriate activity.
2838     */
2839    private class CreateShortcut implements DialogInterface.OnClickListener,
2840            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
2841            DialogInterface.OnShowListener {
2842
2843        private AddAdapter mAdapter;
2844
2845        Dialog createDialog() {
2846            mAdapter = new AddAdapter(Launcher.this);
2847
2848            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this,
2849                    AlertDialog.THEME_HOLO_DARK);
2850            builder.setTitle(getString(R.string.menu_item_add_item));
2851            builder.setAdapter(mAdapter, this);
2852
2853            AlertDialog dialog = builder.create();
2854            dialog.setOnCancelListener(this);
2855            dialog.setOnDismissListener(this);
2856            dialog.setOnShowListener(this);
2857
2858            return dialog;
2859        }
2860
2861        public void onCancel(DialogInterface dialog) {
2862            mWaitingForResult = false;
2863            cleanup();
2864        }
2865
2866        public void onDismiss(DialogInterface dialog) {
2867            mWaitingForResult = false;
2868            cleanup();
2869        }
2870
2871        private void cleanup() {
2872            try {
2873                dismissDialog(DIALOG_CREATE_SHORTCUT);
2874            } catch (Exception e) {
2875                // An exception is thrown if the dialog is not visible, which is fine
2876            }
2877        }
2878
2879        /**
2880         * Handle the action clicked in the "Add to home" dialog.
2881         */
2882        public void onClick(DialogInterface dialog, int which) {
2883            cleanup();
2884
2885            AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which);
2886            switch (item.actionTag) {
2887                case AddAdapter.ITEM_SHORTCUT: {
2888                    if (mAppsCustomizeTabHost != null) {
2889                        mAppsCustomizeTabHost.selectWidgetsTab();
2890                    }
2891                    showAllApps(true);
2892                    break;
2893                }
2894                case AddAdapter.ITEM_APPLICATION: {
2895                    if (mAppsCustomizeTabHost != null) {
2896                        mAppsCustomizeTabHost.selectAppsTab();
2897                    }
2898                    showAllApps(true);
2899                    break;
2900                }
2901                case AddAdapter.ITEM_APPWIDGET: {
2902                    if (mAppsCustomizeTabHost != null) {
2903                        mAppsCustomizeTabHost.selectWidgetsTab();
2904                    }
2905                    showAllApps(true);
2906                    break;
2907                }
2908                case AddAdapter.ITEM_WALLPAPER: {
2909                    startWallpaper();
2910                    break;
2911                }
2912            }
2913        }
2914
2915        public void onShow(DialogInterface dialog) {
2916            mWaitingForResult = true;
2917        }
2918    }
2919
2920    /**
2921     * Receives notifications when applications are added/removed.
2922     */
2923    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2924        @Override
2925        public void onReceive(Context context, Intent intent) {
2926            closeSystemDialogs();
2927            String reason = intent.getStringExtra("reason");
2928            if (!"homekey".equals(reason)) {
2929                boolean animate = true;
2930                if (mPaused || "lock".equals(reason)) {
2931                    animate = false;
2932                }
2933                showWorkspace(animate);
2934            }
2935        }
2936    }
2937
2938    /**
2939     * Receives notifications whenever the appwidgets are reset.
2940     */
2941    private class AppWidgetResetObserver extends ContentObserver {
2942        public AppWidgetResetObserver() {
2943            super(new Handler());
2944        }
2945
2946        @Override
2947        public void onChange(boolean selfChange) {
2948            onAppWidgetReset();
2949        }
2950    }
2951
2952    /**
2953     * If the activity is currently paused, signal that we need to re-run the loader
2954     * in onResume.
2955     *
2956     * This needs to be called from incoming places where resources might have been loaded
2957     * while we are paused.  That is becaues the Configuration might be wrong
2958     * when we're not running, and if it comes back to what it was when we
2959     * were paused, we are not restarted.
2960     *
2961     * Implementation of the method from LauncherModel.Callbacks.
2962     *
2963     * @return true if we are currently paused.  The caller might be able to
2964     * skip some work in that case since we will come back again.
2965     */
2966    public boolean setLoadOnResume() {
2967        if (mPaused) {
2968            Log.i(TAG, "setLoadOnResume");
2969            mOnResumeNeedsLoad = true;
2970            return true;
2971        } else {
2972            return false;
2973        }
2974    }
2975
2976    /**
2977     * Implementation of the method from LauncherModel.Callbacks.
2978     */
2979    public int getCurrentWorkspaceScreen() {
2980        if (mWorkspace != null) {
2981            return mWorkspace.getCurrentPage();
2982        } else {
2983            return SCREEN_COUNT / 2;
2984        }
2985    }
2986
2987
2988    /**
2989     * Refreshes the shortcuts shown on the workspace.
2990     *
2991     * Implementation of the method from LauncherModel.Callbacks.
2992     */
2993    public void startBinding() {
2994        final Workspace workspace = mWorkspace;
2995
2996        mWorkspace.clearDropTargets();
2997        int count = workspace.getChildCount();
2998        for (int i = 0; i < count; i++) {
2999            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
3000            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
3001            layoutParent.removeAllViewsInLayout();
3002        }
3003
3004        if (DEBUG_USER_INTERFACE) {
3005            android.widget.Button finishButton = new android.widget.Button(this);
3006            finishButton.setText("Finish");
3007            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
3008
3009            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
3010                public void onClick(View v) {
3011                    finish();
3012                }
3013            });
3014        }
3015
3016        // This wasn't being called before which resulted in a leak of AppWidgetHostViews
3017        unbindWorkspaceItems();
3018    }
3019
3020    /**
3021     * Bind the items start-end from the list.
3022     *
3023     * Implementation of the method from LauncherModel.Callbacks.
3024     */
3025    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
3026
3027        setLoadOnResume();
3028
3029        final Workspace workspace = mWorkspace;
3030
3031        for (int i=start; i<end; i++) {
3032            final ItemInfo item = shortcuts.get(i);
3033            switch (item.itemType) {
3034                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3035                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3036                    final View shortcut = createShortcut((ShortcutInfo)item);
3037                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
3038                            false);
3039                    break;
3040                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3041                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3042                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3043                            (FolderInfo) item, mIconCache);
3044                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
3045                            false);
3046                    break;
3047            }
3048        }
3049
3050        workspace.requestLayout();
3051    }
3052
3053    /**
3054     * Implementation of the method from LauncherModel.Callbacks.
3055     */
3056    public void bindFolders(HashMap<Long, FolderInfo> folders) {
3057        setLoadOnResume();
3058        sFolders.clear();
3059        sFolders.putAll(folders);
3060    }
3061
3062    /**
3063     * Add the views for a widget to the workspace.
3064     *
3065     * Implementation of the method from LauncherModel.Callbacks.
3066     */
3067    public void bindAppWidget(LauncherAppWidgetInfo item) {
3068        setLoadOnResume();
3069
3070        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3071        if (DEBUG_WIDGETS) {
3072            Log.d(TAG, "bindAppWidget: " + item);
3073        }
3074        final Workspace workspace = mWorkspace;
3075
3076        final int appWidgetId = item.appWidgetId;
3077        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3078        if (DEBUG_WIDGETS) {
3079            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3080        }
3081
3082        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3083
3084        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
3085        item.hostView.setTag(item);
3086
3087        workspace.addInScreen(item.hostView, item.screen, item.cellX,
3088                item.cellY, item.spanX, item.spanY, false);
3089
3090        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3091
3092        workspace.requestLayout();
3093
3094        if (DEBUG_WIDGETS) {
3095            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3096                    + (SystemClock.uptimeMillis()-start) + "ms");
3097        }
3098    }
3099
3100    /**
3101     * Callback saying that there aren't any more items to bind.
3102     *
3103     * Implementation of the method from LauncherModel.Callbacks.
3104     */
3105    public void finishBindingItems() {
3106        setLoadOnResume();
3107
3108        if (mSavedState != null) {
3109            if (!mWorkspace.hasFocus()) {
3110                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3111            }
3112            mSavedState = null;
3113        }
3114
3115        if (mSavedInstanceState != null) {
3116            super.onRestoreInstanceState(mSavedInstanceState);
3117            mSavedInstanceState = null;
3118        }
3119
3120        mWorkspaceLoading = false;
3121
3122        // If we received the result of any pending adds while the loader was running (e.g. the
3123        // widget configuration forced an orientation change), process them now.
3124        for (int i = 0; i < sPendingAddList.size(); i++) {
3125            completeAdd(sPendingAddList.get(i));
3126        }
3127        sPendingAddList.clear();
3128    }
3129
3130    /**
3131     * Updates the icons on the launcher that are affected by changes to the package list
3132     * on the device.
3133     */
3134    private void updateIconsAffectedByPackageManagerChanges() {
3135        updateAppMarketIcon();
3136        updateGlobalSearchIcon();
3137        updateVoiceSearchIcon();
3138    }
3139
3140    /**
3141     * Add the icons for all apps.
3142     *
3143     * Implementation of the method from LauncherModel.Callbacks.
3144     */
3145    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
3146        if (mAppsCustomizeContent != null) {
3147            mAppsCustomizeContent.setApps(apps);
3148        }
3149        updateIconsAffectedByPackageManagerChanges();
3150    }
3151
3152    /**
3153     * A package was installed.
3154     *
3155     * Implementation of the method from LauncherModel.Callbacks.
3156     */
3157    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3158        setLoadOnResume();
3159        removeDialog(DIALOG_CREATE_SHORTCUT);
3160
3161        if (mAppsCustomizeContent != null) {
3162            mAppsCustomizeContent.addApps(apps);
3163        }
3164        updateIconsAffectedByPackageManagerChanges();
3165    }
3166
3167    /**
3168     * A package was updated.
3169     *
3170     * Implementation of the method from LauncherModel.Callbacks.
3171     */
3172    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3173        setLoadOnResume();
3174        removeDialog(DIALOG_CREATE_SHORTCUT);
3175        if (mWorkspace != null) {
3176            mWorkspace.updateShortcuts(apps);
3177        }
3178
3179        if (mAppsCustomizeContent != null) {
3180            mAppsCustomizeContent.updateApps(apps);
3181        }
3182        updateIconsAffectedByPackageManagerChanges();
3183    }
3184
3185    /**
3186     * A package was uninstalled.
3187     *
3188     * Implementation of the method from LauncherModel.Callbacks.
3189     */
3190    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
3191        removeDialog(DIALOG_CREATE_SHORTCUT);
3192        if (permanent) {
3193            mWorkspace.removeItems(apps);
3194        }
3195
3196        if (mAppsCustomizeContent != null) {
3197            mAppsCustomizeContent.removeApps(apps);
3198        }
3199        updateIconsAffectedByPackageManagerChanges();
3200    }
3201
3202    /**
3203     * A number of packages were updated.
3204     */
3205    public void bindPackagesUpdated() {
3206
3207        if (mAppsCustomizeContent != null) {
3208            mAppsCustomizeContent.onPackagesUpdated();
3209        }
3210    }
3211
3212    private int mapConfigurationOriActivityInfoOri(int configOri) {
3213        final Display d = getWindowManager().getDefaultDisplay();
3214        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3215        switch (d.getRotation()) {
3216        case Surface.ROTATION_0:
3217        case Surface.ROTATION_180:
3218            // We are currently in the same basic orientation as the natural orientation
3219            naturalOri = configOri;
3220            break;
3221        case Surface.ROTATION_90:
3222        case Surface.ROTATION_270:
3223            // We are currently in the other basic orientation to the natural orientation
3224            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3225                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3226            break;
3227        }
3228
3229        int[] oriMap = {
3230                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3231                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3232                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3233                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3234        };
3235        // Since the map starts at portrait, we need to offset if this device's natural orientation
3236        // is landscape.
3237        int indexOffset = 0;
3238        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3239            indexOffset = 1;
3240        }
3241        return oriMap[(d.getRotation() + indexOffset) % 4];
3242    }
3243    public void lockScreenOrientation() {
3244        setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3245                .getConfiguration().orientation));
3246    }
3247    public void unlockScreenOrientation() {
3248        mHandler.postDelayed(new Runnable() {
3249            public void run() {
3250                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3251            }
3252        }, mRestoreScreenOrientationDelay);
3253    }
3254
3255    /**
3256     * Prints out out state for debugging.
3257     */
3258    public void dumpState() {
3259        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3260        Log.d(TAG, "mSavedState=" + mSavedState);
3261        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3262        Log.d(TAG, "mRestoring=" + mRestoring);
3263        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3264        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3265        Log.d(TAG, "sFolders.size=" + sFolders.size());
3266        mModel.dumpState();
3267
3268        if (mAppsCustomizeContent != null) {
3269            mAppsCustomizeContent.dumpState();
3270        }
3271        Log.d(TAG, "END launcher2 dump state");
3272    }
3273}
3274
3275interface LauncherTransitionable {
3276    void onLauncherTransitionStart(Animator animation);
3277    void onLauncherTransitionEnd(Animator animation);
3278}
3279