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