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