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