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