Launcher.java revision ab962b75eeb9f956ac2eb1b00e66f6cca492010e
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher2;
18
19import com.android.common.Search;
20import com.android.launcher.R;
21
22import android.app.Activity;
23import android.app.AlertDialog;
24import android.app.Dialog;
25import android.app.SearchManager;
26import android.app.StatusBarManager;
27import android.app.WallpaperManager;
28import android.appwidget.AppWidgetManager;
29import android.appwidget.AppWidgetProviderInfo;
30import android.content.ActivityNotFoundException;
31import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.DialogInterface;
36import android.content.Intent;
37import android.content.Intent.ShortcutIconResource;
38import android.content.IntentFilter;
39import android.content.pm.ActivityInfo;
40import android.content.pm.PackageManager;
41import android.content.pm.ResolveInfo;
42import android.content.res.Configuration;
43import android.content.res.Resources;
44import android.content.res.TypedArray;
45import android.database.ContentObserver;
46import android.graphics.Bitmap;
47import android.graphics.Canvas;
48import android.graphics.Rect;
49import android.graphics.drawable.ColorDrawable;
50import android.graphics.drawable.Drawable;
51import android.net.Uri;
52import android.os.Bundle;
53import android.os.Handler;
54import android.os.Parcelable;
55import android.os.SystemClock;
56import android.os.SystemProperties;
57import android.provider.LiveFolders;
58import android.text.Selection;
59import android.text.SpannableStringBuilder;
60import android.text.TextUtils;
61import android.text.method.TextKeyListener;
62import android.util.Log;
63import android.view.Display;
64import android.view.HapticFeedbackConstants;
65import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import android.view.Menu;
68import android.view.MenuItem;
69import android.view.MotionEvent;
70import android.view.View;
71import android.view.View.OnLongClickListener;
72import android.view.ViewGroup;
73import android.view.WindowManager;
74import android.view.animation.Animation;
75import android.view.animation.Animation.AnimationListener;
76import android.view.animation.AnimationUtils;
77import android.view.inputmethod.InputMethodManager;
78import android.widget.EditText;
79import android.widget.ImageView;
80import android.widget.LinearLayout;
81import android.widget.PopupWindow;
82import android.widget.TabHost;
83import android.widget.TextView;
84import android.widget.Toast;
85
86import java.io.DataInputStream;
87import java.io.DataOutputStream;
88import java.io.FileNotFoundException;
89import java.io.IOException;
90import java.util.ArrayList;
91import java.util.HashMap;
92import java.util.List;
93
94/**
95 * Default launcher application.
96 */
97public final class Launcher extends Activity
98        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks,
99                   AllAppsView.Watcher, View.OnTouchListener {
100    static final String TAG = "Launcher";
101    static final boolean LOGD = false;
102
103    static final boolean PROFILE_STARTUP = false;
104    static final boolean DEBUG_WIDGETS = false;
105    static final boolean DEBUG_USER_INTERFACE = false;
106
107    private static final int WALLPAPER_SCREENS_SPAN = 2;
108
109    private static final int MENU_GROUP_ADD = 1;
110    private static final int MENU_GROUP_WALLPAPER = MENU_GROUP_ADD + 1;
111
112    private static final int MENU_ADD = Menu.FIRST + 1;
113    private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
114    private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
115    private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
116    private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
117
118    private static final int REQUEST_CREATE_SHORTCUT = 1;
119    private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
120    private static final int REQUEST_CREATE_APPWIDGET = 5;
121    private static final int REQUEST_PICK_APPLICATION = 6;
122    private static final int REQUEST_PICK_SHORTCUT = 7;
123    private static final int REQUEST_PICK_LIVE_FOLDER = 8;
124    private static final int REQUEST_PICK_APPWIDGET = 9;
125    private static final int REQUEST_PICK_WALLPAPER = 10;
126
127    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
128
129    static final int SCREEN_COUNT = 5;
130    static final int DEFAULT_SCREEN = 2;
131    static final int NUMBER_CELLS_X = 4;
132    static final int NUMBER_CELLS_Y = 4;
133
134    static final int DIALOG_CREATE_SHORTCUT = 1;
135    static final int DIALOG_RENAME_FOLDER = 2;
136
137    private static final String PREFERENCES = "launcher.preferences";
138
139    // Type: int
140    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
141    // Type: boolean
142    private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
143    // Type: long
144    private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
145    // Type: int
146    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
147    // Type: int
148    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
149    // Type: int
150    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
151    // Type: int
152    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
153    // Type: int
154    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
155    // Type: int
156    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
157    // Type: int
158    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
159    // Type: int[]
160    private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
161    // Type: boolean
162    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
163    // Type: long
164    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
165
166    static final int APPWIDGET_HOST_ID = 1024;
167
168    private static final Object sLock = new Object();
169    private static int sScreen = DEFAULT_SCREEN;
170
171    private final BroadcastReceiver mCloseSystemDialogsReceiver
172            = new CloseSystemDialogsIntentReceiver();
173    private final ContentObserver mWidgetObserver = new AppWidgetResetObserver();
174
175    private LayoutInflater mInflater;
176
177    private DragController mDragController;
178    private Workspace mWorkspace;
179
180    private AppWidgetManager mAppWidgetManager;
181    private LauncherAppWidgetHost mAppWidgetHost;
182
183    private CellLayout.CellInfo mAddItemCellInfo;
184    private CellLayout.CellInfo mMenuAddInfo;
185    private final int[] mCellCoordinates = new int[2];
186    private FolderInfo mFolderInfo;
187
188    private DeleteZone mDeleteZone;
189    private HandleView mHandleView;
190    private AllAppsView mAllAppsGrid;
191    private TabHost mHomeCustomizationDrawer;
192
193    private Bundle mSavedState;
194
195    private SpannableStringBuilder mDefaultKeySsb = null;
196
197    private boolean mWorkspaceLoading = true;
198
199    private boolean mPaused = true;
200    private boolean mRestoring;
201    private boolean mWaitingForResult;
202
203    private Bundle mSavedInstanceState;
204
205    private LauncherModel mModel;
206    private IconCache mIconCache;
207
208    private ArrayList<ItemInfo> mDesktopItems = new ArrayList<ItemInfo>();
209    private static HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>();
210
211    private ImageView mPreviousView;
212    private ImageView mNextView;
213
214    // Hotseats (quick-launch icons next to AllApps)
215    private static final int NUM_HOTSEATS = 2;
216    private String[] mHotseatConfig = null;
217    private Intent[] mHotseats = null;
218    private Drawable[] mHotseatIcons = null;
219    private CharSequence[] mHotseatLabels = null;
220
221
222    @Override
223    protected void onCreate(Bundle savedInstanceState) {
224        super.onCreate(savedInstanceState);
225
226        if (LauncherApplication.isInPlaceRotationEnabled()) {
227            // hide the status bar (temporary until we get the status bar design figured out)
228            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
229            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
230        }
231
232        LauncherApplication app = ((LauncherApplication)getApplication());
233        mModel = app.setLauncher(this);
234        mIconCache = app.getIconCache();
235        mDragController = new DragController(this);
236        mInflater = getLayoutInflater();
237
238        mAppWidgetManager = AppWidgetManager.getInstance(this);
239        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
240        mAppWidgetHost.startListening();
241
242        if (PROFILE_STARTUP) {
243            android.os.Debug.startMethodTracing("/sdcard/launcher");
244        }
245
246        loadHotseats();
247        checkForLocaleChange();
248        setWallpaperDimension();
249        setContentView(R.layout.launcher);
250        mHomeCustomizationDrawer = (TabHost) findViewById(com.android.internal.R.id.tabhost);
251        if (mHomeCustomizationDrawer != null) {
252            mHomeCustomizationDrawer.setup();
253
254            String widgetsLabel = getString(R.string.widgets_tab_label);
255            mHomeCustomizationDrawer.addTab(mHomeCustomizationDrawer.newTabSpec("widgets")
256                    .setIndicator(widgetsLabel).setContent(R.id.widget_chooser));
257            String foldersLabel = getString(R.string.folders_tab_label);
258            mHomeCustomizationDrawer.addTab(mHomeCustomizationDrawer.newTabSpec("folders")
259                    .setIndicator(foldersLabel).setContent(R.id.folder_chooser));
260            String shortcutsLabel = getString(R.string.shortcuts_tab_label);
261            mHomeCustomizationDrawer.addTab(mHomeCustomizationDrawer.newTabSpec("shortcuts")
262                    .setIndicator(shortcutsLabel).setContent(R.id.shortcut_chooser));
263            String wallpapersLabel = getString(R.string.wallpapers_tab_label);
264            mHomeCustomizationDrawer.addTab(mHomeCustomizationDrawer.newTabSpec("wallpapers")
265                    .setIndicator(wallpapersLabel).setContent(R.id.wallpaperstab));
266
267            mHomeCustomizationDrawer.setCurrentTab(0);
268        }
269        setupViews();
270
271        registerContentObservers();
272
273        lockAllApps();
274
275        mSavedState = savedInstanceState;
276        restoreState(mSavedState);
277
278        if (PROFILE_STARTUP) {
279            android.os.Debug.stopMethodTracing();
280        }
281
282        if (!mRestoring) {
283            mModel.startLoader(this, true);
284        }
285
286        // For handling default keys
287        mDefaultKeySsb = new SpannableStringBuilder();
288        Selection.setSelection(mDefaultKeySsb, 0);
289
290        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
291        registerReceiver(mCloseSystemDialogsReceiver, filter);
292    }
293
294    @Override
295    public void onConfigurationChanged(Configuration newConfig) {
296        // TODO Auto-generated method stub
297        super.onConfigurationChanged(newConfig);
298
299        if (LauncherApplication.isInPlaceRotationEnabled()) {
300            mModel.updateOrientation();
301            mWorkspace.refreshWorkspaceChildren();
302            mWorkspace.rotateCurrentScreensChildren();
303        }
304    }
305
306
307    private void checkForLocaleChange() {
308        final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
309        readConfiguration(this, localeConfiguration);
310
311        final Configuration configuration = getResources().getConfiguration();
312
313        final String previousLocale = localeConfiguration.locale;
314        final String locale = configuration.locale.toString();
315
316        final int previousMcc = localeConfiguration.mcc;
317        final int mcc = configuration.mcc;
318
319        final int previousMnc = localeConfiguration.mnc;
320        final int mnc = configuration.mnc;
321
322        boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
323
324        if (localeChanged) {
325            localeConfiguration.locale = locale;
326            localeConfiguration.mcc = mcc;
327            localeConfiguration.mnc = mnc;
328
329            writeConfiguration(this, localeConfiguration);
330            mIconCache.flush();
331
332            loadHotseats();
333        }
334    }
335
336    private static class LocaleConfiguration {
337        public String locale;
338        public int mcc = -1;
339        public int mnc = -1;
340    }
341
342    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
343        DataInputStream in = null;
344        try {
345            in = new DataInputStream(context.openFileInput(PREFERENCES));
346            configuration.locale = in.readUTF();
347            configuration.mcc = in.readInt();
348            configuration.mnc = in.readInt();
349        } catch (FileNotFoundException e) {
350            // Ignore
351        } catch (IOException e) {
352            // Ignore
353        } finally {
354            if (in != null) {
355                try {
356                    in.close();
357                } catch (IOException e) {
358                    // Ignore
359                }
360            }
361        }
362    }
363
364    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
365        DataOutputStream out = null;
366        try {
367            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
368            out.writeUTF(configuration.locale);
369            out.writeInt(configuration.mcc);
370            out.writeInt(configuration.mnc);
371            out.flush();
372        } catch (FileNotFoundException e) {
373            // Ignore
374        } catch (IOException e) {
375            //noinspection ResultOfMethodCallIgnored
376            context.getFileStreamPath(PREFERENCES).delete();
377        } finally {
378            if (out != null) {
379                try {
380                    out.close();
381                } catch (IOException e) {
382                    // Ignore
383                }
384            }
385        }
386    }
387
388    static int getScreen() {
389        synchronized (sLock) {
390            return sScreen;
391        }
392    }
393
394    static void setScreen(int screen) {
395        synchronized (sLock) {
396            sScreen = screen;
397        }
398    }
399
400    private void setWallpaperDimension() {
401        WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
402
403        Display display = getWindowManager().getDefaultDisplay();
404        boolean isPortrait = display.getWidth() < display.getHeight();
405
406        final int width = isPortrait ? display.getWidth() : display.getHeight();
407        final int height = isPortrait ? display.getHeight() : display.getWidth();
408        wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);
409    }
410
411    // Note: This doesn't do all the client-id magic that BrowserProvider does
412    // in Browser. (http://b/2425179)
413    private Uri getDefaultBrowserUri() {
414        String url = getString(R.string.default_browser_url);
415        if (url.indexOf("{CID}") != -1) {
416            url = url.replace("{CID}", "android-google");
417        }
418        return Uri.parse(url);
419    }
420
421    // Load the Intent templates from arrays.xml to populate the hotseats. For
422    // each Intent, if it resolves to a single app, use that as the launch
423    // intent & use that app's label as the contentDescription. Otherwise,
424    // retain the ResolveActivity so the user can pick an app.
425    private void loadHotseats() {
426        if (mHotseatConfig == null) {
427            mHotseatConfig = getResources().getStringArray(R.array.hotseats);
428            if (mHotseatConfig.length > 0) {
429                mHotseats = new Intent[mHotseatConfig.length];
430                mHotseatLabels = new CharSequence[mHotseatConfig.length];
431                mHotseatIcons = new Drawable[mHotseatConfig.length];
432            } else {
433                mHotseats = null;
434                mHotseatIcons = null;
435                mHotseatLabels = null;
436            }
437
438            TypedArray hotseatIconDrawables = getResources().obtainTypedArray(R.array.hotseat_icons);
439            for (int i=0; i<mHotseatConfig.length; i++) {
440                // load icon for this slot; currently unrelated to the actual activity
441                try {
442                    mHotseatIcons[i] = hotseatIconDrawables.getDrawable(i);
443                } catch (ArrayIndexOutOfBoundsException ex) {
444                    Log.w(TAG, "Missing hotseat_icons array item #" + i);
445                    mHotseatIcons[i] = null;
446                }
447            }
448            hotseatIconDrawables.recycle();
449        }
450
451        PackageManager pm = getPackageManager();
452        for (int i=0; i<mHotseatConfig.length; i++) {
453            Intent intent = null;
454            if (mHotseatConfig[i].equals("*BROWSER*")) {
455                // magic value meaning "launch user's default web browser"
456                // replace it with a generic web request so we can see if there is indeed a default
457                String defaultUri = getString(R.string.default_browser_url);
458                intent = new Intent(
459                        Intent.ACTION_VIEW,
460                        ((defaultUri != null)
461                            ? Uri.parse(defaultUri)
462                            : getDefaultBrowserUri())
463                    ).addCategory(Intent.CATEGORY_BROWSABLE);
464                // note: if the user launches this without a default set, she
465                // will always be taken to the default URL above; this is
466                // unavoidable as we must specify a valid URL in order for the
467                // chooser to appear, and once the user selects something, that
468                // URL is unavoidably sent to the chosen app.
469            } else {
470                try {
471                    intent = Intent.parseUri(mHotseatConfig[i], 0);
472                } catch (java.net.URISyntaxException ex) {
473                    Log.w(TAG, "Invalid hotseat intent: " + mHotseatConfig[i]);
474                    // bogus; leave intent=null
475                }
476            }
477
478            if (intent == null) {
479                mHotseats[i] = null;
480                mHotseatLabels[i] = getText(R.string.activity_not_found);
481                continue;
482            }
483
484            if (LOGD) {
485                Log.d(TAG, "loadHotseats: hotseat " + i
486                    + " initial intent=["
487                    + intent.toUri(Intent.URI_INTENT_SCHEME)
488                    + "]");
489            }
490
491            ResolveInfo bestMatch = pm.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
492            List<ResolveInfo> allMatches = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
493            if (LOGD) {
494                Log.d(TAG, "Best match for intent: " + bestMatch);
495                Log.d(TAG, "All matches: ");
496                for (ResolveInfo ri : allMatches) {
497                    Log.d(TAG, "  --> " + ri);
498                }
499            }
500            // did this resolve to a single app, or the resolver?
501            if (allMatches.size() == 0 || bestMatch == null) {
502                // can't find any activity to handle this. let's leave the
503                // intent as-is and let Launcher show a toast when it fails
504                // to launch.
505                mHotseats[i] = intent;
506
507                // set accessibility text to "Not installed"
508                mHotseatLabels[i] = getText(R.string.activity_not_found);
509            } else {
510                boolean found = false;
511                for (ResolveInfo ri : allMatches) {
512                    if (bestMatch.activityInfo.name.equals(ri.activityInfo.name)
513                        && bestMatch.activityInfo.applicationInfo.packageName
514                            .equals(ri.activityInfo.applicationInfo.packageName)) {
515                        found = true;
516                        break;
517                    }
518                }
519
520                if (!found) {
521                    if (LOGD) Log.d(TAG, "Multiple options, no default yet");
522                    // the bestMatch is probably the ResolveActivity, meaning the
523                    // user has not yet selected a default
524                    // so: we'll keep the original intent for now
525                    mHotseats[i] = intent;
526
527                    // set the accessibility text to "Select shortcut"
528                    mHotseatLabels[i] = getText(R.string.title_select_shortcut);
529                } else {
530                    // we have an app!
531                    // now reconstruct the intent to launch it through the front
532                    // door
533                    ComponentName com = new ComponentName(
534                        bestMatch.activityInfo.applicationInfo.packageName,
535                        bestMatch.activityInfo.name);
536                    mHotseats[i] = new Intent(Intent.ACTION_MAIN).setComponent(com);
537
538                    // load the app label for accessibility
539                    mHotseatLabels[i] = bestMatch.activityInfo.loadLabel(pm);
540                }
541            }
542
543            if (LOGD) {
544                Log.d(TAG, "loadHotseats: hotseat " + i
545                    + " final intent=["
546                    + ((mHotseats[i] == null)
547                        ? "null"
548                        : mHotseats[i].toUri(Intent.URI_INTENT_SCHEME))
549                    + "] label=[" + mHotseatLabels[i]
550                    + "]"
551                    );
552            }
553        }
554    }
555
556    @Override
557    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
558        mWaitingForResult = false;
559
560        // The pattern used here is that a user PICKs a specific application,
561        // which, depending on the target, might need to CREATE the actual target.
562
563        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
564        // launch over to the Music app to actually CREATE_SHORTCUT.
565
566        if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
567            switch (requestCode) {
568                case REQUEST_PICK_APPLICATION:
569                    completeAddApplication(this, data, mAddItemCellInfo);
570                    break;
571                case REQUEST_PICK_SHORTCUT:
572                    processShortcut(data);
573                    break;
574                case REQUEST_CREATE_SHORTCUT:
575                    completeAddShortcut(data, mAddItemCellInfo);
576                    break;
577                case REQUEST_PICK_LIVE_FOLDER:
578                    addLiveFolder(data);
579                    break;
580                case REQUEST_CREATE_LIVE_FOLDER:
581                    completeAddLiveFolder(data, mAddItemCellInfo);
582                    break;
583                case REQUEST_PICK_APPWIDGET:
584                    addAppWidgetFromPick(data);
585                    break;
586                case REQUEST_CREATE_APPWIDGET:
587                    int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
588                    completeAddAppWidget(appWidgetId, mAddItemCellInfo);
589                    break;
590                case REQUEST_PICK_WALLPAPER:
591                    // We just wanted the activity result here so we can clear mWaitingForResult
592                    break;
593            }
594        } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
595                requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED &&
596                data != null) {
597            // Clean up the appWidgetId if we canceled
598            int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
599            if (appWidgetId != -1) {
600                mAppWidgetHost.deleteAppWidgetId(appWidgetId);
601            }
602        }
603    }
604
605    @Override
606    protected void onResume() {
607        super.onResume();
608
609        mPaused = false;
610
611        if (mRestoring) {
612            mWorkspaceLoading = true;
613            mModel.startLoader(this, true);
614            mRestoring = false;
615        }
616    }
617
618    @Override
619    protected void onPause() {
620        super.onPause();
621        // Some launcher layouts don't have a previous and next view
622        if (mPreviousView != null) {
623            dismissPreview(mPreviousView);
624        }
625        if (mNextView != null) {
626            dismissPreview(mNextView);
627        }
628        mDragController.cancelDrag();
629    }
630
631    @Override
632    public Object onRetainNonConfigurationInstance() {
633        // Flag the loader to stop early before switching
634        mModel.stopLoader();
635        mAllAppsGrid.surrender();
636        return Boolean.TRUE;
637    }
638
639    // We can't hide the IME if it was forced open.  So don't bother
640    /*
641    @Override
642    public void onWindowFocusChanged(boolean hasFocus) {
643        super.onWindowFocusChanged(hasFocus);
644
645        if (hasFocus) {
646            final InputMethodManager inputManager = (InputMethodManager)
647                    getSystemService(Context.INPUT_METHOD_SERVICE);
648            WindowManager.LayoutParams lp = getWindow().getAttributes();
649            inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new
650                        android.os.Handler()) {
651                        protected void onReceiveResult(int resultCode, Bundle resultData) {
652                            Log.d(TAG, "ResultReceiver got resultCode=" + resultCode);
653                        }
654                    });
655            Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged");
656        }
657    }
658    */
659
660    private boolean acceptFilter() {
661        final InputMethodManager inputManager = (InputMethodManager)
662                getSystemService(Context.INPUT_METHOD_SERVICE);
663        return !inputManager.isFullscreenMode();
664    }
665
666    @Override
667    public boolean onKeyDown(int keyCode, KeyEvent event) {
668        boolean handled = super.onKeyDown(keyCode, event);
669        if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
670            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
671                    keyCode, event);
672            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
673                // something usable has been typed - start a search
674                // the typed text will be retrieved and cleared by
675                // showSearchDialog()
676                // If there are multiple keystrokes before the search dialog takes focus,
677                // onSearchRequested() will be called for every keystroke,
678                // but it is idempotent, so it's fine.
679                return onSearchRequested();
680            }
681        }
682
683        // Eat the long press event so the keyboard doesn't come up.
684        if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) {
685            return true;
686        }
687
688        return handled;
689    }
690
691    private String getTypedText() {
692        return mDefaultKeySsb.toString();
693    }
694
695    private void clearTypedText() {
696        mDefaultKeySsb.clear();
697        mDefaultKeySsb.clearSpans();
698        Selection.setSelection(mDefaultKeySsb, 0);
699    }
700
701    /**
702     * Restores the previous state, if it exists.
703     *
704     * @param savedState The previous state.
705     */
706    private void restoreState(Bundle savedState) {
707        if (savedState == null) {
708            return;
709        }
710
711        final boolean allApps = savedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
712        if (allApps) {
713            showAllApps(false);
714        }
715
716        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
717        if (currentScreen > -1) {
718            mWorkspace.setCurrentScreen(currentScreen);
719        }
720
721        final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
722        if (addScreen > -1) {
723            mAddItemCellInfo = new CellLayout.CellInfo();
724            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
725            addItemCellInfo.valid = true;
726            addItemCellInfo.screen = addScreen;
727            addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
728            addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
729            addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
730            addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
731            addItemCellInfo.findVacantCellsFromOccupied(
732                    savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
733                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
734                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
735            mRestoring = true;
736        }
737
738        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
739        if (renameFolder) {
740            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
741            mFolderInfo = mModel.getFolderById(this, mFolders, id);
742            mRestoring = true;
743        }
744    }
745
746    /**
747     * Finds all the views we need and configure them properly.
748     */
749    private void setupViews() {
750        DragController dragController = mDragController;
751
752        DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
753        dragLayer.setDragController(dragController);
754
755        mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view);
756        mAllAppsGrid.setLauncher(this);
757        mAllAppsGrid.setDragController(dragController);
758        ((View) mAllAppsGrid).setWillNotDraw(false); // We don't want a hole punched in our window.
759        // Manage focusability manually since this thing is always visible
760        ((View) mAllAppsGrid).setFocusable(false);
761
762        mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
763        final Workspace workspace = mWorkspace;
764        workspace.setHapticFeedbackEnabled(false);
765
766        // We only intercept touch events to dismiss the home customization drawer; if it doesn't
767        //  exist, then no need to do this
768        if (mHomeCustomizationDrawer != null)
769            workspace.setOnInterceptTouchListener(this);
770
771        DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
772        mDeleteZone = deleteZone;
773
774        mHandleView = (HandleView) findViewById(R.id.all_apps_button);
775        mHandleView.setLauncher(this);
776        mHandleView.setOnClickListener(this);
777        mHandleView.setOnLongClickListener(this);
778
779        WidgetChooser widgetChooser = (WidgetChooser) findViewById(R.id.widget_chooser);
780        if (widgetChooser != null) {
781            WidgetListAdapter widgetGalleryAdapter = new WidgetListAdapter(this);
782            widgetChooser.setAdapter(widgetGalleryAdapter);
783            widgetChooser.setDragController(dragController);
784            widgetChooser.setLauncher(this);
785
786            FolderChooser folderChooser = (FolderChooser) findViewById(R.id.folder_chooser);
787            IntentListAdapter folderTypes = new FolderListAdapter(this, LiveFolders.ACTION_CREATE_LIVE_FOLDER);
788            folderChooser.setAdapter(folderTypes);
789            folderChooser.setLauncher(this);
790
791            ShortcutChooser shortcutChooser = (ShortcutChooser) findViewById(R.id.shortcut_chooser);
792            IntentListAdapter shortcutTypes = new ShortcutListAdapter(this, Intent.ACTION_CREATE_SHORTCUT);
793            shortcutChooser.setAdapter(shortcutTypes);
794            shortcutChooser.setLauncher(this);
795        } else {
796             ImageView hotseatLeft = (ImageView) findViewById(R.id.hotseat_left);
797             hotseatLeft.setContentDescription(mHotseatLabels[0]);
798             hotseatLeft.setImageDrawable(mHotseatIcons[0]);
799             ImageView hotseatRight = (ImageView) findViewById(R.id.hotseat_right);
800             hotseatRight.setContentDescription(mHotseatLabels[1]);
801             hotseatRight.setImageDrawable(mHotseatIcons[1]);
802
803             mPreviousView = (ImageView) dragLayer.findViewById(R.id.previous_screen);
804             mNextView = (ImageView) dragLayer.findViewById(R.id.next_screen);
805
806             Drawable previous = mPreviousView.getDrawable();
807             Drawable next = mNextView.getDrawable();
808             mWorkspace.setIndicators(previous, next);
809
810             mPreviousView.setHapticFeedbackEnabled(false);
811             mPreviousView.setOnLongClickListener(this);
812             mNextView.setHapticFeedbackEnabled(false);
813             mNextView.setOnLongClickListener(this);
814        }
815
816        workspace.setOnLongClickListener(this);
817        workspace.setDragController(dragController);
818        workspace.setLauncher(this);
819
820        deleteZone.setLauncher(this);
821        deleteZone.setDragController(dragController);
822        int deleteZoneHandleId = LauncherApplication.isScreenXLarge() ? R.id.add_button : R.id.all_apps_button_cluster;
823        deleteZone.setHandle(findViewById(deleteZoneHandleId));
824
825        dragController.setDragScoller(workspace);
826        dragController.setDragListener(deleteZone);
827        dragController.setScrollView(dragLayer);
828        dragController.setMoveTarget(workspace);
829
830        // The order here is bottom to top.
831        dragController.addDropTarget(workspace);
832        dragController.addDropTarget(deleteZone);
833    }
834
835    @SuppressWarnings({"UnusedDeclaration"})
836    public void previousScreen(View v) {
837        if (!isAllAppsVisible()) {
838            mWorkspace.scrollLeft();
839        }
840    }
841
842    @SuppressWarnings({"UnusedDeclaration"})
843    public void nextScreen(View v) {
844        if (!isAllAppsVisible()) {
845            mWorkspace.scrollRight();
846        }
847    }
848
849    @SuppressWarnings({"UnusedDeclaration"})
850    public void launchHotSeat(View v) {
851        if (isAllAppsVisible()) return;
852
853        int index = -1;
854        if (v.getId() == R.id.hotseat_left) {
855            index = 0;
856        } else if (v.getId() == R.id.hotseat_right) {
857            index = 1;
858        }
859
860        // reload these every tap; you never know when they might change
861        loadHotseats();
862        if (index >= 0 && index < mHotseats.length && mHotseats[index] != null) {
863            Intent intent = mHotseats[index];
864            startActivitySafely(
865                mHotseats[index],
866                "hotseat"
867            );
868        }
869    }
870
871    /**
872     * Creates a view representing a shortcut.
873     *
874     * @param info The data structure describing the shortcut.
875     *
876     * @return A View inflated from R.layout.application.
877     */
878    View createShortcut(ShortcutInfo info) {
879        return createShortcut(R.layout.application,
880                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
881    }
882
883    /**
884     * Creates a view representing a shortcut inflated from the specified resource.
885     *
886     * @param layoutResId The id of the XML layout used to create the shortcut.
887     * @param parent The group the shortcut belongs to.
888     * @param info The data structure describing the shortcut.
889     *
890     * @return A View inflated from layoutResId.
891     */
892    View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) {
893        TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
894
895        favorite.setCompoundDrawablesWithIntrinsicBounds(null,
896                new FastBitmapDrawable(info.getIcon(mIconCache)),
897                null, null);
898        favorite.setText(info.title);
899        favorite.setTag(info);
900        favorite.setOnClickListener(this);
901
902        return favorite;
903    }
904
905    /**
906     * Add an application shortcut to the workspace.
907     *
908     * @param data The intent describing the application.
909     * @param cellInfo The position on screen where to create the shortcut.
910     */
911    void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) {
912        cellInfo.screen = mWorkspace.getCurrentScreen();
913        if (!findSingleSlot(cellInfo)) return;
914
915        final ShortcutInfo info = mModel.getShortcutInfo(context.getPackageManager(),
916                data, context);
917
918        if (info != null) {
919            info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK |
920                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
921            info.container = ItemInfo.NO_ID;
922            mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked());
923        } else {
924            Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data);
925        }
926    }
927
928    /**
929     * Add a shortcut to the workspace.
930     *
931     * @param data The intent describing the shortcut.
932     * @param cellInfo The position on screen where to create the shortcut.
933     */
934    private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) {
935        cellInfo.screen = mWorkspace.getCurrentScreen();
936        if (!findSingleSlot(cellInfo)) return;
937
938        final ShortcutInfo info = mModel.addShortcut(this, data, cellInfo, false);
939
940        if (!mRestoring) {
941            final View view = createShortcut(info);
942            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
943                    isWorkspaceLocked());
944        }
945    }
946
947
948    /**
949     * Add a widget to the workspace.
950     *
951     * @param data The intent describing the appWidgetId.
952     * @param cellInfo The position on screen where to create the widget.
953     */
954    private void completeAddAppWidget(int appWidgetId, CellLayout.CellInfo cellInfo) {
955        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
956
957        // Calculate the grid spans needed to fit this widget
958        CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
959        int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight, null);
960
961        // Try finding open space on Launcher screen
962        final int[] xy = mCellCoordinates;
963        if (!findSlot(cellInfo, xy, spans[0], spans[1])) {
964            if (appWidgetId != -1) mAppWidgetHost.deleteAppWidgetId(appWidgetId);
965            return;
966        }
967
968        // Build Launcher-specific widget info and save to database
969        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
970        launcherInfo.spanX = spans[0];
971        launcherInfo.spanY = spans[1];
972
973        LauncherModel.addItemToDatabase(this, launcherInfo,
974                LauncherSettings.Favorites.CONTAINER_DESKTOP,
975                mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
976
977        if (!mRestoring) {
978            mDesktopItems.add(launcherInfo);
979
980            // Perform actual inflation because we're live
981            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
982
983            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
984            launcherInfo.hostView.setTag(launcherInfo);
985
986            mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
987                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
988        }
989    }
990
991    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
992        mDesktopItems.remove(launcherInfo);
993        launcherInfo.hostView = null;
994    }
995
996    public LauncherAppWidgetHost getAppWidgetHost() {
997        return mAppWidgetHost;
998    }
999
1000    void closeSystemDialogs() {
1001        getWindow().closeAllPanels();
1002
1003        try {
1004            dismissDialog(DIALOG_CREATE_SHORTCUT);
1005            // Unlock the workspace if the dialog was showing
1006        } catch (Exception e) {
1007            // An exception is thrown if the dialog is not visible, which is fine
1008        }
1009
1010        try {
1011            dismissDialog(DIALOG_RENAME_FOLDER);
1012            // Unlock the workspace if the dialog was showing
1013        } catch (Exception e) {
1014            // An exception is thrown if the dialog is not visible, which is fine
1015        }
1016
1017        // Whatever we were doing is hereby canceled.
1018        mWaitingForResult = false;
1019    }
1020
1021    @Override
1022    protected void onNewIntent(Intent intent) {
1023        super.onNewIntent(intent);
1024
1025        // Close the menu
1026        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
1027            // also will cancel mWaitingForResult.
1028            closeSystemDialogs();
1029
1030            boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
1031                        != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
1032            boolean allAppsVisible = isAllAppsVisible();
1033
1034            // TODO: Figure out the right thing to do in XLarge mode here
1035            if (!mWorkspace.isDefaultScreenShowing()) {
1036                mWorkspace.moveToDefaultScreen(alreadyOnHome && !allAppsVisible);
1037            }
1038            closeAllApps(alreadyOnHome && allAppsVisible);
1039            hideCustomizationDrawer();
1040
1041            final View v = getWindow().peekDecorView();
1042            if (v != null && v.getWindowToken() != null) {
1043                InputMethodManager imm = (InputMethodManager)getSystemService(
1044                        INPUT_METHOD_SERVICE);
1045                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
1046            }
1047        }
1048    }
1049
1050    @Override
1051    protected void onRestoreInstanceState(Bundle savedInstanceState) {
1052        // Do not call super here
1053        mSavedInstanceState = savedInstanceState;
1054
1055        if (mHomeCustomizationDrawer != null) {
1056            String cur = savedInstanceState.getString("currentTab");
1057            if (cur != null) {
1058                mHomeCustomizationDrawer.setCurrentTabByTag(cur);
1059            }
1060        }
1061    }
1062
1063    @Override
1064    protected void onSaveInstanceState(Bundle outState) {
1065        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
1066
1067        final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
1068        if (folders.size() > 0) {
1069            final int count = folders.size();
1070            long[] ids = new long[count];
1071            for (int i = 0; i < count; i++) {
1072                final FolderInfo info = folders.get(i).getInfo();
1073                ids[i] = info.id;
1074            }
1075            outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
1076        } else {
1077            super.onSaveInstanceState(outState);
1078        }
1079
1080        // TODO should not do this if the drawer is currently closing.
1081        if (isAllAppsVisible()) {
1082            outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
1083        }
1084
1085        if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
1086            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
1087            final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
1088
1089            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
1090            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
1091            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
1092            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
1093            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
1094            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
1095            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
1096            outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
1097                   layout.getOccupiedCellsFlattened());
1098        }
1099
1100        if (mFolderInfo != null && mWaitingForResult) {
1101            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
1102            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
1103        }
1104
1105        if (mHomeCustomizationDrawer != null) {
1106            String currentTabTag = mHomeCustomizationDrawer.getCurrentTabTag();
1107            if (currentTabTag != null) {
1108                outState.putString("currentTab", currentTabTag);
1109            }
1110        }
1111    }
1112
1113    @Override
1114    public void onDestroy() {
1115        super.onDestroy();
1116
1117        try {
1118            mAppWidgetHost.stopListening();
1119        } catch (NullPointerException ex) {
1120            Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
1121        }
1122
1123        TextKeyListener.getInstance().release();
1124
1125        mModel.stopLoader();
1126
1127        unbindDesktopItems();
1128
1129        getContentResolver().unregisterContentObserver(mWidgetObserver);
1130
1131        // Some launcher layouts don't have a previous and next view
1132        if (mPreviousView != null) {
1133            dismissPreview(mPreviousView);
1134        }
1135        if (mNextView != null) {
1136            dismissPreview(mNextView);
1137        }
1138
1139        unregisterReceiver(mCloseSystemDialogsReceiver);
1140    }
1141
1142    @Override
1143    public void startActivityForResult(Intent intent, int requestCode) {
1144        if (requestCode >= 0) mWaitingForResult = true;
1145        super.startActivityForResult(intent, requestCode);
1146    }
1147
1148    @Override
1149    public void startSearch(String initialQuery, boolean selectInitialQuery,
1150            Bundle appSearchData, boolean globalSearch) {
1151
1152        closeAllApps(true);
1153
1154        if (initialQuery == null) {
1155            // Use any text typed in the launcher as the initial query
1156            initialQuery = getTypedText();
1157            clearTypedText();
1158        }
1159        if (appSearchData == null) {
1160            appSearchData = new Bundle();
1161            appSearchData.putString(Search.SOURCE, "launcher-search");
1162        }
1163
1164        final SearchManager searchManager =
1165                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1166        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1167            appSearchData, globalSearch);
1168    }
1169
1170    @Override
1171    public boolean onCreateOptionsMenu(Menu menu) {
1172        if (isWorkspaceLocked()) {
1173            return false;
1174        }
1175
1176        super.onCreateOptionsMenu(menu);
1177
1178        menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
1179                .setIcon(android.R.drawable.ic_menu_add)
1180                .setAlphabeticShortcut('A');
1181        menu.add(MENU_GROUP_WALLPAPER, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1182                 .setIcon(android.R.drawable.ic_menu_gallery)
1183                 .setAlphabeticShortcut('W');
1184        menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
1185                .setIcon(android.R.drawable.ic_search_category_default)
1186                .setAlphabeticShortcut(SearchManager.MENU_KEY);
1187        menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
1188                .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
1189                .setAlphabeticShortcut('N');
1190
1191        final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1192        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1193                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1194
1195        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1196                .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1197                .setIntent(settings);
1198
1199        return true;
1200    }
1201
1202    @Override
1203    public boolean onPrepareOptionsMenu(Menu menu) {
1204        super.onPrepareOptionsMenu(menu);
1205
1206        // If all apps is animating, don't show the menu, because we don't know
1207        // which one to show.
1208        if (mAllAppsGrid.isVisible() && !mAllAppsGrid.isOpaque()) {
1209            return false;
1210        }
1211
1212        // Only show the add and wallpaper options when we're not in all apps.
1213        boolean visible = !mAllAppsGrid.isOpaque();
1214        menu.setGroupVisible(MENU_GROUP_ADD, visible);
1215        menu.setGroupVisible(MENU_GROUP_WALLPAPER, visible);
1216
1217        // Disable add if the workspace is full.
1218        if (visible) {
1219            mMenuAddInfo = mWorkspace.findAllVacantCells(null);
1220            menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
1221        }
1222
1223        return true;
1224    }
1225
1226    // we need to initialize mAddItemCellInfo before adding something to the homescreen -- when
1227    // using the settings menu to add an item, something similar happens in showAddDialog
1228    public void prepareAddItemFromHomeCustomizationDrawer() {
1229        mMenuAddInfo = mWorkspace.findAllVacantCells(null);
1230        mAddItemCellInfo = mMenuAddInfo;
1231    }
1232
1233    @Override
1234    public boolean onOptionsItemSelected(MenuItem item) {
1235        switch (item.getItemId()) {
1236            case MENU_ADD:
1237                addItems();
1238                return true;
1239            case MENU_WALLPAPER_SETTINGS:
1240                startWallpaper();
1241                return true;
1242            case MENU_SEARCH:
1243                onSearchRequested();
1244                return true;
1245            case MENU_NOTIFICATIONS:
1246                showNotifications();
1247                return true;
1248        }
1249
1250        return super.onOptionsItemSelected(item);
1251    }
1252
1253    /**
1254     * Indicates that we want global search for this activity by setting the globalSearch
1255     * argument for {@link #startSearch} to true.
1256     */
1257
1258    @Override
1259    public boolean onSearchRequested() {
1260        startSearch(null, false, null, true);
1261        return true;
1262    }
1263
1264    public boolean isWorkspaceLocked() {
1265        return mWorkspaceLoading || mWaitingForResult;
1266    }
1267
1268    private void addItems() {
1269        closeAllApps(true);
1270        if (LauncherApplication.isScreenXLarge()) {
1271            // Animate the widget chooser up from the bottom of the screen
1272            if (!isCustomizationDrawerVisible()) {
1273                showCustomizationDrawer();
1274            }
1275        } else {
1276            showAddDialog(mMenuAddInfo);
1277        }
1278    }
1279
1280    void addAppWidgetFromDrop(ComponentName appWidgetProvider, CellLayout.CellInfo cellInfo) {
1281        mAddItemCellInfo = cellInfo;
1282        int appWidgetId = getAppWidgetHost().allocateAppWidgetId();
1283        AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, appWidgetProvider);
1284        addAppWidgetImpl(appWidgetId);
1285    }
1286
1287    void addAppWidgetFromPick(Intent data) {
1288        // TODO: catch bad widget exception when sent
1289        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1290        // TODO: Is this log message meaningful?
1291        if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras());
1292        addAppWidgetImpl(appWidgetId);
1293    }
1294
1295    void addAppWidgetImpl(int appWidgetId) {
1296        AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1297
1298        if (appWidget.configure != null) {
1299            // Launch over to configure widget, if needed
1300            Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1301            intent.setComponent(appWidget.configure);
1302            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1303
1304            startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET);
1305        } else {
1306            // Otherwise just add it
1307            completeAddAppWidget(appWidgetId, mAddItemCellInfo);
1308        }
1309    }
1310
1311    void processShortcut(Intent intent) {
1312        // Handle case where user selected "Applications"
1313        String applicationName = getResources().getString(R.string.group_applications);
1314        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1315
1316        if (applicationName != null && applicationName.equals(shortcutName)) {
1317            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1318            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1319
1320            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1321            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1322            startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
1323        } else {
1324            startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
1325        }
1326    }
1327
1328    void addLiveFolder(Intent intent) {
1329        // Handle case where user selected "Folder"
1330        String folderName = getResources().getString(R.string.group_folder);
1331        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1332
1333        if (folderName != null && folderName.equals(shortcutName)) {
1334            addFolder();
1335        } else {
1336            startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1337        }
1338    }
1339
1340    void addFolder() {
1341        UserFolderInfo folderInfo = new UserFolderInfo();
1342        folderInfo.title = getText(R.string.folder_name);
1343
1344        CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1345        cellInfo.screen = mWorkspace.getCurrentScreen();
1346        if (!findSingleSlot(cellInfo)) return;
1347
1348        // Update the model
1349        LauncherModel.addItemToDatabase(this, folderInfo,
1350                LauncherSettings.Favorites.CONTAINER_DESKTOP,
1351                mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1352        mFolders.put(folderInfo.id, folderInfo);
1353
1354        // Create the view
1355        FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1356                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1357        mWorkspace.addInCurrentScreen(newFolder,
1358                cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked());
1359    }
1360
1361    void removeFolder(FolderInfo folder) {
1362        mFolders.remove(folder.id);
1363    }
1364
1365    private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) {
1366        cellInfo.screen = mWorkspace.getCurrentScreen();
1367        if (!findSingleSlot(cellInfo)) return;
1368
1369        final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1370
1371        if (!mRestoring) {
1372            final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1373                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1374            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
1375                    isWorkspaceLocked());
1376        }
1377    }
1378
1379    static LiveFolderInfo addLiveFolder(Context context, Intent data,
1380            CellLayout.CellInfo cellInfo, boolean notify) {
1381
1382        Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1383        String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1384
1385        Drawable icon = null;
1386        Intent.ShortcutIconResource iconResource = null;
1387
1388        Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1389        if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1390            try {
1391                iconResource = (Intent.ShortcutIconResource) extra;
1392                final PackageManager packageManager = context.getPackageManager();
1393                Resources resources = packageManager.getResourcesForApplication(
1394                        iconResource.packageName);
1395                final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1396                icon = resources.getDrawable(id);
1397            } catch (Exception e) {
1398                Log.w(TAG, "Could not load live folder icon: " + extra);
1399            }
1400        }
1401
1402        if (icon == null) {
1403            icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1404        }
1405
1406        final LiveFolderInfo info = new LiveFolderInfo();
1407        info.icon = Utilities.createIconBitmap(icon, context);
1408        info.title = name;
1409        info.iconResource = iconResource;
1410        info.uri = data.getData();
1411        info.baseIntent = baseIntent;
1412        info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1413                LiveFolders.DISPLAY_MODE_GRID);
1414
1415        LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1416                cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1417        mFolders.put(info.id, info);
1418
1419        return info;
1420    }
1421
1422    private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1423        final int[] xy = new int[2];
1424        if (findSlot(cellInfo, xy, 1, 1)) {
1425            cellInfo.cellX = xy[0];
1426            cellInfo.cellY = xy[1];
1427            return true;
1428        }
1429        return false;
1430    }
1431
1432    private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1433        if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1434            boolean[] occupied = mSavedState != null ?
1435                    mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1436            cellInfo = mWorkspace.findAllVacantCells(occupied);
1437            if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1438                Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1439                return false;
1440            }
1441        }
1442        return true;
1443    }
1444
1445    private void showNotifications() {
1446        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1447        if (statusBar != null) {
1448            statusBar.expand();
1449        }
1450    }
1451
1452    private void startWallpaper() {
1453        closeAllApps(true);
1454        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1455        Intent chooser = Intent.createChooser(pickWallpaper,
1456                getText(R.string.chooser_wallpaper));
1457        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
1458        //       Removed in Eclair MR1
1459//        WallpaperManager wm = (WallpaperManager)
1460//                getSystemService(Context.WALLPAPER_SERVICE);
1461//        WallpaperInfo wi = wm.getWallpaperInfo();
1462//        if (wi != null && wi.getSettingsActivity() != null) {
1463//            LabeledIntent li = new LabeledIntent(getPackageName(),
1464//                    R.string.configure_wallpaper, 0);
1465//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1466//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1467//        }
1468        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
1469    }
1470
1471    /**
1472     * Registers various content observers. The current implementation registers
1473     * only a favorites observer to keep track of the favorites applications.
1474     */
1475    private void registerContentObservers() {
1476        ContentResolver resolver = getContentResolver();
1477        resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI,
1478                true, mWidgetObserver);
1479    }
1480
1481    @Override
1482    public boolean dispatchKeyEvent(KeyEvent event) {
1483        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1484            switch (event.getKeyCode()) {
1485                case KeyEvent.KEYCODE_HOME:
1486                    return true;
1487                case KeyEvent.KEYCODE_VOLUME_DOWN:
1488                    if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) {
1489                        dumpState();
1490                        return true;
1491                    }
1492                    break;
1493            }
1494        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1495            switch (event.getKeyCode()) {
1496                case KeyEvent.KEYCODE_HOME:
1497                    return true;
1498            }
1499        }
1500
1501        return super.dispatchKeyEvent(event);
1502    }
1503
1504    @Override
1505    public void onBackPressed() {
1506        if (isAllAppsVisible()) {
1507            closeAllApps(true);
1508        } else if (isCustomizationDrawerVisible()) {
1509            hideCustomizationDrawer();
1510        } else {
1511            closeFolder();
1512        }
1513        // Some launcher layouts don't have a previous and next view
1514        if (mPreviousView != null) {
1515            dismissPreview(mPreviousView);
1516            dismissPreview(mNextView);
1517        }
1518    }
1519
1520    private void closeFolder() {
1521        Folder folder = mWorkspace.getOpenFolder();
1522        if (folder != null) {
1523            closeFolder(folder);
1524        }
1525    }
1526
1527    void closeFolder(Folder folder) {
1528        folder.getInfo().opened = false;
1529        ViewGroup parent = (ViewGroup) folder.getParent();
1530        if (parent != null) {
1531            parent.removeView(folder);
1532            if (folder instanceof DropTarget) {
1533                // Live folders aren't DropTargets.
1534                mDragController.removeDropTarget((DropTarget)folder);
1535            }
1536        }
1537        folder.onClose();
1538    }
1539
1540    /**
1541     * Re-listen when widgets are reset.
1542     */
1543    private void onAppWidgetReset() {
1544        mAppWidgetHost.startListening();
1545    }
1546
1547    /**
1548     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1549     * leak the previous Home screen on orientation change.
1550     */
1551    private void unbindDesktopItems() {
1552        for (ItemInfo item: mDesktopItems) {
1553            item.unbind();
1554        }
1555    }
1556
1557    /**
1558     * Launches the intent referred by the clicked shortcut.
1559     *
1560     * @param v The view representing the clicked shortcut.
1561     */
1562    public void onClick(View v) {
1563        Object tag = v.getTag();
1564        if (tag instanceof ShortcutInfo) {
1565            // Open shortcut
1566            final Intent intent = ((ShortcutInfo) tag).intent;
1567            int[] pos = new int[2];
1568            v.getLocationOnScreen(pos);
1569            intent.setSourceBounds(new Rect(pos[0], pos[1],
1570                    pos[0] + v.getWidth(), pos[1] + v.getHeight()));
1571            startActivitySafely(intent, tag);
1572        } else if (tag instanceof FolderInfo) {
1573            handleFolderClick((FolderInfo) tag);
1574        } else if (v == mHandleView) {
1575            if (isAllAppsVisible()) {
1576                closeAllApps(true);
1577            } else {
1578                showAllApps(true);
1579            }
1580        }
1581    }
1582
1583    public boolean onTouch(View v, MotionEvent event) {
1584        // this is being forwarded from mWorkspace;
1585        // clicking anywhere on the workspace causes the drawer to slide down
1586        hideCustomizationDrawer();
1587        return false;
1588    }
1589
1590    /**
1591     * Event handler for the "plus" button that appears on the home screen, which
1592     * enters home screen customization mode.
1593     *
1594     * @param v The view that was clicked.
1595     */
1596    public void onClickAddButton(View v) {
1597        addItems();
1598    }
1599
1600    void startActivitySafely(Intent intent, Object tag) {
1601        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1602        try {
1603            startActivity(intent);
1604        } catch (ActivityNotFoundException e) {
1605            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1606            Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
1607        } catch (SecurityException e) {
1608            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1609            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1610                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1611                    "or use the exported attribute for this activity. "
1612                    + "tag="+ tag + " intent=" + intent, e);
1613        }
1614    }
1615
1616    void startActivityForResultSafely(Intent intent, int requestCode) {
1617        try {
1618            startActivityForResult(intent, requestCode);
1619        } catch (ActivityNotFoundException e) {
1620            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1621        } catch (SecurityException e) {
1622            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1623            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
1624                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1625                    "or use the exported attribute for this activity.", e);
1626        }
1627    }
1628
1629    private void handleFolderClick(FolderInfo folderInfo) {
1630        if (!folderInfo.opened) {
1631            // Close any open folder
1632            closeFolder();
1633            // Open the requested folder
1634            openFolder(folderInfo);
1635        } else {
1636            // Find the open folder...
1637            Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1638            int folderScreen;
1639            if (openFolder != null) {
1640                folderScreen = mWorkspace.getScreenForView(openFolder);
1641                // .. and close it
1642                closeFolder(openFolder);
1643                if (folderScreen != mWorkspace.getCurrentScreen()) {
1644                    // Close any folder open on the current screen
1645                    closeFolder();
1646                    // Pull the folder onto this screen
1647                    openFolder(folderInfo);
1648                }
1649            }
1650        }
1651    }
1652
1653    /**
1654     * Opens the user fodler described by the specified tag. The opening of the folder
1655     * is animated relative to the specified View. If the View is null, no animation
1656     * is played.
1657     *
1658     * @param folderInfo The FolderInfo describing the folder to open.
1659     */
1660    public void openFolder(FolderInfo folderInfo) {
1661        Folder openFolder;
1662
1663        if (folderInfo instanceof UserFolderInfo) {
1664            openFolder = UserFolder.fromXml(this);
1665        } else if (folderInfo instanceof LiveFolderInfo) {
1666            openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo);
1667        } else {
1668            return;
1669        }
1670
1671        openFolder.setDragController(mDragController);
1672        openFolder.setLauncher(this);
1673
1674        openFolder.bind(folderInfo);
1675        folderInfo.opened = true;
1676
1677        mWorkspace.addInFullScreen(openFolder, folderInfo.screen);
1678
1679        openFolder.onOpen();
1680    }
1681
1682    public boolean onLongClick(View v) {
1683        switch (v.getId()) {
1684            case R.id.previous_screen:
1685                if (!isAllAppsVisible()) {
1686                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1687                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1688                    showPreviews(v);
1689                }
1690                return true;
1691            case R.id.next_screen:
1692                if (!isAllAppsVisible()) {
1693                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1694                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1695                    showPreviews(v);
1696                }
1697                return true;
1698            case R.id.all_apps_button:
1699                if (!isAllAppsVisible()) {
1700                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1701                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1702                    showPreviews(v);
1703                }
1704                return true;
1705        }
1706
1707        if (isWorkspaceLocked()) {
1708            return false;
1709        }
1710
1711        if (!(v instanceof CellLayout)) {
1712            v = (View) v.getParent();
1713        }
1714
1715        CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1716
1717        // This happens when long clicking an item with the dpad/trackball
1718        if (cellInfo == null) {
1719            return true;
1720        }
1721
1722        if (mWorkspace.allowLongPress()) {
1723            if (cellInfo.cell == null) {
1724                if (cellInfo.valid) {
1725                    // User long pressed on empty space
1726                    mWorkspace.setAllowLongPress(false);
1727                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1728                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1729                    showAddDialog(cellInfo);
1730                }
1731            } else {
1732                if (!(cellInfo.cell instanceof Folder)) {
1733                    // User long pressed on an item
1734                    mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS,
1735                            HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
1736                    mWorkspace.startDrag(cellInfo);
1737                }
1738            }
1739        }
1740        return true;
1741    }
1742
1743    @SuppressWarnings({"unchecked"})
1744    private void dismissPreview(final View v) {
1745        final PopupWindow window = (PopupWindow) v.getTag();
1746        if (window != null) {
1747            window.setOnDismissListener(new PopupWindow.OnDismissListener() {
1748                public void onDismiss() {
1749                    ViewGroup group = (ViewGroup) v.getTag(R.id.workspace);
1750                    int count = group.getChildCount();
1751                    for (int i = 0; i < count; i++) {
1752                        ((ImageView) group.getChildAt(i)).setImageDrawable(null);
1753                    }
1754                    ArrayList<Bitmap> bitmaps = (ArrayList<Bitmap>) v.getTag(R.id.icon);
1755                    for (Bitmap bitmap : bitmaps) bitmap.recycle();
1756
1757                    v.setTag(R.id.workspace, null);
1758                    v.setTag(R.id.icon, null);
1759                    window.setOnDismissListener(null);
1760                }
1761            });
1762            window.dismiss();
1763        }
1764        v.setTag(null);
1765    }
1766
1767    private void showPreviews(View anchor) {
1768        showPreviews(anchor, 0, mWorkspace.getChildCount());
1769    }
1770
1771    private void showPreviews(final View anchor, int start, int end) {
1772        final Resources resources = getResources();
1773        final Workspace workspace = mWorkspace;
1774
1775        CellLayout cell = ((CellLayout) workspace.getChildAt(start));
1776
1777        float max = workspace.getChildCount();
1778
1779        final Rect r = new Rect();
1780        resources.getDrawable(R.drawable.preview_background).getPadding(r);
1781        int extraW = (int) ((r.left + r.right) * max);
1782        int extraH = r.top + r.bottom;
1783
1784        int aW = cell.getWidth() - extraW;
1785        float w = aW / max;
1786
1787        int width = cell.getWidth();
1788        int height = cell.getHeight();
1789        int x = cell.getLeftPadding();
1790        int y = cell.getTopPadding();
1791        width -= (x + cell.getRightPadding());
1792        height -= (y + cell.getBottomPadding());
1793
1794        float scale = w / width;
1795
1796        int count = end - start;
1797
1798        final float sWidth = width * scale;
1799        float sHeight = height * scale;
1800
1801        LinearLayout preview = new LinearLayout(this);
1802
1803        PreviewTouchHandler handler = new PreviewTouchHandler(anchor);
1804        ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count);
1805
1806        for (int i = start; i < end; i++) {
1807            ImageView image = new ImageView(this);
1808            cell = (CellLayout) workspace.getChildAt(i);
1809
1810            final Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight,
1811                    Bitmap.Config.ARGB_8888);
1812
1813            final Canvas c = new Canvas(bitmap);
1814            c.scale(scale, scale);
1815            c.translate(-cell.getLeftPadding(), -cell.getTopPadding());
1816            cell.dispatchDraw(c);
1817
1818            image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background));
1819            image.setImageBitmap(bitmap);
1820            image.setTag(i);
1821            image.setOnClickListener(handler);
1822            image.setOnFocusChangeListener(handler);
1823            image.setFocusable(true);
1824            if (i == mWorkspace.getCurrentScreen()) image.requestFocus();
1825
1826            preview.addView(image,
1827                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
1828
1829            bitmaps.add(bitmap);
1830        }
1831
1832        final PopupWindow p = new PopupWindow(this);
1833        p.setContentView(preview);
1834        p.setWidth((int) (sWidth * count + extraW));
1835        p.setHeight((int) (sHeight + extraH));
1836        p.setAnimationStyle(R.style.AnimationPreview);
1837        p.setOutsideTouchable(true);
1838        p.setFocusable(true);
1839        p.setBackgroundDrawable(new ColorDrawable(0));
1840        p.showAsDropDown(anchor, 0, 0);
1841
1842        p.setOnDismissListener(new PopupWindow.OnDismissListener() {
1843            public void onDismiss() {
1844                dismissPreview(anchor);
1845            }
1846        });
1847
1848        anchor.setTag(p);
1849        anchor.setTag(R.id.workspace, preview);
1850        anchor.setTag(R.id.icon, bitmaps);
1851    }
1852
1853    class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener {
1854        private final View mAnchor;
1855
1856        public PreviewTouchHandler(View anchor) {
1857            mAnchor = anchor;
1858        }
1859
1860        public void onClick(View v) {
1861            mWorkspace.snapToScreen((Integer) v.getTag());
1862            v.post(this);
1863        }
1864
1865        public void run() {
1866            dismissPreview(mAnchor);
1867        }
1868
1869        public void onFocusChange(View v, boolean hasFocus) {
1870            if (hasFocus) {
1871                mWorkspace.snapToScreen((Integer) v.getTag());
1872            }
1873        }
1874    }
1875
1876    Workspace getWorkspace() {
1877        return mWorkspace;
1878    }
1879
1880    @Override
1881    protected Dialog onCreateDialog(int id) {
1882        switch (id) {
1883            case DIALOG_CREATE_SHORTCUT:
1884                return new CreateShortcut().createDialog();
1885            case DIALOG_RENAME_FOLDER:
1886                return new RenameFolder().createDialog();
1887        }
1888
1889        return super.onCreateDialog(id);
1890    }
1891
1892    @Override
1893    protected void onPrepareDialog(int id, Dialog dialog) {
1894        switch (id) {
1895            case DIALOG_CREATE_SHORTCUT:
1896                break;
1897            case DIALOG_RENAME_FOLDER:
1898                if (mFolderInfo != null) {
1899                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1900                    final CharSequence text = mFolderInfo.title;
1901                    input.setText(text);
1902                    input.setSelection(0, text.length());
1903                }
1904                break;
1905        }
1906    }
1907
1908    void showRenameDialog(FolderInfo info) {
1909        mFolderInfo = info;
1910        mWaitingForResult = true;
1911        showDialog(DIALOG_RENAME_FOLDER);
1912    }
1913
1914    private void showAddDialog(CellLayout.CellInfo cellInfo) {
1915        mAddItemCellInfo = cellInfo;
1916        mWaitingForResult = true;
1917        showDialog(DIALOG_CREATE_SHORTCUT);
1918    }
1919
1920    private void pickShortcut() {
1921        // Insert extra item to handle picking application
1922        Bundle bundle = new Bundle();
1923
1924        ArrayList<String> shortcutNames = new ArrayList<String>();
1925        shortcutNames.add(getString(R.string.group_applications));
1926        bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1927
1928        ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
1929        shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1930                        R.drawable.ic_launcher_application));
1931        bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1932
1933        Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1934        pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
1935        pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_shortcut));
1936        pickIntent.putExtras(bundle);
1937
1938        startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1939    }
1940
1941    private class RenameFolder {
1942        private EditText mInput;
1943
1944        Dialog createDialog() {
1945            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1946            mInput = (EditText) layout.findViewById(R.id.folder_name);
1947
1948            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1949            builder.setIcon(0);
1950            builder.setTitle(getString(R.string.rename_folder_title));
1951            builder.setCancelable(true);
1952            builder.setOnCancelListener(new Dialog.OnCancelListener() {
1953                public void onCancel(DialogInterface dialog) {
1954                    cleanup();
1955                }
1956            });
1957            builder.setNegativeButton(getString(R.string.cancel_action),
1958                new Dialog.OnClickListener() {
1959                    public void onClick(DialogInterface dialog, int which) {
1960                        cleanup();
1961                    }
1962                }
1963            );
1964            builder.setPositiveButton(getString(R.string.rename_action),
1965                new Dialog.OnClickListener() {
1966                    public void onClick(DialogInterface dialog, int which) {
1967                        changeFolderName();
1968                    }
1969                }
1970            );
1971            builder.setView(layout);
1972
1973            final AlertDialog dialog = builder.create();
1974            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1975                public void onShow(DialogInterface dialog) {
1976                    mWaitingForResult = true;
1977                    mInput.requestFocus();
1978                    InputMethodManager inputManager = (InputMethodManager)
1979                            getSystemService(Context.INPUT_METHOD_SERVICE);
1980                    inputManager.showSoftInput(mInput, 0);
1981                }
1982            });
1983
1984            return dialog;
1985        }
1986
1987        private void changeFolderName() {
1988            final String name = mInput.getText().toString();
1989            if (!TextUtils.isEmpty(name)) {
1990                // Make sure we have the right folder info
1991                mFolderInfo = mFolders.get(mFolderInfo.id);
1992                mFolderInfo.title = name;
1993                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1994
1995                if (mWorkspaceLoading) {
1996                    lockAllApps();
1997                    mModel.startLoader(Launcher.this, false);
1998                } else {
1999                    final FolderIcon folderIcon = (FolderIcon)
2000                            mWorkspace.getViewForTag(mFolderInfo);
2001                    if (folderIcon != null) {
2002                        folderIcon.setText(name);
2003                        getWorkspace().requestLayout();
2004                    } else {
2005                        lockAllApps();
2006                        mWorkspaceLoading = true;
2007                        mModel.startLoader(Launcher.this, false);
2008                    }
2009                }
2010            }
2011            cleanup();
2012        }
2013
2014        private void cleanup() {
2015            dismissDialog(DIALOG_RENAME_FOLDER);
2016            mWaitingForResult = false;
2017            mFolderInfo = null;
2018        }
2019    }
2020
2021    // Now a part of LauncherModel.Callbacks. Used to reorder loading steps.
2022    public boolean isAllAppsVisible() {
2023        return (mAllAppsGrid != null) ? mAllAppsGrid.isVisible() : false;
2024    }
2025
2026    // AllAppsView.Watcher
2027    public void zoomed(float zoom) {
2028        if (zoom == 1.0f) {
2029            mWorkspace.setVisibility(View.GONE);
2030        }
2031    }
2032
2033    void showAllApps(boolean animated) {
2034        hideCustomizationDrawer();
2035
2036        if (LauncherApplication.isScreenXLarge() && animated) {
2037            // Not really a zoom -- this just makes the view visible
2038            mAllAppsGrid.zoom(1.0f, false);
2039            Animation anim = AnimationUtils.loadAnimation(this, R.anim.all_apps_zoom_in);
2040            ((View) mAllAppsGrid).startAnimation(anim);
2041        } else {
2042            mAllAppsGrid.zoom(1.0f, animated);
2043        }
2044
2045        ((View) mAllAppsGrid).setFocusable(true);
2046        ((View) mAllAppsGrid).requestFocus();
2047
2048        // TODO: fade these two too
2049        mDeleteZone.setVisibility(View.GONE);
2050    }
2051
2052    /**
2053     * Things to test when changing this code.
2054     *   - Home from workspace
2055     *          - from center screen
2056     *          - from other screens
2057     *   - Home from all apps
2058     *          - from center screen
2059     *          - from other screens
2060     *   - Back from all apps
2061     *          - from center screen
2062     *          - from other screens
2063     *   - Launch app from workspace and quit
2064     *          - with back
2065     *          - with home
2066     *   - Launch app from all apps and quit
2067     *          - with back
2068     *          - with home
2069     *   - Go to a screen that's not the default, then all
2070     *     apps, and launch and app, and go back
2071     *          - with back
2072     *          -with home
2073     *   - On workspace, long press power and go back
2074     *          - with back
2075     *          - with home
2076     *   - On all apps, long press power and go back
2077     *          - with back
2078     *          - with home
2079     *   - On workspace, power off
2080     *   - On all apps, power off
2081     *   - Launch an app and turn off the screen while in that app
2082     *          - Go back with home key
2083     *          - Go back with back key  TODO: make this not go to workspace
2084     *          - From all apps
2085     *          - From workspace
2086     *   - Enter and exit car mode (becuase it causes an extra configuration changed)
2087     *          - From all apps
2088     *          - From the center workspace
2089     *          - From another workspace
2090     */
2091    void closeAllApps(boolean animated) {
2092        if (mAllAppsGrid.isVisible()) {
2093            mWorkspace.setVisibility(View.VISIBLE);
2094            if (LauncherApplication.isScreenXLarge() && animated) {
2095                Animation anim = AnimationUtils.loadAnimation(this, R.anim.all_apps_zoom_out);
2096                anim.setAnimationListener(new AnimationListener() {
2097                    public void onAnimationStart(Animation animation) {}
2098                    public void onAnimationRepeat(Animation animation) {}
2099                    public void onAnimationEnd(Animation animation) {
2100                        mAllAppsGrid.zoom(0.0f, false);
2101                    }
2102                });
2103                ((View)mAllAppsGrid).startAnimation(anim);
2104            } else {
2105                mAllAppsGrid.zoom(0.0f, animated);
2106            }
2107            ((View)mAllAppsGrid).setFocusable(false);
2108            mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
2109        }
2110    }
2111
2112    void lockAllApps() {
2113        // TODO
2114    }
2115
2116    void unlockAllApps() {
2117        // TODO
2118    }
2119
2120    private boolean isCustomizationDrawerVisible() {
2121        return mHomeCustomizationDrawer != null && mHomeCustomizationDrawer.getVisibility() == View.VISIBLE;
2122    }
2123
2124    private void showCustomizationDrawer() {
2125        if (isAllAppsVisible()) {
2126            // TODO: Make a smoother transition here
2127            closeAllApps(false);
2128        }
2129        mHomeCustomizationDrawer.setVisibility(View.VISIBLE);
2130        mHomeCustomizationDrawer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.home_customization_drawer_slide_up));
2131    }
2132
2133    private void hideCustomizationDrawer() {
2134        if (isCustomizationDrawerVisible()) {
2135            Animation slideDownAnimation = AnimationUtils.loadAnimation(this, R.anim.home_customization_drawer_slide_down);
2136            slideDownAnimation.setAnimationListener(new Animation.AnimationListener() {
2137                public void onAnimationEnd(Animation animation) {
2138                    mHomeCustomizationDrawer.setVisibility(View.GONE);
2139                }
2140                public void onAnimationRepeat(Animation animation) {}
2141                public void onAnimationStart(Animation animation) {}
2142            });
2143            mHomeCustomizationDrawer.startAnimation(slideDownAnimation);
2144        }
2145    }
2146
2147    /**
2148     * Displays the shortcut creation dialog and launches, if necessary, the
2149     * appropriate activity.
2150     */
2151    private class CreateShortcut implements DialogInterface.OnClickListener,
2152            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
2153            DialogInterface.OnShowListener {
2154
2155        private AddAdapter mAdapter;
2156
2157        Dialog createDialog() {
2158            mAdapter = new AddAdapter(Launcher.this);
2159
2160            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
2161            builder.setTitle(getString(R.string.menu_item_add_item));
2162            builder.setAdapter(mAdapter, this);
2163
2164            builder.setInverseBackgroundForced(true);
2165
2166            AlertDialog dialog = builder.create();
2167            dialog.setOnCancelListener(this);
2168            dialog.setOnDismissListener(this);
2169            dialog.setOnShowListener(this);
2170
2171            return dialog;
2172        }
2173
2174        public void onCancel(DialogInterface dialog) {
2175            mWaitingForResult = false;
2176            cleanup();
2177        }
2178
2179        public void onDismiss(DialogInterface dialog) {
2180        }
2181
2182        private void cleanup() {
2183            try {
2184                dismissDialog(DIALOG_CREATE_SHORTCUT);
2185            } catch (Exception e) {
2186                // An exception is thrown if the dialog is not visible, which is fine
2187            }
2188        }
2189
2190        /**
2191         * Handle the action clicked in the "Add to home" dialog.
2192         */
2193        public void onClick(DialogInterface dialog, int which) {
2194            Resources res = getResources();
2195            cleanup();
2196
2197            switch (which) {
2198                case AddAdapter.ITEM_SHORTCUT: {
2199                    pickShortcut();
2200                    break;
2201                }
2202
2203                case AddAdapter.ITEM_APPWIDGET: {
2204                    int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
2205
2206                    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
2207                    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
2208                    // start the pick activity
2209                    startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
2210                    break;
2211                }
2212
2213                case AddAdapter.ITEM_LIVE_FOLDER: {
2214                    // Insert extra item to handle inserting folder
2215                    Bundle bundle = new Bundle();
2216
2217                    ArrayList<String> shortcutNames = new ArrayList<String>();
2218                    shortcutNames.add(res.getString(R.string.group_folder));
2219                    bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
2220
2221                    ArrayList<ShortcutIconResource> shortcutIcons =
2222                            new ArrayList<ShortcutIconResource>();
2223                    shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
2224                            R.drawable.ic_launcher_folder));
2225                    bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
2226
2227                    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
2228                    pickIntent.putExtra(Intent.EXTRA_INTENT,
2229                            new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
2230                    pickIntent.putExtra(Intent.EXTRA_TITLE,
2231                            getText(R.string.title_select_live_folder));
2232                    pickIntent.putExtras(bundle);
2233
2234                    startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
2235                    break;
2236                }
2237
2238                case AddAdapter.ITEM_WALLPAPER: {
2239                    startWallpaper();
2240                    break;
2241                }
2242            }
2243        }
2244
2245        public void onShow(DialogInterface dialog) {
2246            mWaitingForResult = true;
2247        }
2248    }
2249
2250    /**
2251     * Receives notifications when applications are added/removed.
2252     */
2253    private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2254        @Override
2255        public void onReceive(Context context, Intent intent) {
2256            closeSystemDialogs();
2257            String reason = intent.getStringExtra("reason");
2258            if (!"homekey".equals(reason)) {
2259                boolean animate = true;
2260                if (mPaused || "lock".equals(reason)) {
2261                    animate = false;
2262                }
2263                closeAllApps(animate);
2264            }
2265        }
2266    }
2267
2268    /**
2269     * Receives notifications whenever the appwidgets are reset.
2270     */
2271    private class AppWidgetResetObserver extends ContentObserver {
2272        public AppWidgetResetObserver() {
2273            super(new Handler());
2274        }
2275
2276        @Override
2277        public void onChange(boolean selfChange) {
2278            onAppWidgetReset();
2279        }
2280    }
2281
2282    /**
2283     * Implementation of the method from LauncherModel.Callbacks.
2284     */
2285    public int getCurrentWorkspaceScreen() {
2286        if (mWorkspace != null) {
2287            return mWorkspace.getCurrentScreen();
2288        } else {
2289            return SCREEN_COUNT / 2;
2290        }
2291    }
2292
2293    /**
2294     * Refreshes the shortcuts shown on the workspace.
2295     *
2296     * Implementation of the method from LauncherModel.Callbacks.
2297     */
2298    public void startBinding() {
2299        final Workspace workspace = mWorkspace;
2300        int count = workspace.getChildCount();
2301        for (int i = 0; i < count; i++) {
2302            // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate().
2303            ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
2304        }
2305
2306        if (DEBUG_USER_INTERFACE) {
2307            android.widget.Button finishButton = new android.widget.Button(this);
2308            finishButton.setText("Finish");
2309            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
2310
2311            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
2312                public void onClick(View v) {
2313                    finish();
2314                }
2315            });
2316        }
2317    }
2318
2319    /**
2320     * Bind the items start-end from the list.
2321     *
2322     * Implementation of the method from LauncherModel.Callbacks.
2323     */
2324    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
2325
2326        final Workspace workspace = mWorkspace;
2327
2328        for (int i=start; i<end; i++) {
2329            final ItemInfo item = shortcuts.get(i);
2330            mDesktopItems.add(item);
2331            switch (item.itemType) {
2332                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
2333                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
2334                    final View shortcut = createShortcut((ShortcutInfo)item);
2335                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
2336                            false);
2337                    break;
2338                case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
2339                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
2340                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
2341                            (UserFolderInfo) item);
2342                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
2343                            false);
2344                    break;
2345                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
2346                    final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
2347                            R.layout.live_folder_icon, this,
2348                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
2349                            (LiveFolderInfo) item);
2350                    workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
2351                            false);
2352                    break;
2353            }
2354        }
2355
2356        workspace.requestLayout();
2357    }
2358
2359    /**
2360     * Implementation of the method from LauncherModel.Callbacks.
2361     */
2362    public void bindFolders(HashMap<Long, FolderInfo> folders) {
2363        mFolders.clear();
2364        mFolders.putAll(folders);
2365    }
2366
2367    /**
2368     * Add the views for a widget to the workspace.
2369     *
2370     * Implementation of the method from LauncherModel.Callbacks.
2371     */
2372    public void bindAppWidget(LauncherAppWidgetInfo item) {
2373        final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0;
2374        if (DEBUG_WIDGETS) {
2375            Log.d(TAG, "bindAppWidget: " + item);
2376        }
2377        final Workspace workspace = mWorkspace;
2378
2379        final int appWidgetId = item.appWidgetId;
2380        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
2381        if (DEBUG_WIDGETS) {
2382            Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider);
2383        }
2384
2385        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
2386
2387        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
2388        item.hostView.setTag(item);
2389
2390        workspace.addInScreen(item.hostView, item.screen, item.cellX,
2391                item.cellY, item.spanX, item.spanY, false);
2392
2393        workspace.requestLayout();
2394
2395        mDesktopItems.add(item);
2396
2397        if (DEBUG_WIDGETS) {
2398            Log.d(TAG, "bound widget id="+item.appWidgetId+" in "
2399                    + (SystemClock.uptimeMillis()-start) + "ms");
2400        }
2401    }
2402
2403    /**
2404     * Callback saying that there aren't any more items to bind.
2405     *
2406     * Implementation of the method from LauncherModel.Callbacks.
2407     */
2408    public void finishBindingItems() {
2409        if (mSavedState != null) {
2410            if (!mWorkspace.hasFocus()) {
2411                mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
2412            }
2413
2414            final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
2415            if (userFolders != null) {
2416                for (long folderId : userFolders) {
2417                    final FolderInfo info = mFolders.get(folderId);
2418                    if (info != null) {
2419                        openFolder(info);
2420                    }
2421                }
2422                final Folder openFolder = mWorkspace.getOpenFolder();
2423                if (openFolder != null) {
2424                    openFolder.requestFocus();
2425                }
2426            }
2427
2428            mSavedState = null;
2429        }
2430
2431        if (mSavedInstanceState != null) {
2432            super.onRestoreInstanceState(mSavedInstanceState);
2433            mSavedInstanceState = null;
2434        }
2435
2436        mWorkspaceLoading = false;
2437    }
2438
2439    /**
2440     * Add the icons for all apps.
2441     *
2442     * Implementation of the method from LauncherModel.Callbacks.
2443     */
2444    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
2445        mAllAppsGrid.setApps(apps);
2446    }
2447
2448    /**
2449     * A package was installed.
2450     *
2451     * Implementation of the method from LauncherModel.Callbacks.
2452     */
2453    public void bindAppsAdded(ArrayList<ApplicationInfo> apps) {
2454        removeDialog(DIALOG_CREATE_SHORTCUT);
2455        mAllAppsGrid.addApps(apps);
2456    }
2457
2458    /**
2459     * A package was updated.
2460     *
2461     * Implementation of the method from LauncherModel.Callbacks.
2462     */
2463    public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) {
2464        removeDialog(DIALOG_CREATE_SHORTCUT);
2465        mWorkspace.updateShortcuts(apps);
2466        mAllAppsGrid.updateApps(apps);
2467    }
2468
2469    /**
2470     * A package was uninstalled.
2471     *
2472     * Implementation of the method from LauncherModel.Callbacks.
2473     */
2474    public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) {
2475        removeDialog(DIALOG_CREATE_SHORTCUT);
2476        if (permanent) {
2477            mWorkspace.removeItems(apps);
2478        }
2479        mAllAppsGrid.removeApps(apps);
2480    }
2481
2482    /**
2483     * Prints out out state for debugging.
2484     */
2485    public void dumpState() {
2486        Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this);
2487        Log.d(TAG, "mSavedState=" + mSavedState);
2488        Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading);
2489        Log.d(TAG, "mRestoring=" + mRestoring);
2490        Log.d(TAG, "mWaitingForResult=" + mWaitingForResult);
2491        Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState);
2492        Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size());
2493        Log.d(TAG, "mFolders.size=" + mFolders.size());
2494        mModel.dumpState();
2495        mAllAppsGrid.dumpState();
2496        Log.d(TAG, "END launcher2 dump state");
2497    }
2498}
2499