Launcher.java revision 3732cf8b49a5c386c91030df5b2a9811e6480acf
1
2/*
3 * Copyright (C) 2008 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.launcher2;
19
20import android.animation.Animator;
21import android.animation.AnimatorListenerAdapter;
22import android.animation.AnimatorSet;
23import android.animation.ObjectAnimator;
24import android.animation.PropertyValuesHolder;
25import android.animation.ValueAnimator;
26import android.animation.ValueAnimator.AnimatorUpdateListener;
27import android.app.Activity;
28import android.app.AlertDialog;
29import android.app.Dialog;
30import android.app.SearchManager;
31import android.app.StatusBarManager;
32import android.appwidget.AppWidgetManager;
33import android.appwidget.AppWidgetProviderInfo;
34import android.content.ActivityNotFoundException;
35import android.content.BroadcastReceiver;
36import android.content.ClipData;
37import android.content.ClipDescription;
38import android.content.ComponentName;
39import android.content.ContentResolver;
40import android.content.Context;
41import android.content.DialogInterface;
42import android.content.Intent;
43import android.content.IntentFilter;
44import android.content.Intent.ShortcutIconResource;
45import android.content.pm.ActivityInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.ResolveInfo;
48import android.content.pm.PackageManager.NameNotFoundException;
49import android.content.res.Configuration;
50import android.content.res.Resources;
51import android.content.res.TypedArray;
52import android.database.ContentObserver;
53import android.graphics.Bitmap;
54import android.graphics.Canvas;
55import android.graphics.Rect;
56import android.graphics.drawable.ColorDrawable;
57import android.graphics.drawable.Drawable;
58import android.net.Uri;
59import android.os.AsyncTask;
60import android.os.Bundle;
61import android.os.Environment;
62import android.os.Handler;
63import android.os.Message;
64import android.os.SystemClock;
65import android.os.SystemProperties;
66import android.provider.Settings;
67import android.speech.RecognizerIntent;
68import android.text.Selection;
69import android.text.SpannableStringBuilder;
70import android.text.TextUtils;
71import android.text.method.TextKeyListener;
72import android.util.Log;
73import android.view.Display;
74import android.view.HapticFeedbackConstants;
75import android.view.KeyEvent;
76import android.view.LayoutInflater;
77import android.view.Menu;
78import android.view.MenuItem;
79import android.view.MotionEvent;
80import android.view.Surface;
81import android.view.View;
82import android.view.ViewGroup;
83import android.view.WindowManager;
84import android.view.View.OnClickListener;
85import android.view.View.OnLongClickListener;
86import android.view.accessibility.AccessibilityEvent;
87import android.view.animation.DecelerateInterpolator;
88import android.view.inputmethod.InputMethodManager;
89import android.widget.Advanceable;
90import android.widget.EditText;
91import android.widget.ImageView;
92import android.widget.LinearLayout;
93import android.widget.PopupWindow;
94import android.widget.TabHost;
95import android.widget.TextView;
96import android.widget.Toast;
97
98import com.android.common.Search;
99import com.android.launcher.R;
100import com.android.launcher2.Workspace.ShrinkState;
101
102import java.io.DataInputStream;
103import java.io.DataOutputStream;
104import java.io.FileNotFoundException;
105import java.io.IOException;
106import java.util.ArrayList;
107import java.util.HashMap;
108import java.util.List;
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        APPS_CUSTOMIZE_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                if (toState == State.APPS_CUSTOMIZE) {
2676                    // Shrink workspaces away if going back to AppsCustomize from spring loaded mode
2677                    mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated);
2678                } else {
2679                    // Shrink workspaces to bottom if going back to AllApps from spring loaded mode
2680                    mWorkspace.shrink(ShrinkState.BOTTOM_VISIBLE, animated);
2681                }
2682            } else {
2683                // Shrink workspaces away if going to AllApps/AppsCustomize from workspace
2684                mWorkspace.shrink(ShrinkState.BOTTOM_HIDDEN, animated);
2685
2686                if (LauncherApplication.isScreenLarge()) {
2687                    // Everytime we launch into AllApps, we reset the successful drop flag which
2688                    // controls when it should hide/show the mini workspaces
2689                    mAllAppsPagedView.resetSuccessfulDropFlag();
2690                }
2691            }
2692        } else {
2693            // In Customize mode, shrink the workspaces to the top
2694            mWorkspace.shrink(ShrinkState.TOP, animated);
2695        }
2696
2697        if (animated) {
2698            final ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2699            scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator());
2700            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2701                public void onAnimationUpdate(float a, float b) {
2702                    ((View) toView.getParent()).fastInvalidate();
2703                    toView.setFastScaleX(a * scale + b * 1f);
2704                    toView.setFastScaleY(a * scale + b * 1f);
2705                }
2706            });
2707
2708            if (toAllApps) {
2709                toView.setVisibility(View.VISIBLE);
2710                toView.setFastAlpha(0f);
2711                ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(fadeDuration);
2712                alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2713                alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2714                    public void onAnimationUpdate(float a, float b) {
2715                        // don't need to invalidate because we do so above
2716                        toView.setFastAlpha(a * 0f + b * 1f);
2717                    }
2718                });
2719                alphaAnim.start();
2720            }
2721
2722            if (toView instanceof LauncherTransitionable) {
2723                ((LauncherTransitionable) toView).onLauncherTransitionStart(scaleAnim);
2724            }
2725            scaleAnim.addListener(new AnimatorListenerAdapter() {
2726                @Override
2727                public void onAnimationStart(Animator animation) {
2728                    // Prepare the position
2729                    toView.setTranslationX(0.0f);
2730                    toView.setTranslationY(0.0f);
2731                    toView.setVisibility(View.VISIBLE);
2732                    toView.bringToFront();
2733                    if (!toAllApps) {
2734                        toView.setFastAlpha(1.0f);
2735                    }
2736                }
2737                @Override
2738                public void onAnimationEnd(Animator animation) {
2739                    // If we don't set the final scale values here, if this animation is cancelled
2740                    // it will have the wrong scale value and subsequent cameraPan animations will
2741                    // not fix that
2742                    toView.setScaleX(1.0f);
2743                    toView.setScaleY(1.0f);
2744                    if (toView instanceof LauncherTransitionable) {
2745                        ((LauncherTransitionable) toView).onLauncherTransitionEnd(scaleAnim);
2746                    }
2747                }
2748            });
2749
2750            AnimatorSet toolbarHideAnim = new AnimatorSet();
2751            AnimatorSet toolbarShowAnim = new AnimatorSet();
2752            hideAndShowToolbarButtons(toState, toolbarShowAnim, toolbarHideAnim);
2753
2754            // toView should appear right at the end of the workspace shrink animation
2755            final int startDelay = 0;
2756
2757            if (mStateAnimation != null) mStateAnimation.cancel();
2758            mStateAnimation = new AnimatorSet();
2759            mStateAnimation.playTogether(scaleAnim, toolbarHideAnim);
2760            mStateAnimation.play(scaleAnim).after(startDelay);
2761
2762            // Show the new toolbar buttons just as the main animation is ending
2763            final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
2764            mStateAnimation.play(toolbarShowAnim).after(duration + startDelay - fadeInTime);
2765            mStateAnimation.start();
2766        } else {
2767            toView.setTranslationX(0.0f);
2768            toView.setTranslationY(0.0f);
2769            toView.setScaleX(1.0f);
2770            toView.setScaleY(1.0f);
2771            toView.setVisibility(View.VISIBLE);
2772            toView.bringToFront();
2773            if (toView instanceof LauncherTransitionable) {
2774                ((LauncherTransitionable) toView).onLauncherTransitionStart(null);
2775                ((LauncherTransitionable) toView).onLauncherTransitionEnd(null);
2776            }
2777            hideAndShowToolbarButtons(toState, null, null);
2778        }
2779    }
2780
2781    /**
2782     * Zoom the camera back into the workspace, hiding 'fromView'.
2783     * This is the opposite of cameraZoomOut.
2784     * @param fromState The current state (must be ALL_APPS or CUSTOMIZE).
2785     * @param animated If true, the transition will be animated.
2786     */
2787    private void cameraZoomIn(State fromState, boolean animated, boolean springLoaded) {
2788        Resources res = getResources();
2789        final boolean fromAllApps = (fromState == State.ALL_APPS)
2790                || (fromState == State.APPS_CUSTOMIZE);
2791
2792        int duration = fromAllApps ?
2793            res.getInteger(R.integer.config_appsCustomizeZoomOutTime) :
2794            res.getInteger(R.integer.config_customizeZoomOutTime);
2795
2796        final float scaleFactor = fromAllApps ?
2797            (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor) :
2798            (float) res.getInteger(R.integer.config_customizeZoomScaleFactor);
2799
2800        View tmpView;
2801        if (fromAllApps) {
2802            tmpView = (LauncherApplication.isScreenLarge())
2803                    ? (View) mAllAppsGrid : mAppsCustomizeTabHost;
2804        } else {
2805            tmpView = mHomeCustomizationDrawer;
2806        }
2807        final View fromView = tmpView;
2808
2809        if (LauncherApplication.isScreenLarge()) {
2810            mCustomizePagedView.endChoiceMode();
2811            mAllAppsPagedView.endChoiceMode();
2812        }
2813
2814        setPivotsForZoom(fromView, fromState, scaleFactor);
2815
2816        if (!springLoaded) {
2817            mWorkspace.unshrink(animated);
2818        }
2819        if (animated) {
2820            if (mStateAnimation != null) mStateAnimation.cancel();
2821            mStateAnimation = new AnimatorSet();
2822
2823            final float oldScaleX = fromView.getScaleX();
2824            final float oldScaleY = fromView.getScaleY();
2825
2826            ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration);
2827            scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator());
2828            scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2829                public void onAnimationUpdate(float a, float b) {
2830                    ((View)fromView.getParent()).fastInvalidate();
2831                    fromView.setFastScaleX(a * oldScaleX + b * scaleFactor);
2832                    fromView.setFastScaleY(a * oldScaleY + b * scaleFactor);
2833                }
2834            });
2835            final ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f);
2836            alphaAnim.setDuration(res.getInteger(R.integer.config_appsCustomizeFadeOutTime));
2837            alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f));
2838            alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() {
2839                public void onAnimationUpdate(float a, float b) {
2840                    // don't need to invalidate because we do so above
2841                    fromView.setFastAlpha(a * 1f + b * 0f);
2842                }
2843            });
2844            if (fromView instanceof LauncherTransitionable) {
2845                ((LauncherTransitionable) fromView).onLauncherTransitionStart(alphaAnim);
2846            }
2847            alphaAnim.addListener(new AnimatorListenerAdapter() {
2848                @Override
2849                public void onAnimationEnd(Animator animation) {
2850                    fromView.setVisibility(View.GONE);
2851                    if (fromView instanceof LauncherTransitionable) {
2852                        ((LauncherTransitionable) fromView).onLauncherTransitionEnd(alphaAnim);
2853                    }
2854                }
2855            });
2856
2857            AnimatorSet toolbarHideAnim = new AnimatorSet();
2858            AnimatorSet toolbarShowAnim = new AnimatorSet();
2859            if (!springLoaded) {
2860                hideAndShowToolbarButtons(State.WORKSPACE, toolbarShowAnim, toolbarHideAnim);
2861            }
2862
2863            mStateAnimation.playTogether(scaleAnim, toolbarHideAnim, alphaAnim);
2864
2865            // Show the new toolbar buttons at the very end of the whole animation
2866            final int fadeInTime = res.getInteger(R.integer.config_toolbarButtonFadeInTime);
2867            final int unshrinkTime = res.getInteger(R.integer.config_workspaceUnshrinkTime);
2868            mStateAnimation.play(toolbarShowAnim).after(unshrinkTime - fadeInTime);
2869            mStateAnimation.start();
2870        } else {
2871            fromView.setVisibility(View.GONE);
2872            if (fromView instanceof LauncherTransitionable) {
2873                ((LauncherTransitionable) fromView).onLauncherTransitionStart(null);
2874                ((LauncherTransitionable) fromView).onLauncherTransitionEnd(null);
2875            }
2876            if (!springLoaded) {
2877                hideAndShowToolbarButtons(State.WORKSPACE, null, null);
2878            }
2879        }
2880    }
2881
2882    void showWorkspace(boolean animated) {
2883        showWorkspace(animated, null);
2884    }
2885
2886    void showWorkspace(boolean animated, CellLayout layout) {
2887        if (layout != null) {
2888            // always animated, but that's ok since we never specify a layout and
2889            // want no animation
2890            mWorkspace.unshrink(layout);
2891        } else {
2892            mWorkspace.unshrink(animated);
2893        }
2894        if (mState == State.ALL_APPS || mState == State.APPS_CUSTOMIZE) {
2895            closeAllApps(animated);
2896        } else if (mState == State.CUSTOMIZE) {
2897            hideCustomizationDrawer(animated);
2898        }
2899
2900        // Change the state *after* we've called all the transition code
2901        mState = State.WORKSPACE;
2902
2903        // Resume the auto-advance of widgets
2904        mUserPresent = true;
2905        updateRunning();
2906
2907        // send an accessibility event to announce the context change
2908        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2909    }
2910
2911    void enterSpringLoadedDragMode(CellLayout layout) {
2912        // Enter spring loaded mode on a new layout
2913        mWorkspace.enterSpringLoadedDragMode(layout);
2914
2915        if (mState == State.APPS_CUSTOMIZE) {
2916            mState = State.APPS_CUSTOMIZE_SPRING_LOADED;
2917            cameraZoomIn(State.APPS_CUSTOMIZE, true, true);
2918        } else {
2919            // Do nothing
2920        }
2921    }
2922
2923    void exitSpringLoadedDragMode() {
2924        if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
2925            mWorkspace.exitSpringLoadedDragMode(Workspace.ShrinkState.BOTTOM_HIDDEN);
2926            cameraZoomOut(State.APPS_CUSTOMIZE, true, true);
2927            mState = State.APPS_CUSTOMIZE;
2928        } else {
2929            // Do nothing
2930        }
2931    }
2932
2933    void showAllApps(boolean animated) {
2934        if (mState != State.WORKSPACE) return;
2935        if (LauncherApplication.isScreenLarge()) {
2936            cameraZoomOut(State.ALL_APPS, animated, false);
2937            ((View) mAllAppsGrid).requestFocus();
2938
2939            if (mDeleteZone != null) {
2940                mDeleteZone.setVisibility(View.GONE);
2941            }
2942
2943            // Change the state *after* we've called all the transition code
2944            mState = State.ALL_APPS;
2945        } else {
2946            cameraZoomOut(State.APPS_CUSTOMIZE, animated, false);
2947            mAppsCustomizeTabHost.requestFocus();
2948
2949            // Change the state *after* we've called all the transition code
2950            mState = State.APPS_CUSTOMIZE;
2951        }
2952
2953        // Pause the auto-advance of widgets until we are out of AllApps
2954        mUserPresent = false;
2955        updateRunning();
2956
2957        // Send an accessibility event to announce the context change
2958        getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
2959    }
2960
2961    /**
2962     * Things to test when changing this code.
2963     *   - Home from workspace
2964     *          - from center screen
2965     *          - from other screens
2966     *   - Home from all apps
2967     *          - from center screen
2968     *          - from other screens
2969     *   - Back from all apps
2970     *          - from center screen
2971     *          - from other screens
2972     *   - Launch app from workspace and quit
2973     *          - with back
2974     *          - with home
2975     *   - Launch app from all apps and quit
2976     *          - with back
2977     *          - with home
2978     *   - Go to a screen that's not the default, then all
2979     *     apps, and launch and app, and go back
2980     *          - with back
2981     *          -with home
2982     *   - On workspace, long press power and go back
2983     *          - with back
2984     *          - with home
2985     *   - On all apps, long press power and go back
2986     *          - with back
2987     *          - with home
2988     *   - On workspace, power off
2989     *   - On all apps, power off
2990     *   - Launch an app and turn off the screen while in that app
2991     *          - Go back with home key
2992     *          - Go back with back key  TODO: make this not go to workspace
2993     *          - From all apps
2994     *          - From workspace
2995     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2996     *          - From all apps
2997     *          - From the center workspace
2998     *          - From another workspace
2999     */
3000    void closeAllApps(boolean animated) {
3001        if (LauncherApplication.isScreenLarge()) {
3002            if (mState == State.ALL_APPS) {
3003                mWorkspace.setVisibility(View.VISIBLE);
3004                cameraZoomIn(State.ALL_APPS, animated, false);
3005
3006                // Set focus to the AllApps button
3007                findViewById(R.id.all_apps_button).requestFocus();
3008            }
3009        } else {
3010            if (mState == State.APPS_CUSTOMIZE || mState == State.APPS_CUSTOMIZE_SPRING_LOADED) {
3011                mWorkspace.setVisibility(View.VISIBLE);
3012                cameraZoomIn(State.APPS_CUSTOMIZE, animated, false);
3013
3014                // Set focus to the AllApps button
3015                findViewById(R.id.all_apps_button).requestFocus();
3016            }
3017        }
3018    }
3019
3020    void lockAllApps() {
3021        // TODO
3022    }
3023
3024    void unlockAllApps() {
3025        // TODO
3026    }
3027
3028    // Show the customization drawer (only exists in x-large configuration)
3029    private void showCustomizationDrawer(boolean animated) {
3030        if (mState != State.WORKSPACE) {
3031            return;
3032        }
3033
3034        cameraZoomOut(State.CUSTOMIZE, animated, false);
3035
3036        // Change the state *after* we've called all the transition code
3037        mState = State.CUSTOMIZE;
3038
3039        // Pause the auto-advance of widgets until we are out of Customization drawer
3040        mUserPresent = false;
3041        updateRunning();
3042    }
3043
3044    // Hide the customization drawer (only exists in x-large configuration)
3045    void hideCustomizationDrawer(boolean animated) {
3046        if (mState == State.CUSTOMIZE) {
3047            cameraZoomIn(State.CUSTOMIZE, animated, false);
3048
3049            // Set focus to the customize button
3050            findViewById(R.id.configure_button).requestFocus();
3051        }
3052    }
3053
3054    /**
3055     * Add an item from all apps or customize onto the given workspace screen.
3056     * If layout is null, add to the current screen.
3057     */
3058    void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) {
3059        if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) {
3060            showOutOfSpaceMessage();
3061        } else {
3062            layout.animateDrop();
3063        }
3064    }
3065
3066    void onWorkspaceClick(CellLayout layout) {
3067        showWorkspace(true, layout);
3068    }
3069
3070    private Drawable getExternalPackageToolbarIcon(ComponentName activityName) {
3071        try {
3072            PackageManager packageManager = getPackageManager();
3073            // Look for the toolbar icon specified in the activity meta-data
3074            Bundle metaData = packageManager.getActivityInfo(
3075                    activityName, PackageManager.GET_META_DATA).metaData;
3076            if (metaData != null) {
3077                int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME);
3078                if (iconResId != 0) {
3079                    Resources res = packageManager.getResourcesForActivity(activityName);
3080                    return res.getDrawable(iconResId);
3081                }
3082            }
3083        } catch (NameNotFoundException e) {
3084            // Do nothing
3085        }
3086        return null;
3087    }
3088
3089    // if successful in getting icon, return it; otherwise, set button to use default drawable
3090    private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity(
3091            int buttonId, ComponentName activityName, int fallbackDrawableId) {
3092        TextView button = (TextView) findViewById(buttonId);
3093        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
3094
3095        // If we were unable to find the icon via the meta-data, use a generic one
3096        if (toolbarIcon == null) {
3097            button.setCompoundDrawablesWithIntrinsicBounds(fallbackDrawableId, 0, 0, 0);
3098            return null;
3099        } else {
3100            button.setCompoundDrawablesWithIntrinsicBounds(toolbarIcon, null, null, null);
3101            return toolbarIcon.getConstantState();
3102        }
3103    }
3104
3105    // if successful in getting icon, return it; otherwise, set button to use default drawable
3106    private Drawable.ConstantState updateButtonWithIconFromExternalActivity(
3107            int buttonId, ComponentName activityName, int fallbackDrawableId) {
3108        ImageView button = (ImageView) findViewById(buttonId);
3109        Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName);
3110
3111        // If we were unable to find the icon via the meta-data, use a generic one
3112        if (toolbarIcon == null) {
3113            button.setImageResource(fallbackDrawableId);
3114            return null;
3115        } else {
3116            button.setImageDrawable(toolbarIcon);
3117            return toolbarIcon.getConstantState();
3118        }
3119    }
3120
3121    private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
3122        TextView button = (TextView) findViewById(buttonId);
3123        button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null);
3124    }
3125
3126    private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) {
3127        ImageView button = (ImageView) findViewById(buttonId);
3128        button.setImageDrawable(d.newDrawable(getResources()));
3129    }
3130
3131    private void updateGlobalSearchIcon() {
3132        final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
3133        final View searchDivider = findViewById(R.id.search_divider);
3134
3135        final SearchManager searchManager =
3136                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
3137        ComponentName activityName = searchManager.getGlobalSearchActivity();
3138        if (activityName != null) {
3139            // In landscape mode on the Phone UI, we only have enough space to show the magnifying
3140            // glass icon
3141            boolean iconLoaded = false;
3142            if (!LauncherApplication.isScreenLarge()) {
3143                // TODO-APPS_CUSTOMIZE: Remove when the QSB fixes itself?
3144                int orientation = getResources().getConfiguration().orientation;
3145                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
3146                    searchButton.setImageResource(R.drawable.ic_generic_search);
3147                    iconLoaded = true;
3148                    sGlobalSearchIcon = null;
3149                }
3150            }
3151            if (!iconLoaded) {
3152                sGlobalSearchIcon = updateButtonWithIconFromExternalActivity(
3153                        R.id.search_button, activityName, R.drawable.ic_generic_search);
3154            }
3155            searchButton.setVisibility(View.VISIBLE);
3156            searchDivider.setVisibility(View.VISIBLE);
3157        } else {
3158            searchButton.setVisibility(View.GONE);
3159            searchDivider.setVisibility(View.GONE);
3160        }
3161    }
3162
3163    private void updateGlobalSearchIcon(Drawable.ConstantState d) {
3164        updateButtonWithDrawable(R.id.search_button, d);
3165    }
3166
3167    private void updateVoiceSearchIcon() {
3168        final View searchDivider = findViewById(R.id.search_divider);
3169        final View voiceButton = findViewById(R.id.voice_button);
3170
3171        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
3172        ComponentName activityName = intent.resolveActivity(getPackageManager());
3173        if (activityName != null) {
3174            sVoiceSearchIcon = updateButtonWithIconFromExternalActivity(
3175                    R.id.voice_button, activityName, R.drawable.ic_voice_search);
3176            searchDivider.setVisibility(View.VISIBLE);
3177            voiceButton.setVisibility(View.VISIBLE);
3178        } else {
3179            searchDivider.setVisibility(View.GONE);
3180            voiceButton.setVisibility(View.GONE);
3181        }
3182    }
3183
3184    private void updateVoiceSearchIcon(Drawable.ConstantState d) {
3185        updateButtonWithDrawable(R.id.voice_button, d);
3186    }
3187
3188    /**
3189     * Sets the app market icon (shown when all apps is visible on x-large screens)
3190     */
3191    private void updateAppMarketIcon() {
3192        final View marketButton = findViewById(R.id.market_button);
3193        Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET);
3194        // Find the app market activity by resolving an intent.
3195        // (If multiple app markets are installed, it will return the ResolverActivity.)
3196        ComponentName activityName = intent.resolveActivity(getPackageManager());
3197        if (activityName != null) {
3198            mAppMarketIntent = intent;
3199            sAppMarketIcon = updateTextButtonWithIconFromExternalActivity(
3200                    R.id.market_button, activityName, R.drawable.app_market_generic);
3201            marketButton.setVisibility(View.VISIBLE);
3202        } else {
3203            // We should hide and disable the view so that we don't try and restore the visibility
3204            // of it when we swap between drag & normal states from IconDropTarget subclasses.
3205            marketButton.setVisibility(View.GONE);
3206            marketButton.setEnabled(false);
3207        }
3208    }
3209
3210    private void updateAppMarketIcon(Drawable.ConstantState d) {
3211        updateTextButtonWithDrawable(R.id.market_button, d);
3212    }
3213
3214    /**
3215     * Displays the shortcut creation dialog and launches, if necessary, the
3216     * appropriate activity.
3217     */
3218    private class CreateShortcut implements DialogInterface.OnClickListener,
3219            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
3220            DialogInterface.OnShowListener {
3221
3222        private AddAdapter mAdapter;
3223
3224        Dialog createDialog() {
3225            mAdapter = new AddAdapter(Launcher.this);
3226
3227            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this,
3228                    AlertDialog.THEME_HOLO_DARK);
3229            builder.setTitle(getString(R.string.menu_item_add_item));
3230            builder.setAdapter(mAdapter, this);
3231
3232            AlertDialog dialog = builder.create();
3233            dialog.setOnCancelListener(this);
3234            dialog.setOnDismissListener(this);
3235            dialog.setOnShowListener(this);
3236
3237            return dialog;
3238        }
3239
3240        public void onCancel(DialogInterface dialog) {
3241            mWaitingForResult = false;
3242            cleanup();
3243        }
3244
3245        public void onDismiss(DialogInterface dialog) {
3246            mWaitingForResult = false;
3247            cleanup();
3248        }
3249
3250        private void cleanup() {
3251            try {
3252                dismissDialog(DIALOG_CREATE_SHORTCUT);
3253            } catch (Exception e) {
3254                // An exception is thrown if the dialog is not visible, which is fine
3255            }
3256        }
3257
3258        /**
3259         * Handle the action clicked in the "Add to home" dialog.
3260         */
3261        public void onClick(DialogInterface dialog, int which) {
3262            Resources res = getResources();
3263            cleanup();
3264
3265            AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which);
3266            switch (item.actionTag) {
3267                case AddAdapter.ITEM_SHORTCUT: {
3268                    pickShortcut();
3269                    break;
3270                }
3271                case AddAdapter.ITEM_APPLICATION: {
3272                    if (mAppsCustomizeTabHost != null) {
3273                        mAppsCustomizeTabHost.selectAppsTab();
3274                    }
3275                    showAllApps(true);
3276                    break;
3277                }
3278                case AddAdapter.ITEM_APPWIDGET: {
3279                    if (mAppsCustomizeTabHost != null) {
3280                        mAppsCustomizeTabHost.selectWidgetsTab();
3281                    }
3282                    showAllApps(true);
3283                    break;
3284                }
3285                case AddAdapter.ITEM_WALLPAPER: {
3286                    startWallpaper();
3287                    break;
3288                }
3289            }
3290        }
3291
3292        public void onShow(DialogInterface dialog) {
3293            mWaitingForResult = true;
3294        }
3295    }
3296
3297    /**
3298     * Receives notifications when applications are added/removed.
3299     */
3300    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
3301        @Override
3302        public void onReceive(Context context, Intent intent) {
3303            closeSystemDialogs();
3304            String reason = intent.getStringExtra("reason");
3305            if (!"homekey".equals(reason)) {
3306                boolean animate = true;
3307                if (mPaused || "lock".equals(reason)) {
3308                    animate = false;
3309                }
3310                showWorkspace(animate);
3311            }
3312        }
3313    }
3314
3315    /**
3316     * Receives notifications whenever the appwidgets are reset.
3317     */
3318    private class AppWidgetResetObserver extends ContentObserver {
3319        public AppWidgetResetObserver() {
3320            super(new Handler());
3321        }
3322
3323        @Override
3324        public void onChange(boolean selfChange) {
3325            onAppWidgetReset();
3326        }
3327    }
3328
3329    /**
3330     * If the activity is currently paused, signal that we need to re-run the loader
3331     * in onResume.
3332     *
3333     * This needs to be called from incoming places where resources might have been loaded
3334     * while we are paused.  That is becaues the Configuration might be wrong
3335     * when we're not running, and if it comes back to what it was when we
3336     * were paused, we are not restarted.
3337     *
3338     * Implementation of the method from LauncherModel.Callbacks.
3339     *
3340     * @return true if we are currently paused.  The caller might be able to
3341     * skip some work in that case since we will come back again.
3342     */
3343    public boolean setLoadOnResume() {
3344        if (mPaused) {
3345            Log.i(TAG, "setLoadOnResume");
3346            mOnResumeNeedsLoad = true;
3347            return true;
3348        } else {
3349            return false;
3350        }
3351    }
3352
3353    /**
3354     * Implementation of the method from LauncherModel.Callbacks.
3355     */
3356    public int getCurrentWorkspaceScreen() {
3357        if (mWorkspace != null) {
3358            return mWorkspace.getCurrentPage();
3359        } else {
3360            return SCREEN_COUNT / 2;
3361        }
3362    }
3363
3364    void setAllAppsPagedView(AllAppsPagedView view) {
3365        mAllAppsPagedView = view;
3366    }
3367
3368    /**
3369     * Refreshes the shortcuts shown on the workspace.
3370     *
3371     * Implementation of the method from LauncherModel.Callbacks.
3372     */
3373    public void startBinding() {
3374        final Workspace workspace = mWorkspace;
3375
3376        mWorkspace.clearDropTargets();
3377        int count = workspace.getChildCount();
3378        for (int i = 0; i < count; i++) {
3379            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
3380            final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i);
3381            layoutParent.removeAllViewsInLayout();
3382        }
3383
3384        if (DEBUG_USER_INTERFACE) {
3385            android.widget.Button finishButton = new android.widget.Button(this);
3386            finishButton.setText("Finish");
3387            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
3388
3389            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
3390                public void onClick(View v) {
3391                    finish();
3392                }
3393            });
3394        }
3395
3396        // This wasn't being called before which resulted in a leak of AppWidgetHostViews (through
3397        // mDesktopItems -> AppWidgetInfo -> hostView).
3398        unbindDesktopItems();
3399    }
3400
3401    /**
3402     * Bind the items start-end from the list.
3403     *
3404     * Implementation of the method from LauncherModel.Callbacks.
3405     */
3406    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
3407
3408        setLoadOnResume();
3409
3410        final Workspace workspace = mWorkspace;
3411
3412        for (int i=start; i<end; i++) {
3413            final ItemInfo item = shortcuts.get(i);
3414            mDesktopItems.add(item);
3415            switch (item.itemType) {
3416                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
3417                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
3418                    final View shortcut = createShortcut((ShortcutInfo)item);
3419                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
3420                            false);
3421                    break;
3422                case LauncherSettings.Favorites.ITEM_TYPE_FOLDER:
3423                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
3424                            (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()),
3425                            (FolderInfo) item, mIconCache);
3426                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
3427                            false);
3428                    break;
3429            }
3430        }
3431
3432        workspace.requestLayout();
3433    }
3434
3435    /**
3436     * Implementation of the method from LauncherModel.Callbacks.
3437     */
3438    public void bindFolders(HashMap<Long, FolderInfo> folders) {
3439        setLoadOnResume();
3440        sFolders.clear();
3441        sFolders.putAll(folders);
3442    }
3443
3444    /**
3445     * Add the views for a widget to the workspace.
3446     *
3447     * Implementation of the method from LauncherModel.Callbacks.
3448     */
3449    public void bindAppWidget(LauncherAppWidgetInfo item) {
3450        setLoadOnResume();
3451
3452        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
3453        if (DEBUG_WIDGETS) {
3454            Log.d(TAG, "bindAppWidget: " + item);
3455        }
3456        final Workspace workspace = mWorkspace;
3457
3458        final int appWidgetId = item.appWidgetId;
3459        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
3460        if (DEBUG_WIDGETS) {
3461            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
3462        }
3463
3464        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
3465
3466        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
3467        item.hostView.setTag(item);
3468
3469        workspace.addInScreen(item.hostView, item.screen, item.cellX,
3470                item.cellY, item.spanX, item.spanY, false);
3471
3472        addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo);
3473
3474        workspace.requestLayout();
3475
3476        mDesktopItems.add(item);
3477
3478        if (DEBUG_WIDGETS) {
3479            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
3480                    + (SystemClock.uptimeMillis()-start) + "ms");
3481        }
3482    }
3483
3484    /**
3485     * Callback saying that there aren't any more items to bind.
3486     *
3487     * Implementation of the method from LauncherModel.Callbacks.
3488     */
3489    public void finishBindingItems() {
3490        setLoadOnResume();
3491
3492        if (mSavedState != null) {
3493            if (!mWorkspace.hasFocus()) {
3494                mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus();
3495            }
3496
3497            final long[] folders = mSavedState.getLongArray(RUNTIME_STATE_FOLDERS);
3498            if (folders != null) {
3499                for (long folderId : folders) {
3500                    final FolderInfo info = sFolders.get(folderId);
3501                    final FolderIcon folderIcon = (FolderIcon)
3502                        mWorkspace.getViewForTag(info);
3503                    if (folderIcon != null) {
3504                        openFolder(folderIcon);
3505                    }
3506                }
3507                final Folder openFolder = mWorkspace.getOpenFolder();
3508                if (openFolder != null) {
3509                    openFolder.requestFocus();
3510                }
3511            }
3512
3513            mSavedState = null;
3514        }
3515
3516        if (mSavedInstanceState != null) {
3517            super.onRestoreInstanceState(mSavedInstanceState);
3518            mSavedInstanceState = null;
3519        }
3520
3521        // Workaround a bug that occurs when rotating the device while the customization mode is
3522        // open, we trigger a new layout on all the CellLayout children.
3523        if (LauncherApplication.isScreenLarge() && (mState == State.CUSTOMIZE)) {
3524            final int childCount = mWorkspace.getChildCount();
3525            for (int i = 0; i < childCount; ++i) {
3526                mWorkspace.getChildAt(i).requestLayout();
3527            }
3528        }
3529
3530        mWorkspaceLoading = false;
3531
3532        // If we received the result of any pending adds while the loader was running (e.g. the
3533        // widget configuration forced an orientation change), process them now.
3534        for (int i = 0; i < sPendingAddList.size(); i++) {
3535            completeAdd(sPendingAddList.get(i));
3536        }
3537        sPendingAddList.clear();
3538    }
3539
3540    /**
3541     * Updates the icons on the launcher that are affected by changes to the package list
3542     * on the device.
3543     */
3544    private void updateIconsAffectedByPackageManagerChanges() {
3545        updateAppMarketIcon();
3546        updateGlobalSearchIcon();
3547        updateVoiceSearchIcon();
3548    }
3549
3550    /**
3551     * Add the icons for all apps.
3552     *
3553     * Implementation of the method from LauncherModel.Callbacks.
3554     */
3555    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
3556        if (mAllAppsGrid != null) {
3557            mAllAppsGrid.setApps(apps);
3558        }
3559        if (mAppsCustomizeContent != null) {
3560            mAppsCustomizeContent.setApps(apps);
3561        }
3562        if (mCustomizePagedView != null) {
3563            mCustomizePagedView.setApps(apps);
3564        }
3565        updateIconsAffectedByPackageManagerChanges();
3566    }
3567
3568    /**
3569     * A package was installed.
3570     *
3571     * Implementation of the method from LauncherModel.Callbacks.
3572     */
3573    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
3574        setLoadOnResume();
3575        removeDialog(DIALOG_CREATE_SHORTCUT);
3576        if (mAllAppsGrid != null) {
3577            mAllAppsGrid.addApps(apps);
3578        }
3579        if (mAppsCustomizeContent != null) {
3580            mAppsCustomizeContent.addApps(apps);
3581        }
3582        if (mCustomizePagedView != null) {
3583            mCustomizePagedView.addApps(apps);
3584        }
3585        updateIconsAffectedByPackageManagerChanges();
3586    }
3587
3588    /**
3589     * A package was updated.
3590     *
3591     * Implementation of the method from LauncherModel.Callbacks.
3592     */
3593    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
3594        setLoadOnResume();
3595        removeDialog(DIALOG_CREATE_SHORTCUT);
3596        if (mWorkspace != null) {
3597            mWorkspace.updateShortcuts(apps);
3598        }
3599        if (mAllAppsGrid != null) {
3600            mAllAppsGrid.updateApps(apps);
3601        }
3602        if (mAppsCustomizeContent != null) {
3603            mAppsCustomizeContent.updateApps(apps);
3604        }
3605        if (mCustomizePagedView != null) {
3606            mCustomizePagedView.updateApps(apps);
3607        }
3608        updateIconsAffectedByPackageManagerChanges();
3609    }
3610
3611    /**
3612     * A package was uninstalled.
3613     *
3614     * Implementation of the method from LauncherModel.Callbacks.
3615     */
3616    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
3617        removeDialog(DIALOG_CREATE_SHORTCUT);
3618        if (permanent) {
3619            mWorkspace.removeItems(apps);
3620        }
3621        if (mAllAppsGrid != null) {
3622            mAllAppsGrid.removeApps(apps);
3623        }
3624        if (mAppsCustomizeContent != null) {
3625            mAppsCustomizeContent.removeApps(apps);
3626        }
3627        if (mCustomizePagedView != null) {
3628            mCustomizePagedView.removeApps(apps);
3629        }
3630        updateIconsAffectedByPackageManagerChanges();
3631    }
3632
3633    /**
3634     * A number of packages were updated.
3635     */
3636    public void bindPackagesUpdated() {
3637        // update the customization drawer contents
3638        if (mCustomizePagedView != null) {
3639            mCustomizePagedView.update();
3640        }
3641        if (mAppsCustomizeContent != null) {
3642            mAppsCustomizeContent.onPackagesUpdated();
3643        }
3644    }
3645
3646    private int mapConfigurationOriActivityInfoOri(int configOri) {
3647        final Display d = getWindowManager().getDefaultDisplay();
3648        int naturalOri = Configuration.ORIENTATION_LANDSCAPE;
3649        switch (d.getRotation()) {
3650        case Surface.ROTATION_0:
3651        case Surface.ROTATION_180:
3652            // We are currently in the same basic orientation as the natural orientation
3653            naturalOri = configOri;
3654            break;
3655        case Surface.ROTATION_90:
3656        case Surface.ROTATION_270:
3657            // We are currently in the other basic orientation to the natural orientation
3658            naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ?
3659                    Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
3660            break;
3661        }
3662
3663        int[] oriMap = {
3664                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
3665                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
3666                ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
3667                ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
3668        };
3669        // Since the map starts at portrait, we need to offset if this device's natural orientation
3670        // is landscape.
3671        int indexOffset = 0;
3672        if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) {
3673            indexOffset = 1;
3674        }
3675        return oriMap[(d.getRotation() + indexOffset) % 4];
3676    }
3677    public void lockScreenOrientation() {
3678        setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources()
3679                .getConfiguration().orientation));
3680    }
3681    public void unlockScreenOrientation() {
3682        mHandler.postDelayed(new Runnable() {
3683            public void run() {
3684                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
3685            }
3686        }, mRestoreScreenOrientationDelay);
3687    }
3688
3689    /**
3690     * Prints out out state for debugging.
3691     */
3692    public void dumpState() {
3693        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
3694        Log.d(TAG, "mSavedState=" + mSavedState);
3695        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
3696        Log.d(TAG, "mRestoring=" + mRestoring);
3697        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
3698        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
3699        Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size());
3700        Log.d(TAG, "sFolders.size=" + sFolders.size());
3701        mModel.dumpState();
3702        if (mAllAppsGrid != null) {
3703            mAllAppsGrid.dumpState();
3704        }
3705        if (mAppsCustomizeContent != null) {
3706            mAppsCustomizeContent.dumpState();
3707        }
3708        Log.d(TAG, "END launcher2 dump state");
3709    }
3710}
3711
3712interface LauncherTransitionable {
3713    void onLauncherTransitionStart(Animator animation);
3714    void onLauncherTransitionEnd(Animator animation);
3715}
3716