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