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