OSDN Git Service

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