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