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