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