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