OSDN Git Service

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