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