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