Launcher.java revision 12c14a8559375a457bd73fd16c6815df9c38cb06
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 android.app.Activity;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.ISearchManager;
23import android.app.SearchManager;
24import android.app.StatusBarManager;
25import android.app.WallpaperInfo;
26import android.app.WallpaperManager;
27import android.content.ActivityNotFoundException;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.Intent.ShortcutIconResource;
33import android.content.pm.ActivityInfo;
34import android.content.pm.LabeledIntent;
35import android.content.pm.PackageManager;
36import android.content.pm.PackageManager.NameNotFoundException;
37import android.content.res.Configuration;
38import android.content.res.Resources;
39import android.graphics.Bitmap;
40import android.graphics.drawable.Drawable;
41import android.graphics.drawable.TransitionDrawable;
42import android.os.Bundle;
43import android.os.Looper;
44import android.os.Message;
45import android.os.MessageQueue;
46import android.os.Parcelable;
47import android.os.RemoteException;
48import android.os.ServiceManager;
49import android.provider.LiveFolders;
50import android.text.Selection;
51import android.text.SpannableStringBuilder;
52import android.text.TextUtils;
53import android.text.method.TextKeyListener;
54import static android.util.Log.*;
55import android.util.Log;
56import android.view.Display;
57import android.view.KeyEvent;
58import android.view.LayoutInflater;
59import android.view.Menu;
60import android.view.MenuItem;
61import android.view.View;
62import android.view.ViewGroup;
63import android.view.WindowManager;
64import android.view.View.OnLongClickListener;
65import android.view.inputmethod.InputMethodManager;
66import android.widget.EditText;
67import android.widget.TextView;
68import android.widget.Toast;
69import android.appwidget.AppWidgetManager;
70import android.appwidget.AppWidgetProviderInfo;
71
72import java.lang.ref.WeakReference;
73import java.util.ArrayList;
74import java.util.HashMap;
75import java.util.LinkedList;
76import java.io.DataOutputStream;
77import java.io.FileNotFoundException;
78import java.io.IOException;
79import java.io.DataInputStream;
80
81/**
82 * Default launcher application.
83 */
84public final class Launcher extends Activity
85        implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks {
86    static final String LOG_TAG = "Launcher";
87    static final String TAG = LOG_TAG;
88    static final boolean LOGD = false;
89
90    static final boolean PROFILE_STARTUP = false;
91    static final boolean PROFILE_ROTATE = false;
92    static final boolean DEBUG_USER_INTERFACE = false;
93
94    private static final int WALLPAPER_SCREENS_SPAN = 2;
95
96    private static final int MENU_GROUP_ADD = 1;
97    private static final int MENU_ADD = Menu.FIRST + 1;
98    private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
99    private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
100    private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
101    private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
102
103    private static final int REQUEST_CREATE_SHORTCUT = 1;
104    private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
105    private static final int REQUEST_CREATE_APPWIDGET = 5;
106    private static final int REQUEST_PICK_APPLICATION = 6;
107    private static final int REQUEST_PICK_SHORTCUT = 7;
108    private static final int REQUEST_PICK_LIVE_FOLDER = 8;
109    private static final int REQUEST_PICK_APPWIDGET = 9;
110
111    static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
112
113    static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
114    static final String SEARCH_WIDGET = "search_widget";
115
116    static final int SCREEN_COUNT = 3;
117    static final int DEFAULT_SCREN = 1;
118    static final int NUMBER_CELLS_X = 4;
119    static final int NUMBER_CELLS_Y = 4;
120
121    static final int DIALOG_CREATE_SHORTCUT = 1;
122    static final int DIALOG_RENAME_FOLDER = 2;
123
124    private static final String PREFERENCES = "launcher.preferences";
125
126    // Type: int
127    private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
128    // Type: boolean
129    private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
130    // Type: long
131    private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
132    // Type: int
133    private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
134    // Type: int
135    private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
136    // Type: int
137    private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
138    // Type: int
139    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
140    // Type: int
141    private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
142    // Type: int
143    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
144    // Type: int
145    private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
146    // Type: int[]
147    private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
148    // Type: boolean
149    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
150    // Type: long
151    private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
152
153    static final int APPWIDGET_HOST_ID = 1024;
154
155    private static final Object sLock = new Object();
156    private static int sScreen = DEFAULT_SCREN;
157
158    private LayoutInflater mInflater;
159
160    private DragController mDragController;
161    private Workspace mWorkspace;
162
163    private AppWidgetManager mAppWidgetManager;
164    private LauncherAppWidgetHost mAppWidgetHost;
165
166    private CellLayout.CellInfo mAddItemCellInfo;
167    private CellLayout.CellInfo mMenuAddInfo;
168    private final int[] mCellCoordinates = new int[2];
169    private FolderInfo mFolderInfo;
170
171    private DeleteZone mDeleteZone;
172    private HandleView mHandleView;
173    private AllAppsView mAllAppsGrid;
174
175    private Bundle mSavedState;
176
177    private SpannableStringBuilder mDefaultKeySsb = null;
178
179    private boolean mIsNewIntent;
180
181    private boolean mWorkspaceLoading = true;
182
183    private boolean mRestoring;
184    private boolean mWaitingForResult;
185    private boolean mLocaleChanged;
186
187    private boolean mHomeDown;
188    private boolean mBackDown;
189
190    private Bundle mSavedInstanceState;
191
192    private LauncherModel mModel;
193
194    private ArrayList<ItemInfo> mDesktopItems = new ArrayList();
195    private static HashMap<Long, FolderInfo> mFolders = new HashMap();
196    private ArrayList<ApplicationInfo> mAllAppsList = new ArrayList();
197
198    @Override
199    protected void onCreate(Bundle savedInstanceState) {
200        super.onCreate(savedInstanceState);
201
202        mModel = ((LauncherApplication)getApplication()).setLauncher(this);
203        mInflater = getLayoutInflater();
204
205        mAppWidgetManager = AppWidgetManager.getInstance(this);
206
207        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
208        mAppWidgetHost.startListening();
209
210        if (PROFILE_STARTUP) {
211            android.os.Debug.startMethodTracing("/sdcard/launcher");
212        }
213
214        checkForLocaleChange();
215        setWallpaperDimension();
216
217        setContentView(R.layout.launcher);
218        setupViews();
219
220        lockAllApps();
221
222        mSavedState = savedInstanceState;
223        restoreState(mSavedState);
224
225        if (PROFILE_STARTUP) {
226            android.os.Debug.stopMethodTracing();
227        }
228
229        if (!mRestoring) {
230            mModel.startLoader(this, true);
231        }
232
233        // For handling default keys
234        mDefaultKeySsb = new SpannableStringBuilder();
235        Selection.setSelection(mDefaultKeySsb, 0);
236    }
237
238    private void checkForLocaleChange() {
239        final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
240        readConfiguration(this, localeConfiguration);
241
242        final Configuration configuration = getResources().getConfiguration();
243
244        final String previousLocale = localeConfiguration.locale;
245        final String locale = configuration.locale.toString();
246
247        final int previousMcc = localeConfiguration.mcc;
248        final int mcc = configuration.mcc;
249
250        final int previousMnc = localeConfiguration.mnc;
251        final int mnc = configuration.mnc;
252
253        mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
254
255        if (mLocaleChanged) {
256            localeConfiguration.locale = locale;
257            localeConfiguration.mcc = mcc;
258            localeConfiguration.mnc = mnc;
259
260            writeConfiguration(this, localeConfiguration);
261            AppInfoCache.flush();
262        }
263    }
264
265    private static class LocaleConfiguration {
266        public String locale;
267        public int mcc = -1;
268        public int mnc = -1;
269    }
270
271    private static void readConfiguration(Context context, LocaleConfiguration configuration) {
272        DataInputStream in = null;
273        try {
274            in = new DataInputStream(context.openFileInput(PREFERENCES));
275            configuration.locale = in.readUTF();
276            configuration.mcc = in.readInt();
277            configuration.mnc = in.readInt();
278        } catch (FileNotFoundException e) {
279            // Ignore
280        } catch (IOException e) {
281            // Ignore
282        } finally {
283            if (in != null) {
284                try {
285                    in.close();
286                } catch (IOException e) {
287                    // Ignore
288                }
289            }
290        }
291    }
292
293    private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
294        DataOutputStream out = null;
295        try {
296            out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
297            out.writeUTF(configuration.locale);
298            out.writeInt(configuration.mcc);
299            out.writeInt(configuration.mnc);
300            out.flush();
301        } catch (FileNotFoundException e) {
302            // Ignore
303        } catch (IOException e) {
304            //noinspection ResultOfMethodCallIgnored
305            context.getFileStreamPath(PREFERENCES).delete();
306        } finally {
307            if (out != null) {
308                try {
309                    out.close();
310                } catch (IOException e) {
311                    // Ignore
312                }
313            }
314        }
315    }
316
317    static int getScreen() {
318        synchronized (sLock) {
319            return sScreen;
320        }
321    }
322
323    static void setScreen(int screen) {
324        synchronized (sLock) {
325            sScreen = screen;
326        }
327    }
328
329    private void setWallpaperDimension() {
330        WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
331
332        Display display = getWindowManager().getDefaultDisplay();
333        boolean isPortrait = display.getWidth() < display.getHeight();
334
335        final int width = isPortrait ? display.getWidth() : display.getHeight();
336        final int height = isPortrait ? display.getHeight() : display.getWidth();
337        wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);
338    }
339
340    @Override
341    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
342        mWaitingForResult = false;
343
344        // The pattern used here is that a user PICKs a specific application,
345        // which, depending on the target, might need to CREATE the actual target.
346
347        // For example, the user would PICK_SHORTCUT for "Music playlist", and we
348        // launch over to the Music app to actually CREATE_SHORTCUT.
349
350        if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
351            switch (requestCode) {
352                case REQUEST_PICK_APPLICATION:
353                    completeAddApplication(this, data, mAddItemCellInfo);
354                    break;
355                case REQUEST_PICK_SHORTCUT:
356                    processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT);
357                    break;
358                case REQUEST_CREATE_SHORTCUT:
359                    completeAddShortcut(data, mAddItemCellInfo);
360                    break;
361                case REQUEST_PICK_LIVE_FOLDER:
362                    addLiveFolder(data);
363                    break;
364                case REQUEST_CREATE_LIVE_FOLDER:
365                    completeAddLiveFolder(data, mAddItemCellInfo);
366                    break;
367                case REQUEST_PICK_APPWIDGET:
368                    addAppWidget(data);
369                    break;
370                case REQUEST_CREATE_APPWIDGET:
371                    completeAddAppWidget(data, mAddItemCellInfo);
372                    break;
373            }
374        } else if (requestCode == REQUEST_PICK_APPWIDGET &&
375                resultCode == RESULT_CANCELED && data != null) {
376            // Clean up the appWidgetId if we canceled
377            int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
378            if (appWidgetId != -1) {
379                mAppWidgetHost.deleteAppWidgetId(appWidgetId);
380            }
381        }
382    }
383
384    @Override
385    protected void onResume() {
386        super.onResume();
387
388        if (mRestoring) {
389            mWorkspaceLoading = true;
390            mModel.startLoader(this, true);
391            mRestoring = false;
392        }
393
394        // If this was a new intent (i.e., the mIsNewIntent flag got set to true by
395        // onNewIntent), then close the search dialog if needed, because it probably
396        // came from the user pressing 'home' (rather than, for example, pressing 'back').
397        if (mIsNewIntent) {
398            // Post to a handler so that this happens after the search dialog tries to open
399            // itself again.
400            mWorkspace.post(new Runnable() {
401                public void run() {
402                    ISearchManager searchManagerService = ISearchManager.Stub.asInterface(
403                            ServiceManager.getService(Context.SEARCH_SERVICE));
404                    try {
405                        searchManagerService.stopSearch();
406                    } catch (RemoteException e) {
407                        e(LOG_TAG, "error stopping search", e);
408                    }
409                }
410            });
411        }
412
413        mIsNewIntent = false;
414    }
415
416    @Override
417    protected void onPause() {
418        super.onPause();
419        closeAllApps(false);
420    }
421
422    @Override
423    public Object onRetainNonConfigurationInstance() {
424        // Flag the loader to stop early before switching
425        mModel.stopLoader();
426
427        if (PROFILE_ROTATE) {
428            android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
429        }
430        return null;
431    }
432
433    private boolean acceptFilter() {
434        final InputMethodManager inputManager = (InputMethodManager)
435                getSystemService(Context.INPUT_METHOD_SERVICE);
436        return !inputManager.isFullscreenMode();
437    }
438
439    @Override
440    public boolean onKeyDown(int keyCode, KeyEvent event) {
441        boolean handled = super.onKeyDown(keyCode, event);
442        if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
443            boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
444                    keyCode, event);
445            if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
446                // something usable has been typed - start a search
447                // the typed text will be retrieved and cleared by
448                // showSearchDialog()
449                // If there are multiple keystrokes before the search dialog takes focus,
450                // onSearchRequested() will be called for every keystroke,
451                // but it is idempotent, so it's fine.
452                return onSearchRequested();
453            }
454        }
455
456        return handled;
457    }
458
459    private String getTypedText() {
460        return mDefaultKeySsb.toString();
461    }
462
463    private void clearTypedText() {
464        mDefaultKeySsb.clear();
465        mDefaultKeySsb.clearSpans();
466        Selection.setSelection(mDefaultKeySsb, 0);
467    }
468
469    /**
470     * Restores the previous state, if it exists.
471     *
472     * @param savedState The previous state.
473     */
474    private void restoreState(Bundle savedState) {
475        if (savedState == null) {
476            return;
477        }
478
479        final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
480        if (currentScreen > -1) {
481            mWorkspace.setCurrentScreen(currentScreen);
482        }
483
484        final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
485        if (addScreen > -1) {
486            mAddItemCellInfo = new CellLayout.CellInfo();
487            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
488            addItemCellInfo.valid = true;
489            addItemCellInfo.screen = addScreen;
490            addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
491            addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
492            addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
493            addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
494            addItemCellInfo.findVacantCellsFromOccupied(
495                    savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
496                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
497                    savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
498            mRestoring = true;
499        }
500
501        boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
502        if (renameFolder) {
503            long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
504            mFolderInfo = mModel.getFolderById(this, mFolders, id);
505            mRestoring = true;
506        }
507    }
508
509    /**
510     * Finds all the views we need and configure them properly.
511     */
512    private void setupViews() {
513        mDragController = new DragController(this);
514        DragController dragController = mDragController;
515
516        DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer);
517        dragLayer.setDragController(dragController);
518
519        mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view);
520        mAllAppsGrid.setLauncher(this);
521        mAllAppsGrid.setDragController(dragController);
522        mAllAppsGrid.setWillNotDraw(false); // We don't want a hole punched in our window.
523
524        mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
525        final Workspace workspace = mWorkspace;
526
527        DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
528        mDeleteZone = deleteZone;
529
530        mHandleView = (HandleView) findViewById(R.id.all_apps_button);
531        mHandleView.setLauncher(this);
532        mHandleView.setOnClickListener(this);
533        /* TODO
534        TransitionDrawable handleIcon = (TransitionDrawable) mHandleView.getDrawable();
535        handleIocon.setCrossFadeEnabled(true);
536        */
537
538        workspace.setOnLongClickListener(this);
539        workspace.setDragController(dragController);
540        workspace.setLauncher(this);
541
542        deleteZone.setLauncher(this);
543        deleteZone.setDragController(dragController);
544        deleteZone.setHandle(mHandleView);
545
546        dragController.setDragScoller(workspace);
547        dragController.setDragListener(deleteZone);
548        dragController.setScrollView(dragLayer);
549
550        // The order here is bottom to top.
551        dragController.addDropTarget(workspace);
552        dragController.addDropTarget(deleteZone);
553    }
554
555    /**
556     * Creates a view representing a shortcut.
557     *
558     * @param info The data structure describing the shortcut.
559     *
560     * @return A View inflated from R.layout.application.
561     */
562    View createShortcut(ApplicationInfo info) {
563        return createShortcut(R.layout.application,
564                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
565    }
566
567    /**
568     * Creates a view representing a shortcut inflated from the specified resource.
569     *
570     * @param layoutResId The id of the XML layout used to create the shortcut.
571     * @param parent The group the shortcut belongs to.
572     * @param info The data structure describing the shortcut.
573     *
574     * @return A View inflated from layoutResId.
575     */
576    View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
577        TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
578
579        if (info.icon == null) {
580            info.icon = AppInfoCache.getIconDrawable(getPackageManager(), info);
581        }
582        if (!info.filtered) {
583            info.icon = Utilities.createIconThumbnail(info.icon, this);
584            info.filtered = true;
585        }
586
587        favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
588        favorite.setText(info.title);
589        favorite.setTag(info);
590        favorite.setOnClickListener(this);
591
592        return favorite;
593    }
594
595    /**
596     * Add an application shortcut to the workspace.
597     *
598     * @param data The intent describing the application.
599     * @param cellInfo The position on screen where to create the shortcut.
600     */
601    void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) {
602        cellInfo.screen = mWorkspace.getCurrentScreen();
603        if (!findSingleSlot(cellInfo)) return;
604
605        final ApplicationInfo info = infoFromApplicationIntent(context, data);
606        if (info != null) {
607            mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked());
608        }
609    }
610
611    private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) {
612        ComponentName component = data.getComponent();
613        PackageManager packageManager = context.getPackageManager();
614        ActivityInfo activityInfo = null;
615        try {
616            activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
617        } catch (NameNotFoundException e) {
618            e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
619        }
620
621        if (activityInfo != null) {
622            ApplicationInfo itemInfo = new ApplicationInfo();
623
624            itemInfo.title = activityInfo.loadLabel(packageManager);
625            if (itemInfo.title == null) {
626                itemInfo.title = activityInfo.name;
627            }
628
629            itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
630                    Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
631            itemInfo.icon = activityInfo.loadIcon(packageManager);
632            itemInfo.container = ItemInfo.NO_ID;
633
634            return itemInfo;
635        }
636
637        return null;
638    }
639
640    /**
641     * Add a shortcut to the workspace.
642     *
643     * @param data The intent describing the shortcut.
644     * @param cellInfo The position on screen where to create the shortcut.
645     */
646    private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) {
647        cellInfo.screen = mWorkspace.getCurrentScreen();
648        if (!findSingleSlot(cellInfo)) return;
649
650        final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
651
652        if (!mRestoring) {
653            final View view = createShortcut(info);
654            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
655                    isWorkspaceLocked());
656        }
657    }
658
659
660    /**
661     * Add a widget to the workspace.
662     *
663     * @param data The intent describing the appWidgetId.
664     * @param cellInfo The position on screen where to create the widget.
665     */
666    private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) {
667        Bundle extras = data.getExtras();
668        int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
669
670        d(LOG_TAG, "dumping extras content="+extras.toString());
671
672        AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
673
674        // Calculate the grid spans needed to fit this widget
675        CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
676        int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
677
678        // Try finding open space on Launcher screen
679        final int[] xy = mCellCoordinates;
680        if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
681
682        // Build Launcher-specific widget info and save to database
683        LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
684        launcherInfo.spanX = spans[0];
685        launcherInfo.spanY = spans[1];
686
687        LauncherModel.addItemToDatabase(this, launcherInfo,
688                LauncherSettings.Favorites.CONTAINER_DESKTOP,
689                mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
690
691        if (!mRestoring) {
692            mDesktopItems.add(launcherInfo);
693
694            // Perform actual inflation because we're live
695            launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
696
697            launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
698            launcherInfo.hostView.setTag(launcherInfo);
699
700            mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
701                    launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked());
702        }
703    }
704
705    public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) {
706        mDesktopItems.remove(launcherInfo);
707        launcherInfo.hostView = null;
708    }
709
710    public LauncherAppWidgetHost getAppWidgetHost() {
711        return mAppWidgetHost;
712    }
713
714    static ApplicationInfo addShortcut(Context context, Intent data,
715            CellLayout.CellInfo cellInfo, boolean notify) {
716
717        final ApplicationInfo info = infoFromShortcutIntent(context, data);
718        LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
719                cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
720
721        return info;
722    }
723
724    private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) {
725        Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
726        String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
727        Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
728
729        Drawable icon = null;
730        boolean filtered = false;
731        boolean customIcon = false;
732        ShortcutIconResource iconResource = null;
733
734        if (bitmap != null) {
735            icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
736            filtered = true;
737            customIcon = true;
738        } else {
739            Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
740            if (extra != null && extra instanceof ShortcutIconResource) {
741                try {
742                    iconResource = (ShortcutIconResource) extra;
743                    final PackageManager packageManager = context.getPackageManager();
744                    Resources resources = packageManager.getResourcesForApplication(
745                            iconResource.packageName);
746                    final int id = resources.getIdentifier(iconResource.resourceName, null, null);
747                    icon = resources.getDrawable(id);
748                } catch (Exception e) {
749                    w(LOG_TAG, "Could not load shortcut icon: " + extra);
750                }
751            }
752        }
753
754        if (icon == null) {
755            icon = context.getPackageManager().getDefaultActivityIcon();
756        }
757
758        final ApplicationInfo info = new ApplicationInfo();
759        info.icon = icon;
760        info.filtered = filtered;
761        info.title = name;
762        info.intent = intent;
763        info.customIcon = customIcon;
764        info.iconResource = iconResource;
765
766        return info;
767    }
768
769    @Override
770    protected void onNewIntent(Intent intent) {
771        super.onNewIntent(intent);
772
773        // Close the menu
774        if (Intent.ACTION_MAIN.equals(intent.getAction())) {
775            getWindow().closeAllPanels();
776
777            // Set this flag so that onResume knows to close the search dialog if it's open,
778            // because this was a new intent (thus a press of 'home' or some such) rather than
779            // for example onResume being called when the user pressed the 'back' button.
780            mIsNewIntent = true;
781
782            try {
783                dismissDialog(DIALOG_CREATE_SHORTCUT);
784                // Unlock the workspace if the dialog was showing
785            } catch (Exception e) {
786                // An exception is thrown if the dialog is not visible, which is fine
787            }
788
789            try {
790                dismissDialog(DIALOG_RENAME_FOLDER);
791                // Unlock the workspace if the dialog was showing
792            } catch (Exception e) {
793                // An exception is thrown if the dialog is not visible, which is fine
794            }
795
796            if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
797                    Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
798
799                if (!mWorkspace.isDefaultScreenShowing()) {
800                    mWorkspace.moveToDefaultScreen();
801                }
802
803                closeAllApps(true);
804
805                final View v = getWindow().peekDecorView();
806                if (v != null && v.getWindowToken() != null) {
807                    InputMethodManager imm = (InputMethodManager)getSystemService(
808                            INPUT_METHOD_SERVICE);
809                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
810                }
811            } else {
812                closeAllApps(false);
813            }
814        }
815    }
816
817    @Override
818    protected void onRestoreInstanceState(Bundle savedInstanceState) {
819        // Do not call super here
820        mSavedInstanceState = savedInstanceState;
821    }
822
823    @Override
824    protected void onSaveInstanceState(Bundle outState) {
825        outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
826
827        final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
828        if (folders.size() > 0) {
829            final int count = folders.size();
830            long[] ids = new long[count];
831            for (int i = 0; i < count; i++) {
832                final FolderInfo info = folders.get(i).getInfo();
833                ids[i] = info.id;
834            }
835            outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
836        } else {
837            super.onSaveInstanceState(outState);
838        }
839
840        final boolean isConfigurationChange = getChangingConfigurations() != 0;
841
842        // When the drawer is opened and we are saving the state because of a
843        // configuration change
844        // TODO should not do this if the drawer is currently closing.
845        if (isAllAppsVisible() && isConfigurationChange) {
846            outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
847        }
848
849        if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
850            final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
851            final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
852
853            outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
854            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
855            outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
856            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
857            outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
858            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
859            outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
860            outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
861                   layout.getOccupiedCells());
862        }
863
864        if (mFolderInfo != null && mWaitingForResult) {
865            outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
866            outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
867        }
868    }
869
870    @Override
871    public void onDestroy() {
872        super.onDestroy();
873
874        try {
875            mAppWidgetHost.stopListening();
876        } catch (NullPointerException ex) {
877            w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
878        }
879
880        TextKeyListener.getInstance().release();
881
882        mModel.stopLoader();
883
884        unbindDesktopItems();
885        AppInfoCache.unbindDrawables();
886    }
887
888    @Override
889    public void startActivityForResult(Intent intent, int requestCode) {
890        if (requestCode >= 0) mWaitingForResult = true;
891        super.startActivityForResult(intent, requestCode);
892    }
893
894    @Override
895    public void startSearch(String initialQuery, boolean selectInitialQuery,
896            Bundle appSearchData, boolean globalSearch) {
897
898        closeAllApps(true);
899
900        // Slide the search widget to the top, if it's on the current screen,
901        // otherwise show the search dialog immediately.
902        Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
903        if (searchWidget == null) {
904            showSearchDialog(initialQuery, selectInitialQuery, appSearchData, globalSearch);
905        } else {
906            searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
907            // show the currently typed text in the search widget while sliding
908            searchWidget.setQuery(getTypedText());
909        }
910    }
911
912    /**
913     * Show the search dialog immediately, without changing the search widget.
914     *
915     * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean)
916     */
917    void showSearchDialog(String initialQuery, boolean selectInitialQuery,
918            Bundle appSearchData, boolean globalSearch) {
919
920        if (initialQuery == null) {
921            // Use any text typed in the launcher as the initial query
922            initialQuery = getTypedText();
923            clearTypedText();
924        }
925        if (appSearchData == null) {
926            appSearchData = new Bundle();
927            appSearchData.putString(SearchManager.SOURCE, "launcher-search");
928        }
929
930        final SearchManager searchManager =
931                (SearchManager) getSystemService(Context.SEARCH_SERVICE);
932
933        final Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
934        if (searchWidget != null) {
935            // This gets called when the user leaves the search dialog to go back to
936            // the Launcher.
937            searchManager.setOnCancelListener(new SearchManager.OnCancelListener() {
938                public void onCancel() {
939                    searchManager.setOnCancelListener(null);
940                    stopSearch();
941                }
942            });
943        }
944
945        searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
946            appSearchData, globalSearch);
947    }
948
949    /**
950     * Cancel search dialog if it is open.
951     */
952    void stopSearch() {
953        // Close search dialog
954        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
955        searchManager.stopSearch();
956        // Restore search widget to its normal position
957        Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
958        if (searchWidget != null) {
959            searchWidget.stopSearch(false);
960        }
961    }
962
963    @Override
964    public boolean onCreateOptionsMenu(Menu menu) {
965        if (isWorkspaceLocked()) {
966            return false;
967        }
968
969        super.onCreateOptionsMenu(menu);
970        menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
971                .setIcon(android.R.drawable.ic_menu_add)
972                .setAlphabeticShortcut('A');
973        menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
974                 .setIcon(android.R.drawable.ic_menu_gallery)
975                 .setAlphabeticShortcut('W');
976        menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
977                .setIcon(android.R.drawable.ic_search_category_default)
978                .setAlphabeticShortcut(SearchManager.MENU_KEY);
979        menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
980                .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
981                .setAlphabeticShortcut('N');
982
983        final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
984        settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
985                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
986
987        menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
988                .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
989                .setIntent(settings);
990
991        return true;
992    }
993
994    @Override
995    public boolean onPrepareOptionsMenu(Menu menu) {
996        super.onPrepareOptionsMenu(menu);
997
998        mMenuAddInfo = mWorkspace.findAllVacantCells(null);
999        menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
1000
1001        return true;
1002    }
1003
1004    @Override
1005    public boolean onOptionsItemSelected(MenuItem item) {
1006        switch (item.getItemId()) {
1007            case MENU_ADD:
1008                addItems();
1009                return true;
1010            case MENU_WALLPAPER_SETTINGS:
1011                startWallpaper();
1012                return true;
1013            case MENU_SEARCH:
1014                onSearchRequested();
1015                return true;
1016            case MENU_NOTIFICATIONS:
1017                showNotifications();
1018                return true;
1019        }
1020
1021        return super.onOptionsItemSelected(item);
1022    }
1023
1024    /**
1025     * Indicates that we want global search for this activity by setting the globalSearch
1026     * argument for {@link #startSearch} to true.
1027     */
1028
1029    @Override
1030    public boolean onSearchRequested() {
1031        startSearch(null, false, null, true);
1032        return true;
1033    }
1034
1035    public boolean isWorkspaceLocked() {
1036        return mWorkspaceLoading || mWaitingForResult;
1037    }
1038
1039    private void addItems() {
1040        showAddDialog(mMenuAddInfo);
1041    }
1042
1043    void addAppWidget(Intent data) {
1044        // TODO: catch bad widget exception when sent
1045        int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1046
1047        String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
1048        if (SEARCH_WIDGET.equals(customWidget)) {
1049            // We don't need this any more, since this isn't a real app widget.
1050            mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1051            // add the search widget
1052            addSearch();
1053        } else {
1054            AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1055
1056            if (appWidget.configure != null) {
1057                // Launch over to configure widget, if needed
1058                Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1059                intent.setComponent(appWidget.configure);
1060                intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1061
1062                startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
1063            } else {
1064                // Otherwise just add it
1065                onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
1066            }
1067        }
1068    }
1069
1070    void addSearch() {
1071        final Widget info = Widget.makeSearch();
1072        final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1073
1074        final int[] xy = mCellCoordinates;
1075        final int spanX = info.spanX;
1076        final int spanY = info.spanY;
1077
1078        if (!findSlot(cellInfo, xy, spanX, spanY)) return;
1079
1080        LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1081        mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
1082
1083        final View view = mInflater.inflate(info.layoutResource, null);
1084        view.setTag(info);
1085        Search search = (Search) view.findViewById(R.id.widget_search);
1086        search.setLauncher(this);
1087
1088        mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
1089    }
1090
1091    void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) {
1092        // Handle case where user selected "Applications"
1093        String applicationName = getResources().getString(R.string.group_applications);
1094        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1095
1096        if (applicationName != null && applicationName.equals(shortcutName)) {
1097            Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1098            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1099
1100            Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1101            pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1102            startActivityForResult(pickIntent, requestCodeApplication);
1103        } else {
1104            startActivityForResult(intent, requestCodeShortcut);
1105        }
1106    }
1107
1108    void addLiveFolder(Intent intent) {
1109        // Handle case where user selected "Folder"
1110        String folderName = getResources().getString(R.string.group_folder);
1111        String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1112
1113        if (folderName != null && folderName.equals(shortcutName)) {
1114            addFolder();
1115        } else {
1116            startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1117        }
1118    }
1119
1120    void addFolder() {
1121        UserFolderInfo folderInfo = new UserFolderInfo();
1122        folderInfo.title = getText(R.string.folder_name);
1123
1124        CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1125        cellInfo.screen = mWorkspace.getCurrentScreen();
1126        if (!findSingleSlot(cellInfo)) return;
1127
1128        // Update the model
1129        LauncherModel.addItemToDatabase(this, folderInfo,
1130                LauncherSettings.Favorites.CONTAINER_DESKTOP,
1131                mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1132        mFolders.put(folderInfo.id, folderInfo);
1133
1134        // Create the view
1135        FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1136                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1137        mWorkspace.addInCurrentScreen(newFolder,
1138                cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked());
1139    }
1140
1141    void removeFolder(FolderInfo folder) {
1142        mFolders.remove(folder.id);
1143    }
1144
1145    private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) {
1146        cellInfo.screen = mWorkspace.getCurrentScreen();
1147        if (!findSingleSlot(cellInfo)) return;
1148
1149        final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1150
1151        if (!mRestoring) {
1152            final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1153                (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1154            mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1,
1155                    isWorkspaceLocked());
1156        }
1157    }
1158
1159    static LiveFolderInfo addLiveFolder(Context context, Intent data,
1160            CellLayout.CellInfo cellInfo, boolean notify) {
1161
1162        Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1163        String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1164
1165        Drawable icon = null;
1166        boolean filtered = false;
1167        Intent.ShortcutIconResource iconResource = null;
1168
1169        Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1170        if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1171            try {
1172                iconResource = (Intent.ShortcutIconResource) extra;
1173                final PackageManager packageManager = context.getPackageManager();
1174                Resources resources = packageManager.getResourcesForApplication(
1175                        iconResource.packageName);
1176                final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1177                icon = resources.getDrawable(id);
1178            } catch (Exception e) {
1179                w(LOG_TAG, "Could not load live folder icon: " + extra);
1180            }
1181        }
1182
1183        if (icon == null) {
1184            icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1185        }
1186
1187        final LiveFolderInfo info = new LiveFolderInfo();
1188        info.icon = icon;
1189        info.filtered = filtered;
1190        info.title = name;
1191        info.iconResource = iconResource;
1192        info.uri = data.getData();
1193        info.baseIntent = baseIntent;
1194        info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1195                LiveFolders.DISPLAY_MODE_GRID);
1196
1197        LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1198                cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1199        mFolders.put(info.id, info);
1200
1201        return info;
1202    }
1203
1204    private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1205        final int[] xy = new int[2];
1206        if (findSlot(cellInfo, xy, 1, 1)) {
1207            cellInfo.cellX = xy[0];
1208            cellInfo.cellY = xy[1];
1209            return true;
1210        }
1211        return false;
1212    }
1213
1214    private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1215        if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1216            boolean[] occupied = mSavedState != null ?
1217                    mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1218            cellInfo = mWorkspace.findAllVacantCells(occupied);
1219            if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1220                Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1221                return false;
1222            }
1223        }
1224        return true;
1225    }
1226
1227    private void showNotifications() {
1228        final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1229        if (statusBar != null) {
1230            statusBar.expand();
1231        }
1232    }
1233
1234    private void startWallpaper() {
1235        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1236        Intent chooser = Intent.createChooser(pickWallpaper,
1237                getText(R.string.chooser_wallpaper));
1238        WallpaperManager wm = (WallpaperManager)
1239                getSystemService(Context.WALLPAPER_SERVICE);
1240        WallpaperInfo wi = wm.getWallpaperInfo();
1241        if (wi != null && wi.getSettingsActivity() != null) {
1242            LabeledIntent li = new LabeledIntent(getPackageName(),
1243                    R.string.configure_wallpaper, 0);
1244            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
1245            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
1246        }
1247        startActivity(chooser);
1248    }
1249
1250    @Override
1251    public void onWindowFocusChanged(boolean hasFocus) {
1252        super.onWindowFocusChanged(hasFocus);
1253        if (!hasFocus) {
1254            mBackDown = mHomeDown = false;
1255        }
1256    }
1257
1258    @Override
1259    public boolean dispatchKeyEvent(KeyEvent event) {
1260        if (event.getAction() == KeyEvent.ACTION_DOWN) {
1261            switch (event.getKeyCode()) {
1262                case KeyEvent.KEYCODE_BACK:
1263                    mBackDown = true;
1264                    return true;
1265                case KeyEvent.KEYCODE_HOME:
1266                    mHomeDown = true;
1267                    return true;
1268            }
1269        } else if (event.getAction() == KeyEvent.ACTION_UP) {
1270            switch (event.getKeyCode()) {
1271                case KeyEvent.KEYCODE_BACK:
1272                    if (!event.isCanceled()) {
1273                        mWorkspace.dispatchKeyEvent(event);
1274                        if (isAllAppsVisible()) {
1275                            closeAllApps(true);
1276                        } else {
1277                            closeFolder();
1278                        }
1279                    }
1280                    mBackDown = false;
1281                    return true;
1282                case KeyEvent.KEYCODE_HOME:
1283                    mHomeDown = false;
1284                    return true;
1285            }
1286        }
1287
1288        return super.dispatchKeyEvent(event);
1289    }
1290
1291    private void closeFolder() {
1292        Folder folder = mWorkspace.getOpenFolder();
1293        if (folder != null) {
1294            closeFolder(folder);
1295        }
1296    }
1297
1298    void closeFolder(Folder folder) {
1299        folder.getInfo().opened = false;
1300        ViewGroup parent = (ViewGroup) folder.getParent();
1301        if (parent != null) {
1302            parent.removeView(folder);
1303            // TODO: this line crashes.
1304            //mDragController.removeDropTarget((DropTarget)folder);
1305        }
1306        folder.onClose();
1307    }
1308
1309    /**
1310     * Go through the and disconnect any of the callbacks in the drawables and the views or we
1311     * leak the previous Home screen on orientation change.
1312     */
1313    private void unbindDesktopItems() {
1314        for (ItemInfo item: mDesktopItems) {
1315            item.unbind();
1316        }
1317    }
1318
1319    /**
1320     * Launches the intent referred by the clicked shortcut.
1321     *
1322     * @param v The view representing the clicked shortcut.
1323     */
1324    public void onClick(View v) {
1325        Object tag = v.getTag();
1326        if (tag instanceof ApplicationInfo) {
1327            // Open shortcut
1328            final Intent intent = ((ApplicationInfo) tag).intent;
1329            startActivitySafely(intent);
1330        } else if (tag instanceof FolderInfo) {
1331            handleFolderClick((FolderInfo) tag);
1332        } else if (v == mHandleView) {
1333            Log.d(TAG, "onClick");
1334            if (isAllAppsVisible()) {
1335                closeAllApps(true);
1336            } else {
1337                showAllApps();
1338            }
1339        }
1340    }
1341
1342    void startActivitySafely(Intent intent) {
1343        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1344        try {
1345            startActivity(intent);
1346        } catch (ActivityNotFoundException e) {
1347            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1348        } catch (SecurityException e) {
1349            Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1350            e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1351                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1352                    "or use the exported attribute for this activity.", e);
1353        }
1354    }
1355
1356    private void handleFolderClick(FolderInfo folderInfo) {
1357        if (!folderInfo.opened) {
1358            // Close any open folder
1359            closeFolder();
1360            // Open the requested folder
1361            openFolder(folderInfo);
1362        } else {
1363            // Find the open folder...
1364            Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1365            int folderScreen;
1366            if (openFolder != null) {
1367                folderScreen = mWorkspace.getScreenForView(openFolder);
1368                // .. and close it
1369                closeFolder(openFolder);
1370                if (folderScreen != mWorkspace.getCurrentScreen()) {
1371                    // Close any folder open on the current screen
1372                    closeFolder();
1373                    // Pull the folder onto this screen
1374                    openFolder(folderInfo);
1375                }
1376            }
1377        }
1378    }
1379
1380    /**
1381     * Opens the user fodler described by the specified tag. The opening of the folder
1382     * is animated relative to the specified View. If the View is null, no animation
1383     * is played.
1384     *
1385     * @param folderInfo The FolderInfo describing the folder to open.
1386     */
1387    private void openFolder(FolderInfo folderInfo) {
1388        Folder openFolder;
1389
1390        if (folderInfo instanceof UserFolderInfo) {
1391            openFolder = UserFolder.fromXml(this);
1392        } else if (folderInfo instanceof LiveFolderInfo) {
1393            openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo);
1394        } else {
1395            return;
1396        }
1397
1398        openFolder.setDragController(mDragController);
1399        openFolder.setLauncher(this);
1400
1401        openFolder.bind(folderInfo);
1402        folderInfo.opened = true;
1403
1404        mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1405        openFolder.onOpen();
1406    }
1407
1408    public boolean onLongClick(View v) {
1409        if (isWorkspaceLocked()) {
1410            return false;
1411        }
1412
1413        if (!(v instanceof CellLayout)) {
1414            v = (View) v.getParent();
1415        }
1416
1417        CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1418
1419        // This happens when long clicking an item with the dpad/trackball
1420        if (cellInfo == null) {
1421            return true;
1422        }
1423
1424        if (mWorkspace.allowLongPress()) {
1425            if (cellInfo.cell == null) {
1426                if (cellInfo.valid) {
1427                    // User long pressed on empty space
1428                    mWorkspace.setAllowLongPress(false);
1429                    showAddDialog(cellInfo);
1430                }
1431            } else {
1432                if (!(cellInfo.cell instanceof Folder)) {
1433                    // User long pressed on an item
1434                    mWorkspace.startDrag(cellInfo);
1435                }
1436            }
1437        }
1438        return true;
1439    }
1440
1441    View getDrawerHandle() {
1442        return mHandleView;
1443    }
1444
1445    Workspace getWorkspace() {
1446        return mWorkspace;
1447    }
1448
1449    /* TODO
1450    GridView getApplicationsGrid() {
1451        return mAllAppsGrid;
1452    }
1453    */
1454
1455    @Override
1456    protected Dialog onCreateDialog(int id) {
1457        switch (id) {
1458            case DIALOG_CREATE_SHORTCUT:
1459                return new CreateShortcut().createDialog();
1460            case DIALOG_RENAME_FOLDER:
1461                return new RenameFolder().createDialog();
1462        }
1463
1464        return super.onCreateDialog(id);
1465    }
1466
1467    @Override
1468    protected void onPrepareDialog(int id, Dialog dialog) {
1469        switch (id) {
1470            case DIALOG_CREATE_SHORTCUT:
1471                break;
1472            case DIALOG_RENAME_FOLDER:
1473                if (mFolderInfo != null) {
1474                    EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1475                    final CharSequence text = mFolderInfo.title;
1476                    input.setText(text);
1477                    input.setSelection(0, text.length());
1478                }
1479                break;
1480        }
1481    }
1482
1483    void showRenameDialog(FolderInfo info) {
1484        mFolderInfo = info;
1485        mWaitingForResult = true;
1486        showDialog(DIALOG_RENAME_FOLDER);
1487    }
1488
1489    private void showAddDialog(CellLayout.CellInfo cellInfo) {
1490        mAddItemCellInfo = cellInfo;
1491        mWaitingForResult = true;
1492        showDialog(DIALOG_CREATE_SHORTCUT);
1493    }
1494
1495    private void pickShortcut(int requestCode, int title) {
1496        Bundle bundle = new Bundle();
1497
1498        ArrayList<String> shortcutNames = new ArrayList<String>();
1499        shortcutNames.add(getString(R.string.group_applications));
1500        bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1501
1502        ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
1503        shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1504                        R.drawable.ic_launcher_application));
1505        bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1506
1507        Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1508        pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
1509        pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title));
1510        pickIntent.putExtras(bundle);
1511
1512        startActivityForResult(pickIntent, requestCode);
1513    }
1514
1515    private class RenameFolder {
1516        private EditText mInput;
1517
1518        Dialog createDialog() {
1519            mWaitingForResult = true;
1520            final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1521            mInput = (EditText) layout.findViewById(R.id.folder_name);
1522
1523            AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1524            builder.setIcon(0);
1525            builder.setTitle(getString(R.string.rename_folder_title));
1526            builder.setCancelable(true);
1527            builder.setOnCancelListener(new Dialog.OnCancelListener() {
1528                public void onCancel(DialogInterface dialog) {
1529                    cleanup();
1530                }
1531            });
1532            builder.setNegativeButton(getString(R.string.cancel_action),
1533                new Dialog.OnClickListener() {
1534                    public void onClick(DialogInterface dialog, int which) {
1535                        cleanup();
1536                    }
1537                }
1538            );
1539            builder.setPositiveButton(getString(R.string.rename_action),
1540                new Dialog.OnClickListener() {
1541                    public void onClick(DialogInterface dialog, int which) {
1542                        changeFolderName();
1543                    }
1544                }
1545            );
1546            builder.setView(layout);
1547
1548            final AlertDialog dialog = builder.create();
1549            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1550                public void onShow(DialogInterface dialog) {
1551                }
1552            });
1553
1554            return dialog;
1555        }
1556
1557        private void changeFolderName() {
1558            final String name = mInput.getText().toString();
1559            if (!TextUtils.isEmpty(name)) {
1560                // Make sure we have the right folder info
1561                mFolderInfo = mFolders.get(mFolderInfo.id);
1562                mFolderInfo.title = name;
1563                LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1564
1565                if (mWorkspaceLoading) {
1566                    lockAllApps();
1567                    mModel.setWorkspaceDirty();
1568                    mModel.startLoader(Launcher.this, false);
1569                } else {
1570                    final FolderIcon folderIcon = (FolderIcon)
1571                            mWorkspace.getViewForTag(mFolderInfo);
1572                    if (folderIcon != null) {
1573                        folderIcon.setText(name);
1574                        getWorkspace().requestLayout();
1575                    } else {
1576                        lockAllApps();
1577                        mModel.setWorkspaceDirty();
1578                        mWorkspaceLoading = true;
1579                        mModel.startLoader(Launcher.this, false);
1580                    }
1581                }
1582            }
1583            cleanup();
1584        }
1585
1586        private void cleanup() {
1587            dismissDialog(DIALOG_RENAME_FOLDER);
1588            mWaitingForResult = false;
1589            mFolderInfo = null;
1590        }
1591    }
1592
1593    boolean isAllAppsVisible() {
1594        return mAllAppsGrid.isVisible();
1595    }
1596
1597    void showAllApps() {
1598        mAllAppsGrid.zoom(1.0f);
1599        //mWorkspace.hide();
1600
1601        // TODO: fade these two too
1602        mDeleteZone.setVisibility(View.GONE);
1603        //mHandleView.setVisibility(View.GONE);
1604    }
1605
1606    void closeAllApps(boolean animated) {
1607        if (mAllAppsGrid.isVisible()) {
1608            mAllAppsGrid.zoom(0.0f);
1609            mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1610
1611            // TODO: fade these two too
1612            /*
1613            mDeleteZone.setVisibility(View.VISIBLE);
1614            mHandleView.setVisibility(View.VISIBLE);
1615            */
1616        }
1617    }
1618
1619    void lockAllApps() {
1620        // TODO
1621    }
1622
1623    void unlockAllApps() {
1624        // TODO
1625    }
1626
1627    /**
1628     * Displays the shortcut creation dialog and launches, if necessary, the
1629     * appropriate activity.
1630     */
1631    private class CreateShortcut implements DialogInterface.OnClickListener,
1632            DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
1633            DialogInterface.OnShowListener {
1634
1635        private AddAdapter mAdapter;
1636
1637        Dialog createDialog() {
1638            mWaitingForResult = true;
1639
1640            mAdapter = new AddAdapter(Launcher.this);
1641
1642            final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1643            builder.setTitle(getString(R.string.menu_item_add_item));
1644            builder.setAdapter(mAdapter, this);
1645
1646            builder.setInverseBackgroundForced(true);
1647
1648            AlertDialog dialog = builder.create();
1649            dialog.setOnCancelListener(this);
1650            dialog.setOnDismissListener(this);
1651            dialog.setOnShowListener(this);
1652
1653            return dialog;
1654        }
1655
1656        public void onCancel(DialogInterface dialog) {
1657            mWaitingForResult = false;
1658            cleanup();
1659        }
1660
1661        public void onDismiss(DialogInterface dialog) {
1662        }
1663
1664        private void cleanup() {
1665            dismissDialog(DIALOG_CREATE_SHORTCUT);
1666        }
1667
1668        /**
1669         * Handle the action clicked in the "Add to home" dialog.
1670         */
1671        public void onClick(DialogInterface dialog, int which) {
1672            Resources res = getResources();
1673            cleanup();
1674
1675            switch (which) {
1676                case AddAdapter.ITEM_SHORTCUT: {
1677                    // Insert extra item to handle picking application
1678                    pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut);
1679                    break;
1680                }
1681
1682                case AddAdapter.ITEM_APPWIDGET: {
1683                    int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
1684
1685                    Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1686                    pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1687                    // add the search widget
1688                    ArrayList<AppWidgetProviderInfo> customInfo =
1689                            new ArrayList<AppWidgetProviderInfo>();
1690                    AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1691                    info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1692                    info.label = getString(R.string.group_search);
1693                    info.icon = R.drawable.ic_search_widget;
1694                    customInfo.add(info);
1695                    pickIntent.putParcelableArrayListExtra(
1696                            AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1697                    ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1698                    Bundle b = new Bundle();
1699                    b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1700                    customExtras.add(b);
1701                    pickIntent.putParcelableArrayListExtra(
1702                            AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1703                    // start the pick activity
1704                    startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
1705                    break;
1706                }
1707
1708                case AddAdapter.ITEM_LIVE_FOLDER: {
1709                    // Insert extra item to handle inserting folder
1710                    Bundle bundle = new Bundle();
1711
1712                    ArrayList<String> shortcutNames = new ArrayList<String>();
1713                    shortcutNames.add(res.getString(R.string.group_folder));
1714                    bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1715
1716                    ArrayList<ShortcutIconResource> shortcutIcons =
1717                            new ArrayList<ShortcutIconResource>();
1718                    shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1719                            R.drawable.ic_launcher_folder));
1720                    bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1721
1722                    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1723                    pickIntent.putExtra(Intent.EXTRA_INTENT,
1724                            new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
1725                    pickIntent.putExtra(Intent.EXTRA_TITLE,
1726                            getText(R.string.title_select_live_folder));
1727                    pickIntent.putExtras(bundle);
1728
1729                    startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1730                    break;
1731                }
1732
1733                case AddAdapter.ITEM_WALLPAPER: {
1734                    startWallpaper();
1735                    break;
1736                }
1737            }
1738        }
1739
1740        public void onShow(DialogInterface dialog) {
1741        }
1742    }
1743
1744    /**
1745     * Implementation of the method from LauncherModel.Callbacks.
1746     */
1747    public int getCurrentWorkspaceScreen() {
1748        return mWorkspace.getCurrentScreen();
1749    }
1750
1751    /**
1752     * Refreshes the shortcuts shown on the workspace.
1753     *
1754     * Implementation of the method from LauncherModel.Callbacks.
1755     */
1756    public void startBinding() {
1757        final Workspace workspace = mWorkspace;
1758        int count = workspace.getChildCount();
1759        for (int i = 0; i < count; i++) {
1760            ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1761        }
1762
1763        if (DEBUG_USER_INTERFACE) {
1764            android.widget.Button finishButton = new android.widget.Button(this);
1765            finishButton.setText("Finish");
1766            workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1767
1768            finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1769                public void onClick(View v) {
1770                    finish();
1771                }
1772            });
1773        }
1774    }
1775
1776    /**
1777     * Bind the items start-end from the list.
1778     *
1779     * Implementation of the method from LauncherModel.Callbacks.
1780     */
1781    public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) {
1782
1783        final Workspace workspace = mWorkspace;
1784
1785        for (int i=start; i<end; i++) {
1786            final ItemInfo item = shortcuts.get(i);
1787            mDesktopItems.add(item);
1788            switch (item.itemType) {
1789                case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1790                case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1791                    final View shortcut = createShortcut((ApplicationInfo) item);
1792                    workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1793                            false);
1794                    break;
1795                case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1796                    final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1797                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1798                            (UserFolderInfo) item);
1799                    workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1800                            false);
1801                    break;
1802                case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1803                    final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1804                            R.layout.live_folder_icon, this,
1805                            (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1806                            (LiveFolderInfo) item);
1807                    workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1808                            false);
1809                    break;
1810                case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1811                    final int screen = workspace.getCurrentScreen();
1812                    final View view = mInflater.inflate(R.layout.widget_search,
1813                            (ViewGroup) workspace.getChildAt(screen), false);
1814
1815                    Search search = (Search) view.findViewById(R.id.widget_search);
1816                    search.setLauncher(this);
1817
1818                    final Widget widget = (Widget) item;
1819                    view.setTag(widget);
1820
1821                    workspace.addWidget(view, widget, false);
1822                    break;
1823            }
1824        }
1825
1826        workspace.requestLayout();
1827    }
1828
1829    /**
1830     * Implementation of the method from LauncherModel.Callbacks.
1831     */
1832    void bindFolders(HashMap<Long, FolderInfo> folders) {
1833        mFolders.putAll(folders);
1834    }
1835
1836    /**
1837     * Add the views for a widget to the workspace.
1838     *
1839     * Implementation of the method from LauncherModel.Callbacks.
1840     */
1841    public void bindAppWidget(LauncherAppWidgetInfo item) {
1842        final Workspace workspace = mWorkspace;
1843
1844        final int appWidgetId = item.appWidgetId;
1845        final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1846        item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1847
1848        if (true) {
1849            Log.d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s",
1850                    appWidgetId, appWidgetInfo));
1851        }
1852
1853        item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1854        item.hostView.setTag(item);
1855
1856        workspace.addInScreen(item.hostView, item.screen, item.cellX,
1857                item.cellY, item.spanX, item.spanY, false);
1858
1859        workspace.requestLayout();
1860
1861        mDesktopItems.add(item);
1862    }
1863
1864    /**
1865     * Callback saying that there aren't any more items to bind.
1866     *
1867     * Implementation of the method from LauncherModel.Callbacks.
1868     */
1869    public void finishBindingItems() {
1870        if (mSavedState != null) {
1871            if (!mWorkspace.hasFocus()) {
1872                mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1873            }
1874
1875            final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1876            if (userFolders != null) {
1877                for (long folderId : userFolders) {
1878                    final FolderInfo info = mFolders.get(folderId);
1879                    if (info != null) {
1880                        openFolder(info);
1881                    }
1882                }
1883                final Folder openFolder = mWorkspace.getOpenFolder();
1884                if (openFolder != null) {
1885                    openFolder.requestFocus();
1886                }
1887            }
1888
1889            final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1890            if (allApps) {
1891                showAllApps();
1892            }
1893
1894            mSavedState = null;
1895        }
1896
1897        if (mSavedInstanceState != null) {
1898            super.onRestoreInstanceState(mSavedInstanceState);
1899            mSavedInstanceState = null;
1900        }
1901
1902        /* TODO
1903        if (mAllAppsVisible && !mDrawer.hasFocus()) {
1904            mDrawer.requestFocus();
1905        }
1906        */
1907
1908        Log.d(TAG, "finishBindingItems done");
1909        mWorkspaceLoading = false;
1910    }
1911
1912    /**
1913     * Add the icons for all apps.
1914     *
1915     * Implementation of the method from LauncherModel.Callbacks.
1916     */
1917    public void bindAllApplications(ArrayList<ApplicationInfo> apps) {
1918        Log.d(LOG_TAG, "got info for " + apps.size() + " apps");
1919        mAllAppsList = apps;
1920        mAllAppsGrid.setApps(mAllAppsList);
1921    }
1922
1923    /**
1924     * A package was installed.
1925     *
1926     * Implementation of the method from LauncherModel.Callbacks.
1927     */
1928    public void bindPackageAdded(ArrayList<ApplicationInfo> apps) {
1929        removeDialog(DIALOG_CREATE_SHORTCUT);
1930    }
1931
1932    /**
1933     * A package was updated.
1934     *
1935     * Implementation of the method from LauncherModel.Callbacks.
1936     */
1937    public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps) {
1938        removeDialog(DIALOG_CREATE_SHORTCUT);
1939        mWorkspace.updateShortcutsForPackage(packageName);
1940    }
1941
1942    /**
1943     * A package was uninstalled.
1944     *
1945     * Implementation of the method from LauncherModel.Callbacks.
1946     */
1947    public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps) {
1948        removeDialog(DIALOG_CREATE_SHORTCUT);
1949        mWorkspace.removeShortcutsForPackage(packageName);
1950    }
1951
1952}
1953