2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.launcher;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.Dialog;
22 import android.app.ISearchManager;
23 import android.app.SearchManager;
24 import android.app.StatusBarManager;
25 import android.app.WallpaperManager;
26 import android.content.ActivityNotFoundException;
27 import android.content.BroadcastReceiver;
28 import android.content.ComponentName;
29 import android.content.ContentResolver;
30 import android.content.Context;
31 import android.content.DialogInterface;
32 import android.content.Intent;
33 import android.content.IntentFilter;
34 import android.content.Intent.ShortcutIconResource;
35 import android.content.pm.ActivityInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.PackageManager.NameNotFoundException;
38 import android.content.res.Configuration;
39 import android.content.res.Resources;
40 import android.database.ContentObserver;
41 import android.graphics.Bitmap;
42 import android.graphics.Rect;
43 import android.graphics.drawable.Drawable;
44 import android.graphics.drawable.TransitionDrawable;
45 import android.os.Bundle;
46 import android.os.Handler;
47 import android.os.Looper;
48 import android.os.Message;
49 import android.os.MessageQueue;
50 import android.os.Parcelable;
51 import android.os.RemoteException;
52 import android.os.ServiceManager;
53 import android.provider.LiveFolders;
54 import android.text.Selection;
55 import android.text.SpannableStringBuilder;
56 import android.text.TextUtils;
57 import android.text.method.TextKeyListener;
58 import static android.util.Log.*;
59 import android.util.SparseArray;
60 import android.view.Display;
61 import android.view.KeyEvent;
62 import android.view.LayoutInflater;
63 import android.view.Menu;
64 import android.view.MenuItem;
65 import android.view.View;
66 import android.view.ViewGroup;
67 import android.view.View.OnLongClickListener;
68 import android.view.inputmethod.InputMethodManager;
69 import android.widget.EditText;
70 import android.widget.GridView;
71 import android.widget.SlidingDrawer;
72 import android.widget.TextView;
73 import android.widget.Toast;
74 import android.appwidget.AppWidgetManager;
75 import android.appwidget.AppWidgetProviderInfo;
77 import java.lang.ref.WeakReference;
78 import java.util.ArrayList;
79 import java.util.LinkedList;
80 import java.io.DataOutputStream;
81 import java.io.FileNotFoundException;
82 import java.io.IOException;
83 import java.io.DataInputStream;
86 * Default launcher application.
88 public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
89 static final String LOG_TAG = "Launcher";
90 static final boolean LOGD = false;
92 private static final boolean PROFILE_STARTUP = false;
93 private static final boolean PROFILE_DRAWER = false;
94 private static final boolean PROFILE_ROTATE = false;
95 private static final boolean DEBUG_USER_INTERFACE = false;
97 private static final int MENU_GROUP_ADD = 1;
98 private static final int MENU_ADD = Menu.FIRST + 1;
99 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
100 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
101 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
102 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
104 private static final int REQUEST_CREATE_SHORTCUT = 1;
105 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
106 private static final int REQUEST_CREATE_APPWIDGET = 5;
107 private static final int REQUEST_PICK_APPLICATION = 6;
108 private static final int REQUEST_PICK_SHORTCUT = 7;
109 private static final int REQUEST_PICK_LIVE_FOLDER = 8;
110 private static final int REQUEST_PICK_APPWIDGET = 9;
112 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
114 static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
115 static final String SEARCH_WIDGET = "search_widget";
117 static final int WALLPAPER_SCREENS_SPAN = 2;
118 static final int SCREEN_COUNT = 3;
119 static final int DEFAULT_SCREN = 1;
120 static final int NUMBER_CELLS_X = 4;
121 static final int NUMBER_CELLS_Y = 4;
123 private static final int DIALOG_CREATE_SHORTCUT = 1;
124 static final int DIALOG_RENAME_FOLDER = 2;
126 private static final String PREFERENCES = "launcher.preferences";
129 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
131 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
133 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
135 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
137 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
139 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
141 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
143 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
145 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
147 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
149 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
151 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
153 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
155 private static final LauncherModel sModel = new LauncherModel();
157 private static final Object sLock = new Object();
158 private static int sScreen = DEFAULT_SCREN;
160 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
161 private final ContentObserver mObserver = new FavoritesChangeObserver();
163 private LayoutInflater mInflater;
165 private DragLayer mDragLayer;
166 private Workspace mWorkspace;
168 private AppWidgetManager mAppWidgetManager;
169 private LauncherAppWidgetHost mAppWidgetHost;
171 static final int APPWIDGET_HOST_ID = 1024;
173 private CellLayout.CellInfo mAddItemCellInfo;
174 private CellLayout.CellInfo mMenuAddInfo;
175 private final int[] mCellCoordinates = new int[2];
176 private FolderInfo mFolderInfo;
178 private SlidingDrawer mDrawer;
179 private TransitionDrawable mHandleIcon;
180 private HandleView mHandleView;
181 private AllAppsGridView mAllAppsGrid;
183 private boolean mDesktopLocked = true;
184 private Bundle mSavedState;
186 private SpannableStringBuilder mDefaultKeySsb = null;
188 private boolean mDestroyed;
190 private boolean mIsNewIntent;
192 private boolean mRestoring;
193 private boolean mWaitingForResult;
194 private boolean mLocaleChanged;
196 private Bundle mSavedInstanceState;
198 private DesktopBinder mBinder;
201 protected void onCreate(Bundle savedInstanceState) {
202 super.onCreate(savedInstanceState);
203 mInflater = getLayoutInflater();
205 mAppWidgetManager = AppWidgetManager.getInstance(this);
207 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
208 mAppWidgetHost.startListening();
210 if (PROFILE_STARTUP) {
211 android.os.Debug.startMethodTracing("/sdcard/launcher");
214 checkForLocaleChange();
215 setWallpaperDimension();
217 setContentView(R.layout.launcher);
220 registerIntentReceivers();
221 registerContentObservers();
223 mSavedState = savedInstanceState;
224 restoreState(mSavedState);
226 if (PROFILE_STARTUP) {
227 android.os.Debug.stopMethodTracing();
234 // For handling default keys
235 mDefaultKeySsb = new SpannableStringBuilder();
236 Selection.setSelection(mDefaultKeySsb, 0);
239 private void checkForLocaleChange() {
240 final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
241 readConfiguration(this, localeConfiguration);
243 final Configuration configuration = getResources().getConfiguration();
245 final String previousLocale = localeConfiguration.locale;
246 final String locale = configuration.locale.toString();
248 final int previousMcc = localeConfiguration.mcc;
249 final int mcc = configuration.mcc;
251 final int previousMnc = localeConfiguration.mnc;
252 final int mnc = configuration.mnc;
254 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
256 if (mLocaleChanged) {
257 localeConfiguration.locale = locale;
258 localeConfiguration.mcc = mcc;
259 localeConfiguration.mnc = mnc;
261 writeConfiguration(this, localeConfiguration);
265 private static class LocaleConfiguration {
266 public String locale;
271 private static void readConfiguration(Context context, LocaleConfiguration configuration) {
272 DataInputStream in = null;
274 in = new DataInputStream(context.openFileInput(PREFERENCES));
275 configuration.locale = in.readUTF();
276 configuration.mcc = in.readInt();
277 configuration.mnc = in.readInt();
278 } catch (FileNotFoundException e) {
280 } catch (IOException e) {
286 } catch (IOException e) {
293 private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
294 DataOutputStream out = null;
296 out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
297 out.writeUTF(configuration.locale);
298 out.writeInt(configuration.mcc);
299 out.writeInt(configuration.mnc);
301 } catch (FileNotFoundException e) {
303 } catch (IOException e) {
304 //noinspection ResultOfMethodCallIgnored
305 context.getFileStreamPath(PREFERENCES).delete();
310 } catch (IOException e) {
317 static int getScreen() {
318 synchronized (sLock) {
323 static void setScreen(int screen) {
324 synchronized (sLock) {
329 private void startLoaders() {
330 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
331 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
336 private void setWallpaperDimension() {
337 WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
339 Display display = getWindowManager().getDefaultDisplay();
340 boolean isPortrait = display.getWidth() < display.getHeight();
342 final int width = isPortrait ? display.getWidth() : display.getHeight();
343 final int height = isPortrait ? display.getHeight() : display.getWidth();
344 wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height);
348 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
349 mWaitingForResult = false;
351 // The pattern used here is that a user PICKs a specific application,
352 // which, depending on the target, might need to CREATE the actual target.
354 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
355 // launch over to the Music app to actually CREATE_SHORTCUT.
357 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
358 switch (requestCode) {
359 case REQUEST_PICK_APPLICATION:
360 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
362 case REQUEST_PICK_SHORTCUT:
363 processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT);
365 case REQUEST_CREATE_SHORTCUT:
366 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
368 case REQUEST_PICK_LIVE_FOLDER:
371 case REQUEST_CREATE_LIVE_FOLDER:
372 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
374 case REQUEST_PICK_APPWIDGET:
377 case REQUEST_CREATE_APPWIDGET:
378 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
381 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
382 resultCode == RESULT_CANCELED && data != null) {
383 // Clean up the appWidgetId if we canceled
384 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
385 if (appWidgetId != -1) {
386 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
392 protected void onResume() {
399 // If this was a new intent (i.e., the mIsNewIntent flag got set to true by
400 // onNewIntent), then close the search dialog if needed, because it probably
401 // came from the user pressing 'home' (rather than, for example, pressing 'back').
403 // Post to a handler so that this happens after the search dialog tries to open
405 mWorkspace.post(new Runnable() {
407 ISearchManager searchManagerService = ISearchManager.Stub.asInterface(
408 ServiceManager.getService(Context.SEARCH_SERVICE));
410 searchManagerService.stopSearch();
411 } catch (RemoteException e) {
412 e(LOG_TAG, "error stopping search", e);
418 mIsNewIntent = false;
422 protected void onPause() {
428 public Object onRetainNonConfigurationInstance() {
429 // Flag any binder to stop early before switching
430 if (mBinder != null) {
431 mBinder.mTerminate = true;
434 if (PROFILE_ROTATE) {
435 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
440 private boolean acceptFilter() {
441 final InputMethodManager inputManager = (InputMethodManager)
442 getSystemService(Context.INPUT_METHOD_SERVICE);
443 return !inputManager.isFullscreenMode();
447 public boolean onKeyDown(int keyCode, KeyEvent event) {
448 boolean handled = super.onKeyDown(keyCode, event);
449 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
450 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
452 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
453 // something usable has been typed - start a search
454 // the typed text will be retrieved and cleared by
455 // showSearchDialog()
456 // If there are multiple keystrokes before the search dialog takes focus,
457 // onSearchRequested() will be called for every keystroke,
458 // but it is idempotent, so it's fine.
459 return onSearchRequested();
466 private String getTypedText() {
467 return mDefaultKeySsb.toString();
470 private void clearTypedText() {
471 mDefaultKeySsb.clear();
472 mDefaultKeySsb.clearSpans();
473 Selection.setSelection(mDefaultKeySsb, 0);
477 * Restores the previous state, if it exists.
479 * @param savedState The previous state.
481 private void restoreState(Bundle savedState) {
482 if (savedState == null) {
486 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
487 if (currentScreen > -1) {
488 mWorkspace.setCurrentScreen(currentScreen);
491 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
492 if (addScreen > -1) {
493 mAddItemCellInfo = new CellLayout.CellInfo();
494 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
495 addItemCellInfo.valid = true;
496 addItemCellInfo.screen = addScreen;
497 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
498 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
499 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
500 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
501 addItemCellInfo.findVacantCellsFromOccupied(
502 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
503 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
504 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
508 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
510 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
511 mFolderInfo = sModel.getFolderById(this, id);
517 * Finds all the views we need and configure them properly.
519 private void setupViews() {
520 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
521 final DragLayer dragLayer = mDragLayer;
523 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
524 final Workspace workspace = mWorkspace;
526 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
527 final SlidingDrawer drawer = mDrawer;
529 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
530 final AllAppsGridView grid = mAllAppsGrid;
532 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
534 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
535 mHandleView.setLauncher(this);
536 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
537 mHandleIcon.setCrossFadeEnabled(true);
540 final DrawerManager drawerManager = new DrawerManager();
541 drawer.setOnDrawerOpenListener(drawerManager);
542 drawer.setOnDrawerCloseListener(drawerManager);
543 drawer.setOnDrawerScrollListener(drawerManager);
545 grid.setTextFilterEnabled(false);
546 grid.setDragger(dragLayer);
547 grid.setLauncher(this);
549 workspace.setOnLongClickListener(this);
550 workspace.setDragger(dragLayer);
551 workspace.setLauncher(this);
553 deleteZone.setLauncher(this);
554 deleteZone.setDragController(dragLayer);
555 deleteZone.setHandle(mHandleView);
557 dragLayer.setIgnoredDropTarget(grid);
558 dragLayer.setDragScoller(workspace);
559 dragLayer.setDragListener(deleteZone);
563 * Creates a view representing a shortcut.
565 * @param info The data structure describing the shortcut.
567 * @return A View inflated from R.layout.application.
569 View createShortcut(ApplicationInfo info) {
570 return createShortcut(R.layout.application,
571 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
575 * Creates a view representing a shortcut inflated from the specified resource.
577 * @param layoutResId The id of the XML layout used to create the shortcut.
578 * @param parent The group the shortcut belongs to.
579 * @param info The data structure describing the shortcut.
581 * @return A View inflated from layoutResId.
583 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
584 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
586 if (!info.filtered) {
587 info.icon = Utilities.createIconThumbnail(info.icon, this);
588 info.filtered = true;
591 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
592 favorite.setText(info.title);
593 favorite.setTag(info);
594 favorite.setOnClickListener(this);
600 * Add an application shortcut to the workspace.
602 * @param data The intent describing the application.
603 * @param cellInfo The position on screen where to create the shortcut.
605 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
606 boolean insertAtFirst) {
607 cellInfo.screen = mWorkspace.getCurrentScreen();
608 if (!findSingleSlot(cellInfo)) return;
610 final ApplicationInfo info = infoFromApplicationIntent(context, data);
612 mWorkspace.addApplicationShortcut(info, cellInfo, insertAtFirst);
616 private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) {
617 ComponentName component = data.getComponent();
618 PackageManager packageManager = context.getPackageManager();
619 ActivityInfo activityInfo = null;
621 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
622 } catch (NameNotFoundException e) {
623 e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
626 if (activityInfo != null) {
627 ApplicationInfo itemInfo = new ApplicationInfo();
629 itemInfo.title = activityInfo.loadLabel(packageManager);
630 if (itemInfo.title == null) {
631 itemInfo.title = activityInfo.name;
634 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
635 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
636 itemInfo.icon = activityInfo.loadIcon(packageManager);
637 itemInfo.container = ItemInfo.NO_ID;
646 * Add a shortcut to the workspace.
648 * @param data The intent describing the shortcut.
649 * @param cellInfo The position on screen where to create the shortcut.
650 * @param insertAtFirst
652 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
653 boolean insertAtFirst) {
654 cellInfo.screen = mWorkspace.getCurrentScreen();
655 if (!findSingleSlot(cellInfo)) return;
657 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
660 sModel.addDesktopItem(info);
662 final View view = createShortcut(info);
663 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
664 } else if (sModel.isDesktopLoaded()) {
665 sModel.addDesktopItem(info);
671 * Add a widget to the workspace.
673 * @param data The intent describing the appWidgetId.
674 * @param cellInfo The position on screen where to create the widget.
676 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
677 boolean insertAtFirst) {
679 Bundle extras = data.getExtras();
680 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
682 d(LOG_TAG, "dumping extras content="+extras.toString());
684 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
686 // Calculate the grid spans needed to fit this widget
687 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
688 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
690 // Try finding open space on Launcher screen
691 final int[] xy = mCellCoordinates;
692 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
694 // Build Launcher-specific widget info and save to database
695 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
696 launcherInfo.spanX = spans[0];
697 launcherInfo.spanY = spans[1];
699 LauncherModel.addItemToDatabase(this, launcherInfo,
700 LauncherSettings.Favorites.CONTAINER_DESKTOP,
701 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
704 sModel.addDesktopAppWidget(launcherInfo);
706 // Perform actual inflation because we're live
707 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
709 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
710 launcherInfo.hostView.setTag(launcherInfo);
712 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
713 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
714 } else if (sModel.isDesktopLoaded()) {
715 sModel.addDesktopAppWidget(launcherInfo);
719 public LauncherAppWidgetHost getAppWidgetHost() {
720 return mAppWidgetHost;
723 static ApplicationInfo addShortcut(Context context, Intent data,
724 CellLayout.CellInfo cellInfo, boolean notify) {
726 final ApplicationInfo info = infoFromShortcutIntent(context, data);
727 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
728 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
733 private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) {
734 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
735 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
736 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
738 Drawable icon = null;
739 boolean filtered = false;
740 boolean customIcon = false;
741 ShortcutIconResource iconResource = null;
743 if (bitmap != null) {
744 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
748 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
749 if (extra != null && extra instanceof ShortcutIconResource) {
751 iconResource = (ShortcutIconResource) extra;
752 final PackageManager packageManager = context.getPackageManager();
753 Resources resources = packageManager.getResourcesForApplication(
754 iconResource.packageName);
755 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
756 icon = resources.getDrawable(id);
757 } catch (Exception e) {
758 w(LOG_TAG, "Could not load shortcut icon: " + extra);
764 icon = context.getPackageManager().getDefaultActivityIcon();
767 final ApplicationInfo info = new ApplicationInfo();
769 info.filtered = filtered;
771 info.intent = intent;
772 info.customIcon = customIcon;
773 info.iconResource = iconResource;
779 protected void onNewIntent(Intent intent) {
780 super.onNewIntent(intent);
783 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
784 getWindow().closeAllPanels();
786 // Set this flag so that onResume knows to close the search dialog if it's open,
787 // because this was a new intent (thus a press of 'home' or some such) rather than
788 // for example onResume being called when the user pressed the 'back' button.
792 dismissDialog(DIALOG_CREATE_SHORTCUT);
793 // Unlock the workspace if the dialog was showing
795 } catch (Exception e) {
796 // An exception is thrown if the dialog is not visible, which is fine
800 dismissDialog(DIALOG_RENAME_FOLDER);
801 // Unlock the workspace if the dialog was showing
803 } catch (Exception e) {
804 // An exception is thrown if the dialog is not visible, which is fine
807 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
808 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
810 if (!mWorkspace.isDefaultScreenShowing()) {
811 mWorkspace.moveToDefaultScreen();
816 final View v = getWindow().peekDecorView();
817 if (v != null && v.getWindowToken() != null) {
818 InputMethodManager imm = (InputMethodManager)getSystemService(
819 INPUT_METHOD_SERVICE);
820 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
829 protected void onRestoreInstanceState(Bundle savedInstanceState) {
830 // NOTE: Do NOT do this. Ever. This is a terrible and horrifying hack.
832 // Home loads the content of the workspace on a background thread. This means that
833 // a previously focused view will be, after orientation change, added to the view
834 // hierarchy at an undeterminate time in the future. If we were to invoke
835 // super.onRestoreInstanceState() here, the focus restoration would fail because the
836 // view to focus does not exist yet.
838 // However, not invoking super.onRestoreInstanceState() is equally bad. In such a case,
839 // panels would not be restored properly. For instance, if the menu is open then the
840 // user changes the orientation, the menu would not be opened in the new orientation.
842 // To solve both issues Home messes up with the internal state of the bundle to remove
843 // the properties it does not want to see restored at this moment. After invoking
844 // super.onRestoreInstanceState(), it removes the panels state.
846 // Later, when the workspace is done loading, Home calls super.onRestoreInstanceState()
847 // again to restore focus and other view properties. It will not, however, restore
848 // the panels since at this point the panels' state has been removed from the bundle.
850 // This is a bad example, do not do this.
852 // If you are curious on how this code was put together, take a look at the following
853 // in Android's source code:
854 // - Activity.onRestoreInstanceState()
855 // - PhoneWindow.restoreHierarchyState()
856 // - PhoneWindow.DecorView.onAttachedToWindow()
858 // The source code of these various methods shows what states should be kept to
859 // achieve what we want here.
861 Bundle windowState = savedInstanceState.getBundle("android:viewHierarchyState");
862 SparseArray<Parcelable> savedStates = null;
863 int focusedViewId = View.NO_ID;
865 if (windowState != null) {
866 savedStates = windowState.getSparseParcelableArray("android:views");
867 windowState.remove("android:views");
868 focusedViewId = windowState.getInt("android:focusedViewId", View.NO_ID);
869 windowState.remove("android:focusedViewId");
872 super.onRestoreInstanceState(savedInstanceState);
874 if (windowState != null) {
875 windowState.putSparseParcelableArray("android:views", savedStates);
876 windowState.putInt("android:focusedViewId", focusedViewId);
877 windowState.remove("android:Panels");
880 mSavedInstanceState = savedInstanceState;
884 protected void onSaveInstanceState(Bundle outState) {
885 super.onSaveInstanceState(outState);
887 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
889 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
890 if (folders.size() > 0) {
891 final int count = folders.size();
892 long[] ids = new long[count];
893 for (int i = 0; i < count; i++) {
894 final FolderInfo info = folders.get(i).getInfo();
897 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
900 final boolean isConfigurationChange = getChangingConfigurations() != 0;
902 // When the drawer is opened and we are saving the state because of a
903 // configuration change
904 if (mDrawer.isOpened() && isConfigurationChange) {
905 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
908 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
909 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
910 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
912 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
913 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
914 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
915 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
916 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
917 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
918 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
919 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
920 layout.getOccupiedCells());
923 if (mFolderInfo != null && mWaitingForResult) {
924 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
925 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
930 public void onDestroy() {
936 mAppWidgetHost.stopListening();
937 } catch (NullPointerException ex) {
938 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
941 TextKeyListener.getInstance().release();
943 mAllAppsGrid.clearTextFilter();
944 mAllAppsGrid.setAdapter(null);
946 sModel.abortLoaders();
948 getContentResolver().unregisterContentObserver(mObserver);
949 unregisterReceiver(mApplicationsReceiver);
953 public void startActivityForResult(Intent intent, int requestCode) {
954 if (requestCode >= 0) mWaitingForResult = true;
955 super.startActivityForResult(intent, requestCode);
959 public void startSearch(String initialQuery, boolean selectInitialQuery,
960 Bundle appSearchData, boolean globalSearch) {
964 // Slide the search widget to the top, if it's on the current screen,
965 // otherwise show the search dialog immediately.
966 Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
967 if (searchWidget == null) {
968 showSearchDialog(initialQuery, selectInitialQuery, appSearchData, globalSearch);
970 searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
971 // show the currently typed text in the search widget while sliding
972 searchWidget.setQuery(getTypedText());
977 * Show the search dialog immediately, without changing the search widget.
979 * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean)
981 void showSearchDialog(String initialQuery, boolean selectInitialQuery,
982 Bundle appSearchData, boolean globalSearch) {
984 if (initialQuery == null) {
985 // Use any text typed in the launcher as the initial query
986 initialQuery = getTypedText();
989 if (appSearchData == null) {
990 appSearchData = new Bundle();
991 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
994 final SearchManager searchManager =
995 (SearchManager) getSystemService(Context.SEARCH_SERVICE);
997 final Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
998 if (searchWidget != null) {
999 // This gets called when the user leaves the search dialog to go back to
1001 searchManager.setOnCancelListener(new SearchManager.OnCancelListener() {
1002 public void onCancel() {
1003 searchManager.setOnCancelListener(null);
1009 searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1010 appSearchData, globalSearch);
1014 * Cancel search dialog if it is open.
1017 // Close search dialog
1018 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
1019 searchManager.stopSearch();
1020 // Restore search widget to its normal position
1021 Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen();
1022 if (searchWidget != null) {
1023 searchWidget.stopSearch(false);
1028 public boolean onCreateOptionsMenu(Menu menu) {
1029 if (mDesktopLocked && mSavedInstanceState == null) return false;
1031 super.onCreateOptionsMenu(menu);
1032 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
1033 .setIcon(android.R.drawable.ic_menu_add)
1034 .setAlphabeticShortcut('A');
1035 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
1036 .setIcon(android.R.drawable.ic_menu_gallery)
1037 .setAlphabeticShortcut('W');
1038 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
1039 .setIcon(android.R.drawable.ic_search_category_default)
1040 .setAlphabeticShortcut(SearchManager.MENU_KEY);
1041 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
1042 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
1043 .setAlphabeticShortcut('N');
1045 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
1046 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1047 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1049 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1050 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1051 .setIntent(settings);
1057 public boolean onPrepareOptionsMenu(Menu menu) {
1058 super.onPrepareOptionsMenu(menu);
1060 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
1061 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
1067 public boolean onOptionsItemSelected(MenuItem item) {
1068 switch (item.getItemId()) {
1072 case MENU_WALLPAPER_SETTINGS:
1076 onSearchRequested();
1078 case MENU_NOTIFICATIONS:
1079 showNotifications();
1083 return super.onOptionsItemSelected(item);
1087 * Indicates that we want global search for this activity by setting the globalSearch
1088 * argument for {@link #startSearch} to true.
1092 public boolean onSearchRequested() {
1093 startSearch(null, false, null, true);
1097 private void addItems() {
1098 showAddDialog(mMenuAddInfo);
1101 private void removeShortcutsForPackage(String packageName) {
1102 if (packageName != null && packageName.length() > 0) {
1103 mWorkspace.removeShortcutsForPackage(packageName);
1107 private void updateShortcutsForPackage(String packageName) {
1108 if (packageName != null && packageName.length() > 0) {
1109 mWorkspace.updateShortcutsForPackage(packageName);
1113 void addAppWidget(Intent data) {
1114 // TODO: catch bad widget exception when sent
1115 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
1117 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
1118 if (SEARCH_WIDGET.equals(customWidget)) {
1119 // We don't need this any more, since this isn't a real app widget.
1120 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
1121 // add the search widget
1124 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1126 if (appWidget.configure != null) {
1127 // Launch over to configure widget, if needed
1128 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
1129 intent.setComponent(appWidget.configure);
1130 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1132 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
1134 // Otherwise just add it
1135 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
1141 final Widget info = Widget.makeSearch();
1142 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1144 final int[] xy = mCellCoordinates;
1145 final int spanX = info.spanX;
1146 final int spanY = info.spanY;
1148 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
1150 sModel.addDesktopItem(info);
1151 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1152 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
1154 final View view = mInflater.inflate(info.layoutResource, null);
1156 Search search = (Search) view.findViewById(R.id.widget_search);
1157 search.setLauncher(this);
1159 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
1162 void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) {
1163 // Handle case where user selected "Applications"
1164 String applicationName = getResources().getString(R.string.group_applications);
1165 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1167 if (applicationName != null && applicationName.equals(shortcutName)) {
1168 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1169 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1171 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1172 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1173 startActivityForResult(pickIntent, requestCodeApplication);
1175 startActivityForResult(intent, requestCodeShortcut);
1179 void addLiveFolder(Intent intent) {
1180 // Handle case where user selected "Folder"
1181 String folderName = getResources().getString(R.string.group_folder);
1182 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1184 if (folderName != null && folderName.equals(shortcutName)) {
1185 addFolder(!mDesktopLocked);
1187 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1191 void addFolder(boolean insertAtFirst) {
1192 UserFolderInfo folderInfo = new UserFolderInfo();
1193 folderInfo.title = getText(R.string.folder_name);
1195 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1196 cellInfo.screen = mWorkspace.getCurrentScreen();
1197 if (!findSingleSlot(cellInfo)) return;
1200 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1201 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1202 sModel.addDesktopItem(folderInfo);
1203 sModel.addFolder(folderInfo);
1206 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1207 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1208 mWorkspace.addInCurrentScreen(newFolder,
1209 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1212 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
1213 boolean insertAtFirst) {
1214 cellInfo.screen = mWorkspace.getCurrentScreen();
1215 if (!findSingleSlot(cellInfo)) return;
1217 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1220 sModel.addDesktopItem(info);
1222 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1223 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1224 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1225 } else if (sModel.isDesktopLoaded()) {
1226 sModel.addDesktopItem(info);
1230 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1231 CellLayout.CellInfo cellInfo, boolean notify) {
1233 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1234 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1236 Drawable icon = null;
1237 boolean filtered = false;
1238 Intent.ShortcutIconResource iconResource = null;
1240 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1241 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1243 iconResource = (Intent.ShortcutIconResource) extra;
1244 final PackageManager packageManager = context.getPackageManager();
1245 Resources resources = packageManager.getResourcesForApplication(
1246 iconResource.packageName);
1247 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1248 icon = resources.getDrawable(id);
1249 } catch (Exception e) {
1250 w(LOG_TAG, "Could not load live folder icon: " + extra);
1255 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1258 final LiveFolderInfo info = new LiveFolderInfo();
1260 info.filtered = filtered;
1262 info.iconResource = iconResource;
1263 info.uri = data.getData();
1264 info.baseIntent = baseIntent;
1265 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1266 LiveFolders.DISPLAY_MODE_GRID);
1268 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1269 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1270 sModel.addFolder(info);
1275 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1276 final int[] xy = new int[2];
1277 if (findSlot(cellInfo, xy, 1, 1)) {
1278 cellInfo.cellX = xy[0];
1279 cellInfo.cellY = xy[1];
1285 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1286 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1287 boolean[] occupied = mSavedState != null ?
1288 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1289 cellInfo = mWorkspace.findAllVacantCells(occupied);
1290 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1291 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1298 private void showNotifications() {
1299 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1300 if (statusBar != null) {
1305 private void startWallpaper() {
1306 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1307 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1311 * Registers various intent receivers. The current implementation registers
1312 * only a wallpaper intent receiver to let other applications change the
1315 private void registerIntentReceivers() {
1316 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1317 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1318 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1319 filter.addDataScheme("package");
1320 registerReceiver(mApplicationsReceiver, filter);
1324 * Registers various content observers. The current implementation registers
1325 * only a favorites observer to keep track of the favorites applications.
1327 private void registerContentObservers() {
1328 ContentResolver resolver = getContentResolver();
1329 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1333 public boolean dispatchKeyEvent(KeyEvent event) {
1334 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1335 switch (event.getKeyCode()) {
1336 case KeyEvent.KEYCODE_BACK:
1338 case KeyEvent.KEYCODE_HOME:
1341 } else if (event.getAction() == KeyEvent.ACTION_UP) {
1342 switch (event.getKeyCode()) {
1343 case KeyEvent.KEYCODE_BACK:
1344 if (!event.isCanceled()) {
1345 mWorkspace.dispatchKeyEvent(event);
1346 if (mDrawer.isOpened()) {
1353 case KeyEvent.KEYCODE_HOME:
1358 return super.dispatchKeyEvent(event);
1361 private void closeDrawer() {
1365 private void closeDrawer(boolean animated) {
1366 if (mDrawer.isOpened()) {
1368 mDrawer.animateClose();
1372 if (mDrawer.hasFocus()) {
1373 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1378 private void closeFolder() {
1379 Folder folder = mWorkspace.getOpenFolder();
1380 if (folder != null) {
1381 closeFolder(folder);
1385 void closeFolder(Folder folder) {
1386 folder.getInfo().opened = false;
1387 ViewGroup parent = (ViewGroup) folder.getParent();
1388 if (parent != null) {
1389 parent.removeView(folder);
1395 * When the notification that favorites have changed is received, requests
1396 * a favorites list refresh.
1398 private void onFavoritesChanged() {
1399 mDesktopLocked = true;
1401 sModel.loadUserItems(false, this, false, false);
1404 void onDesktopItemsLoaded(ArrayList<ItemInfo> shortcuts,
1405 ArrayList<LauncherAppWidgetInfo> appWidgets) {
1407 if (LauncherModel.DEBUG_LOADERS) {
1408 d(LauncherModel.LOG_TAG, " ------> destroyed, ignoring desktop items");
1412 bindDesktopItems(shortcuts, appWidgets);
1416 * Refreshes the shortcuts shown on the workspace.
1418 private void bindDesktopItems(ArrayList<ItemInfo> shortcuts,
1419 ArrayList<LauncherAppWidgetInfo> appWidgets) {
1421 final ApplicationsAdapter drawerAdapter = sModel.getApplicationsAdapter();
1422 if (shortcuts == null || appWidgets == null || drawerAdapter == null) {
1423 if (LauncherModel.DEBUG_LOADERS) d(LauncherModel.LOG_TAG, " ------> a source is null");
1427 final Workspace workspace = mWorkspace;
1428 int count = workspace.getChildCount();
1429 for (int i = 0; i < count; i++) {
1430 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1433 if (DEBUG_USER_INTERFACE) {
1434 android.widget.Button finishButton = new android.widget.Button(this);
1435 finishButton.setText("Finish");
1436 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1438 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1439 public void onClick(View v) {
1445 // Flag any old binder to terminate early
1446 if (mBinder != null) {
1447 mBinder.mTerminate = true;
1450 mBinder = new DesktopBinder(this, shortcuts, appWidgets, drawerAdapter);
1451 mBinder.startBindingItems();
1454 private void bindItems(Launcher.DesktopBinder binder,
1455 ArrayList<ItemInfo> shortcuts, int start, int count) {
1457 final Workspace workspace = mWorkspace;
1458 final boolean desktopLocked = mDesktopLocked;
1460 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1463 for ( ; i < end; i++) {
1464 final ItemInfo item = shortcuts.get(i);
1465 switch (item.itemType) {
1466 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1467 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1468 final View shortcut = createShortcut((ApplicationInfo) item);
1469 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1472 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1473 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1474 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1475 (UserFolderInfo) item);
1476 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1479 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1480 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1481 R.layout.live_folder_icon, this,
1482 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1483 (LiveFolderInfo) item);
1484 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1487 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1488 final int screen = workspace.getCurrentScreen();
1489 final View view = mInflater.inflate(R.layout.widget_search,
1490 (ViewGroup) workspace.getChildAt(screen), false);
1492 Search search = (Search) view.findViewById(R.id.widget_search);
1493 search.setLauncher(this);
1495 final Widget widget = (Widget) item;
1496 view.setTag(widget);
1498 workspace.addWidget(view, widget, !desktopLocked);
1503 workspace.requestLayout();
1506 finishBindDesktopItems();
1507 binder.startBindingDrawer();
1509 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1513 private void finishBindDesktopItems() {
1514 if (mSavedState != null) {
1515 if (!mWorkspace.hasFocus()) {
1516 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1519 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1520 if (userFolders != null) {
1521 for (long folderId : userFolders) {
1522 final FolderInfo info = sModel.findFolderById(folderId);
1527 final Folder openFolder = mWorkspace.getOpenFolder();
1528 if (openFolder != null) {
1529 openFolder.requestFocus();
1533 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1541 if (mSavedInstanceState != null) {
1542 super.onRestoreInstanceState(mSavedInstanceState);
1543 mSavedInstanceState = null;
1546 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1547 mDrawer.requestFocus();
1550 mDesktopLocked = false;
1554 private void bindDrawer(Launcher.DesktopBinder binder,
1555 ApplicationsAdapter drawerAdapter) {
1556 mAllAppsGrid.setAdapter(drawerAdapter);
1557 binder.startBindingAppWidgetsWhenIdle();
1560 private void bindAppWidgets(Launcher.DesktopBinder binder,
1561 LinkedList<LauncherAppWidgetInfo> appWidgets) {
1563 final Workspace workspace = mWorkspace;
1564 final boolean desktopLocked = mDesktopLocked;
1566 if (!appWidgets.isEmpty()) {
1567 final LauncherAppWidgetInfo item = appWidgets.removeFirst();
1569 final int appWidgetId = item.appWidgetId;
1570 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1571 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1574 d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s",
1575 appWidgetId, appWidgetInfo));
1578 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1579 item.hostView.setTag(item);
1581 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1582 item.cellY, item.spanX, item.spanY, !desktopLocked);
1584 workspace.requestLayout();
1587 if (appWidgets.isEmpty()) {
1588 if (PROFILE_ROTATE) {
1589 android.os.Debug.stopMethodTracing();
1592 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
1597 * Launches the intent referred by the clicked shortcut.
1599 * @param v The view representing the clicked shortcut.
1601 public void onClick(View v) {
1602 Object tag = v.getTag();
1603 if (tag instanceof ApplicationInfo) {
1605 final Intent intent = ((ApplicationInfo) tag).intent;
1606 startActivitySafely(intent);
1607 } else if (tag instanceof FolderInfo) {
1608 handleFolderClick((FolderInfo) tag);
1612 void startActivitySafely(Intent intent) {
1613 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1615 startActivity(intent);
1616 } catch (ActivityNotFoundException e) {
1617 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1618 } catch (SecurityException e) {
1619 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1620 e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1621 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1622 "or use the exported attribute for this activity.", e);
1626 private void handleFolderClick(FolderInfo folderInfo) {
1627 if (!folderInfo.opened) {
1628 // Close any open folder
1630 // Open the requested folder
1631 openFolder(folderInfo);
1633 // Find the open folder...
1634 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1636 if (openFolder != null) {
1637 folderScreen = mWorkspace.getScreenForView(openFolder);
1639 closeFolder(openFolder);
1640 if (folderScreen != mWorkspace.getCurrentScreen()) {
1641 // Close any folder open on the current screen
1643 // Pull the folder onto this screen
1644 openFolder(folderInfo);
1651 * Opens the user fodler described by the specified tag. The opening of the folder
1652 * is animated relative to the specified View. If the View is null, no animation
1655 * @param folderInfo The FolderInfo describing the folder to open.
1657 private void openFolder(FolderInfo folderInfo) {
1660 if (folderInfo instanceof UserFolderInfo) {
1661 openFolder = UserFolder.fromXml(this);
1662 } else if (folderInfo instanceof LiveFolderInfo) {
1663 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1668 openFolder.setDragger(mDragLayer);
1669 openFolder.setLauncher(this);
1671 openFolder.bind(folderInfo);
1672 folderInfo.opened = true;
1674 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1675 openFolder.onOpen();
1679 * Returns true if the workspace is being loaded. When the workspace is loading,
1680 * no user interaction should be allowed to avoid any conflict.
1682 * @return True if the workspace is locked, false otherwise.
1684 boolean isWorkspaceLocked() {
1685 return mDesktopLocked;
1688 public boolean onLongClick(View v) {
1689 if (mDesktopLocked) {
1693 if (!(v instanceof CellLayout)) {
1694 v = (View) v.getParent();
1697 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1699 // This happens when long clicking an item with the dpad/trackball
1700 if (cellInfo == null) {
1704 if (mWorkspace.allowLongPress()) {
1705 if (cellInfo.cell == null) {
1706 if (cellInfo.valid) {
1707 // User long pressed on empty space
1708 mWorkspace.setAllowLongPress(false);
1709 showAddDialog(cellInfo);
1712 if (!(cellInfo.cell instanceof Folder)) {
1713 // User long pressed on an item
1714 mWorkspace.startDrag(cellInfo);
1721 static LauncherModel getModel() {
1725 void closeAllApplications() {
1729 View getDrawerHandle() {
1733 boolean isDrawerDown() {
1734 return !mDrawer.isMoving() && !mDrawer.isOpened();
1737 boolean isDrawerUp() {
1738 return mDrawer.isOpened() && !mDrawer.isMoving();
1741 boolean isDrawerMoving() {
1742 return mDrawer.isMoving();
1745 Workspace getWorkspace() {
1749 GridView getApplicationsGrid() {
1750 return mAllAppsGrid;
1754 protected Dialog onCreateDialog(int id) {
1756 case DIALOG_CREATE_SHORTCUT:
1757 return new CreateShortcut().createDialog();
1758 case DIALOG_RENAME_FOLDER:
1759 return new RenameFolder().createDialog();
1762 return super.onCreateDialog(id);
1766 protected void onPrepareDialog(int id, Dialog dialog) {
1768 case DIALOG_CREATE_SHORTCUT:
1770 case DIALOG_RENAME_FOLDER:
1771 if (mFolderInfo != null) {
1772 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1773 final CharSequence text = mFolderInfo.title;
1774 input.setText(text);
1775 input.setSelection(0, text.length());
1781 void showRenameDialog(FolderInfo info) {
1783 mWaitingForResult = true;
1784 showDialog(DIALOG_RENAME_FOLDER);
1787 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1788 mAddItemCellInfo = cellInfo;
1789 mWaitingForResult = true;
1790 showDialog(DIALOG_CREATE_SHORTCUT);
1793 private void pickShortcut(int requestCode, int title) {
1794 Bundle bundle = new Bundle();
1796 ArrayList<String> shortcutNames = new ArrayList<String>();
1797 shortcutNames.add(getString(R.string.group_applications));
1798 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1800 ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>();
1801 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1802 R.drawable.ic_launcher_application));
1803 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1805 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1806 pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT));
1807 pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title));
1808 pickIntent.putExtras(bundle);
1810 startActivityForResult(pickIntent, requestCode);
1813 private class RenameFolder {
1814 private EditText mInput;
1816 Dialog createDialog() {
1817 mWaitingForResult = true;
1818 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1819 mInput = (EditText) layout.findViewById(R.id.folder_name);
1821 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1823 builder.setTitle(getString(R.string.rename_folder_title));
1824 builder.setCancelable(true);
1825 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1826 public void onCancel(DialogInterface dialog) {
1830 builder.setNegativeButton(getString(R.string.cancel_action),
1831 new Dialog.OnClickListener() {
1832 public void onClick(DialogInterface dialog, int which) {
1837 builder.setPositiveButton(getString(R.string.rename_action),
1838 new Dialog.OnClickListener() {
1839 public void onClick(DialogInterface dialog, int which) {
1844 builder.setView(layout);
1846 final AlertDialog dialog = builder.create();
1847 dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1848 public void onShow(DialogInterface dialog) {
1856 private void changeFolderName() {
1857 final String name = mInput.getText().toString();
1858 if (!TextUtils.isEmpty(name)) {
1859 // Make sure we have the right folder info
1860 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1861 mFolderInfo.title = name;
1862 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1864 if (mDesktopLocked) {
1866 sModel.loadUserItems(false, Launcher.this, false, false);
1868 final FolderIcon folderIcon = (FolderIcon)
1869 mWorkspace.getViewForTag(mFolderInfo);
1870 if (folderIcon != null) {
1871 folderIcon.setText(name);
1872 getWorkspace().requestLayout();
1874 mDesktopLocked = true;
1876 sModel.loadUserItems(false, Launcher.this, false, false);
1883 private void cleanup() {
1884 mWorkspace.unlock();
1885 dismissDialog(DIALOG_RENAME_FOLDER);
1886 mWaitingForResult = false;
1892 * Displays the shortcut creation dialog and launches, if necessary, the
1893 * appropriate activity.
1895 private class CreateShortcut implements DialogInterface.OnClickListener,
1896 DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
1897 DialogInterface.OnShowListener {
1899 private AddAdapter mAdapter;
1901 Dialog createDialog() {
1902 mWaitingForResult = true;
1904 mAdapter = new AddAdapter(Launcher.this);
1906 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1907 builder.setTitle(getString(R.string.menu_item_add_item));
1908 builder.setAdapter(mAdapter, this);
1910 builder.setInverseBackgroundForced(true);
1912 AlertDialog dialog = builder.create();
1913 dialog.setOnCancelListener(this);
1914 dialog.setOnDismissListener(this);
1915 dialog.setOnShowListener(this);
1920 public void onCancel(DialogInterface dialog) {
1921 mWaitingForResult = false;
1925 public void onDismiss(DialogInterface dialog) {
1926 mWorkspace.unlock();
1929 private void cleanup() {
1930 mWorkspace.unlock();
1931 dismissDialog(DIALOG_CREATE_SHORTCUT);
1935 * Handle the action clicked in the "Add to home" dialog.
1937 public void onClick(DialogInterface dialog, int which) {
1938 Resources res = getResources();
1942 case AddAdapter.ITEM_SHORTCUT: {
1943 // Insert extra item to handle picking application
1944 pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut);
1948 case AddAdapter.ITEM_APPWIDGET: {
1949 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
1951 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1952 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1953 // add the search widget
1954 ArrayList<AppWidgetProviderInfo> customInfo =
1955 new ArrayList<AppWidgetProviderInfo>();
1956 AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1957 info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1958 info.label = getString(R.string.group_search);
1959 info.icon = R.drawable.ic_search_widget;
1960 customInfo.add(info);
1961 pickIntent.putParcelableArrayListExtra(
1962 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1963 ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1964 Bundle b = new Bundle();
1965 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1966 customExtras.add(b);
1967 pickIntent.putParcelableArrayListExtra(
1968 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1969 // start the pick activity
1970 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
1974 case AddAdapter.ITEM_LIVE_FOLDER: {
1975 // Insert extra item to handle inserting folder
1976 Bundle bundle = new Bundle();
1978 ArrayList<String> shortcutNames = new ArrayList<String>();
1979 shortcutNames.add(res.getString(R.string.group_folder));
1980 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1982 ArrayList<ShortcutIconResource> shortcutIcons =
1983 new ArrayList<ShortcutIconResource>();
1984 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1985 R.drawable.ic_launcher_folder));
1986 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1988 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1989 pickIntent.putExtra(Intent.EXTRA_INTENT,
1990 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
1991 pickIntent.putExtra(Intent.EXTRA_TITLE,
1992 getText(R.string.title_select_live_folder));
1993 pickIntent.putExtras(bundle);
1995 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1999 case AddAdapter.ITEM_WALLPAPER: {
2006 public void onShow(DialogInterface dialog) {
2012 * Receives notifications when applications are added/removed.
2014 private class ApplicationsIntentReceiver extends BroadcastReceiver {
2016 public void onReceive(Context context, Intent intent) {
2017 final String action = intent.getAction();
2018 final String packageName = intent.getData().getSchemeSpecificPart();
2019 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
2021 if (LauncherModel.DEBUG_LOADERS) {
2022 d(LauncherModel.LOG_TAG, "application intent received: " + action +
2023 ", replacing=" + replacing);
2024 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
2027 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2028 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
2030 removeShortcutsForPackage(packageName);
2031 if (LauncherModel.DEBUG_LOADERS) {
2032 d(LauncherModel.LOG_TAG, " --> remove package");
2034 sModel.removePackage(Launcher.this, packageName);
2036 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
2037 // later, we will update the package at this time
2040 if (LauncherModel.DEBUG_LOADERS) {
2041 d(LauncherModel.LOG_TAG, " --> add package");
2043 sModel.addPackage(Launcher.this, packageName);
2045 if (LauncherModel.DEBUG_LOADERS) {
2046 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
2048 sModel.updatePackage(Launcher.this, packageName);
2049 updateShortcutsForPackage(packageName);
2052 removeDialog(DIALOG_CREATE_SHORTCUT);
2054 if (LauncherModel.DEBUG_LOADERS) {
2055 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
2057 sModel.syncPackage(Launcher.this, packageName);
2063 * Receives notifications whenever the user favorites have changed.
2065 private class FavoritesChangeObserver extends ContentObserver {
2066 public FavoritesChangeObserver() {
2067 super(new Handler());
2071 public void onChange(boolean selfChange) {
2072 onFavoritesChanged();
2076 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
2077 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
2078 private boolean mOpen;
2080 public void onDrawerOpened() {
2082 mHandleIcon.reverseTransition(150);
2084 final Rect bounds = mWorkspace.mDrawerBounds;
2085 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
2091 private void offsetBoundsToDragLayer(Rect bounds, View view) {
2092 view.getDrawingRect(bounds);
2094 while (view != mDragLayer) {
2095 bounds.offset(view.getLeft(), view.getTop());
2096 view = (View) view.getParent();
2100 public void onDrawerClosed() {
2102 mHandleIcon.reverseTransition(150);
2103 mWorkspace.mDrawerBounds.setEmpty();
2107 mAllAppsGrid.setSelection(0);
2108 mAllAppsGrid.clearTextFilter();
2111 public void onScrollStarted() {
2112 if (PROFILE_DRAWER) {
2113 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
2116 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
2117 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
2120 public void onScrollEnded() {
2121 if (PROFILE_DRAWER) {
2122 android.os.Debug.stopMethodTracing();
2127 private static class DesktopBinder extends Handler implements MessageQueue.IdleHandler {
2128 static final int MESSAGE_BIND_ITEMS = 0x1;
2129 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
2130 static final int MESSAGE_BIND_DRAWER = 0x3;
2132 // Number of items to bind in every pass
2133 static final int ITEMS_COUNT = 6;
2135 private final ArrayList<ItemInfo> mShortcuts;
2136 private final LinkedList<LauncherAppWidgetInfo> mAppWidgets;
2137 private final ApplicationsAdapter mDrawerAdapter;
2138 private final WeakReference<Launcher> mLauncher;
2140 public boolean mTerminate = false;
2142 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
2143 ArrayList<LauncherAppWidgetInfo> appWidgets,
2144 ApplicationsAdapter drawerAdapter) {
2146 mLauncher = new WeakReference<Launcher>(launcher);
2147 mShortcuts = shortcuts;
2148 mDrawerAdapter = drawerAdapter;
2150 // Sort widgets so active workspace is bound first
2151 final int currentScreen = launcher.mWorkspace.getCurrentScreen();
2152 final int size = appWidgets.size();
2153 mAppWidgets = new LinkedList<LauncherAppWidgetInfo>();
2155 for (int i = 0; i < size; i++) {
2156 LauncherAppWidgetInfo appWidgetInfo = appWidgets.get(i);
2157 if (appWidgetInfo.screen == currentScreen) {
2158 mAppWidgets.addFirst(appWidgetInfo);
2160 mAppWidgets.addLast(appWidgetInfo);
2164 if (LauncherModel.DEBUG_LOADERS) {
2165 d(Launcher.LOG_TAG, "------> binding " + shortcuts.size() + " items");
2166 d(Launcher.LOG_TAG, "------> binding " + appWidgets.size() + " widgets");
2170 public void startBindingItems() {
2171 if (LauncherModel.DEBUG_LOADERS) d(Launcher.LOG_TAG, "------> start binding items");
2172 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
2175 public void startBindingDrawer() {
2176 obtainMessage(MESSAGE_BIND_DRAWER).sendToTarget();
2179 public void startBindingAppWidgetsWhenIdle() {
2180 // Ask for notification when message queue becomes idle
2181 final MessageQueue messageQueue = Looper.myQueue();
2182 messageQueue.addIdleHandler(this);
2185 public boolean queueIdle() {
2186 // Queue is idle, so start binding items
2187 startBindingAppWidgets();
2191 public void startBindingAppWidgets() {
2192 obtainMessage(MESSAGE_BIND_APPWIDGETS).sendToTarget();
2196 public void handleMessage(Message msg) {
2197 Launcher launcher = mLauncher.get();
2198 if (launcher == null || mTerminate) {
2203 case MESSAGE_BIND_ITEMS: {
2204 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
2207 case MESSAGE_BIND_DRAWER: {
2208 launcher.bindDrawer(this, mDrawerAdapter);
2211 case MESSAGE_BIND_APPWIDGETS: {
2212 launcher.bindAppWidgets(this, mAppWidgets);