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.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;
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;
88 * Default launcher application.
90 public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
91 static final String LOG_TAG = "Launcher";
92 static final boolean LOGD = false;
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;
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;
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;
114 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
116 static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
117 static final String SEARCH_WIDGET = "search_widget";
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;
125 private static final int DIALOG_CREATE_SHORTCUT = 1;
126 static final int DIALOG_RENAME_FOLDER = 2;
128 private static final String PREFERENCES = "launcher.preferences";
131 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
133 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
135 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
137 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
139 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
141 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
143 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
145 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
147 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
149 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
151 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
153 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
155 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
157 private static final LauncherModel sModel = new LauncherModel();
159 private static final Object sLock = new Object();
160 private static int sScreen = DEFAULT_SCREN;
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();
167 private LayoutInflater mInflater;
169 private DragLayer mDragLayer;
170 private Workspace mWorkspace;
172 private AppWidgetManager mAppWidgetManager;
173 private LauncherAppWidgetHost mAppWidgetHost;
175 static final int APPWIDGET_HOST_ID = 1024;
177 private CellLayout.CellInfo mAddItemCellInfo;
178 private CellLayout.CellInfo mMenuAddInfo;
179 private final int[] mCellCoordinates = new int[2];
180 private FolderInfo mFolderInfo;
182 private SlidingDrawer mDrawer;
183 private TransitionDrawable mHandleIcon;
184 private HandleView mHandleView;
185 private AllAppsGridView mAllAppsGrid;
187 private boolean mDesktopLocked = true;
188 private Bundle mSavedState;
190 private SpannableStringBuilder mDefaultKeySsb = null;
192 private boolean mDestroyed;
194 private boolean mIsNewIntent;
196 private boolean mRestoring;
197 private boolean mWaitingForResult;
198 private boolean mLocaleChanged;
200 private Bundle mSavedInstanceState;
202 private DesktopBinder mBinder;
205 protected void onCreate(Bundle savedInstanceState) {
206 super.onCreate(savedInstanceState);
207 mInflater = getLayoutInflater();
209 mAppWidgetManager = AppWidgetManager.getInstance(this);
211 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
212 mAppWidgetHost.startListening();
214 if (PROFILE_STARTUP) {
215 android.os.Debug.startMethodTracing("/sdcard/launcher");
218 checkForLocaleChange();
219 setWallpaperDimension();
221 setContentView(R.layout.launcher);
224 registerIntentReceivers();
225 registerContentObservers();
227 mSavedState = savedInstanceState;
228 restoreState(mSavedState);
230 if (PROFILE_STARTUP) {
231 android.os.Debug.stopMethodTracing();
238 // For handling default keys
239 mDefaultKeySsb = new SpannableStringBuilder();
240 Selection.setSelection(mDefaultKeySsb, 0);
243 private void checkForLocaleChange() {
244 final LocaleConfiguration localeConfiguration = new LocaleConfiguration();
245 readConfiguration(this, localeConfiguration);
247 final Configuration configuration = getResources().getConfiguration();
249 final String previousLocale = localeConfiguration.locale;
250 final String locale = configuration.locale.toString();
252 final int previousMcc = localeConfiguration.mcc;
253 final int mcc = configuration.mcc;
255 final int previousMnc = localeConfiguration.mnc;
256 final int mnc = configuration.mnc;
258 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
260 if (mLocaleChanged) {
261 localeConfiguration.locale = locale;
262 localeConfiguration.mcc = mcc;
263 localeConfiguration.mnc = mnc;
265 writeConfiguration(this, localeConfiguration);
269 private static class LocaleConfiguration {
270 public String locale;
275 private static void readConfiguration(Context context, LocaleConfiguration configuration) {
276 DataInputStream in = null;
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) {
284 } catch (IOException e) {
290 } catch (IOException e) {
297 private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
298 DataOutputStream out = null;
300 out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
301 out.writeUTF(configuration.locale);
302 out.writeInt(configuration.mcc);
303 out.writeInt(configuration.mnc);
305 } catch (FileNotFoundException e) {
307 } catch (IOException e) {
308 //noinspection ResultOfMethodCallIgnored
309 context.getFileStreamPath(PREFERENCES).delete();
314 } catch (IOException e) {
321 static int getScreen() {
322 synchronized (sLock) {
327 static void setScreen(int screen) {
328 synchronized (sLock) {
333 private void startLoaders() {
334 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
335 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
340 private void setWallpaperDimension() {
341 WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE);
343 Display display = getWindowManager().getDefaultDisplay();
344 boolean isPortrait = display.getWidth() < display.getHeight();
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);
352 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
353 mWaitingForResult = false;
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.
358 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
359 // launch over to the Music app to actually CREATE_SHORTCUT.
361 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
362 switch (requestCode) {
363 case REQUEST_PICK_APPLICATION:
364 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
366 case REQUEST_PICK_SHORTCUT:
367 processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT);
369 case REQUEST_CREATE_SHORTCUT:
370 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
372 case REQUEST_PICK_LIVE_FOLDER:
375 case REQUEST_CREATE_LIVE_FOLDER:
376 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
378 case REQUEST_PICK_APPWIDGET:
381 case REQUEST_CREATE_APPWIDGET:
382 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
385 } else if ((requestCode == REQUEST_PICK_APPWIDGET ||
386 requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED &&
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);
397 protected void onResume() {
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').
408 // Post to a handler so that this happens after the search dialog tries to open
410 mWorkspace.post(new Runnable() {
412 ISearchManager searchManagerService = ISearchManager.Stub.asInterface(
413 ServiceManager.getService(Context.SEARCH_SERVICE));
415 searchManagerService.stopSearch();
416 } catch (RemoteException e) {
417 e(LOG_TAG, "error stopping search", e);
423 mIsNewIntent = false;
427 protected void onPause() {
433 public Object onRetainNonConfigurationInstance() {
434 // Flag any binder to stop early before switching
435 if (mBinder != null) {
436 mBinder.mTerminate = true;
439 if (PROFILE_ROTATE) {
440 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
445 private boolean acceptFilter() {
446 final InputMethodManager inputManager = (InputMethodManager)
447 getSystemService(Context.INPUT_METHOD_SERVICE);
448 return !inputManager.isFullscreenMode();
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,
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();
471 private String getTypedText() {
472 return mDefaultKeySsb.toString();
475 private void clearTypedText() {
476 mDefaultKeySsb.clear();
477 mDefaultKeySsb.clearSpans();
478 Selection.setSelection(mDefaultKeySsb, 0);
482 * Restores the previous state, if it exists.
484 * @param savedState The previous state.
486 private void restoreState(Bundle savedState) {
487 if (savedState == null) {
491 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
492 if (currentScreen > -1) {
493 mWorkspace.setCurrentScreen(currentScreen);
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));
513 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
515 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
516 mFolderInfo = sModel.getFolderById(this, id);
522 * Finds all the views we need and configure them properly.
524 private void setupViews() {
525 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
526 final DragLayer dragLayer = mDragLayer;
528 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
529 final Workspace workspace = mWorkspace;
531 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
532 final SlidingDrawer drawer = mDrawer;
534 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
535 final AllAppsGridView grid = mAllAppsGrid;
537 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
539 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
540 mHandleView.setLauncher(this);
541 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
542 mHandleIcon.setCrossFadeEnabled(true);
545 final DrawerManager drawerManager = new DrawerManager();
546 drawer.setOnDrawerOpenListener(drawerManager);
547 drawer.setOnDrawerCloseListener(drawerManager);
548 drawer.setOnDrawerScrollListener(drawerManager);
550 grid.setTextFilterEnabled(false);
551 grid.setDragger(dragLayer);
552 grid.setLauncher(this);
554 workspace.setOnLongClickListener(this);
555 workspace.setDragger(dragLayer);
556 workspace.setLauncher(this);
558 deleteZone.setLauncher(this);
559 deleteZone.setDragController(dragLayer);
560 deleteZone.setHandle(mHandleView);
562 dragLayer.setIgnoredDropTarget(grid);
563 dragLayer.setDragScoller(workspace);
564 dragLayer.setDragListener(deleteZone);
568 * Creates a view representing a shortcut.
570 * @param info The data structure describing the shortcut.
572 * @return A View inflated from R.layout.application.
574 View createShortcut(ApplicationInfo info) {
575 return createShortcut(R.layout.application,
576 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
580 * Creates a view representing a shortcut inflated from the specified resource.
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.
586 * @return A View inflated from layoutResId.
588 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
589 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
591 if (!info.filtered) {
592 info.icon = Utilities.createIconThumbnail(info.icon, this);
593 info.filtered = true;
596 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
597 favorite.setText(info.title);
598 favorite.setTag(info);
599 favorite.setOnClickListener(this);
605 * Add an application shortcut to the workspace.
607 * @param data The intent describing the application.
608 * @param cellInfo The position on screen where to create the shortcut.
610 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
611 boolean insertAtFirst) {
612 cellInfo.screen = mWorkspace.getCurrentScreen();
613 if (!findSingleSlot(cellInfo)) return;
615 final ApplicationInfo info = infoFromApplicationIntent(context, data);
617 mWorkspace.addApplicationShortcut(info, cellInfo, insertAtFirst);
621 private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) {
622 ComponentName component = data.getComponent();
623 PackageManager packageManager = context.getPackageManager();
624 ActivityInfo activityInfo = null;
626 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
627 } catch (NameNotFoundException e) {
628 e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
631 if (activityInfo != null) {
632 ApplicationInfo itemInfo = new ApplicationInfo();
634 itemInfo.title = activityInfo.loadLabel(packageManager);
635 if (itemInfo.title == null) {
636 itemInfo.title = activityInfo.name;
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;
651 * Add a shortcut to the workspace.
653 * @param data The intent describing the shortcut.
654 * @param cellInfo The position on screen where to create the shortcut.
655 * @param insertAtFirst
657 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
658 boolean insertAtFirst) {
659 cellInfo.screen = mWorkspace.getCurrentScreen();
660 if (!findSingleSlot(cellInfo)) return;
662 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
665 sModel.addDesktopItem(info);
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);
676 * Add a widget to the workspace.
678 * @param data The intent describing the appWidgetId.
679 * @param cellInfo The position on screen where to create the widget.
681 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
682 boolean insertAtFirst) {
684 Bundle extras = data.getExtras();
685 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
687 if (LOGD) d(LOG_TAG, "dumping extras content="+extras.toString());
689 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
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);
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);
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];
707 LauncherModel.addItemToDatabase(this, launcherInfo,
708 LauncherSettings.Favorites.CONTAINER_DESKTOP,
709 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
712 sModel.addDesktopAppWidget(launcherInfo);
714 // Perform actual inflation because we're live
715 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
717 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
718 launcherInfo.hostView.setTag(launcherInfo);
720 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
721 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
722 } else if (sModel.isDesktopLoaded()) {
723 sModel.addDesktopAppWidget(launcherInfo);
727 public LauncherAppWidgetHost getAppWidgetHost() {
728 return mAppWidgetHost;
731 static ApplicationInfo addShortcut(Context context, Intent data,
732 CellLayout.CellInfo cellInfo, boolean notify) {
734 final ApplicationInfo info = infoFromShortcutIntent(context, data);
735 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
736 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
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);
746 Drawable icon = null;
747 boolean filtered = false;
748 boolean customIcon = false;
749 ShortcutIconResource iconResource = null;
751 if (bitmap != null) {
752 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
756 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
757 if (extra != null && extra instanceof ShortcutIconResource) {
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);
772 icon = context.getPackageManager().getDefaultActivityIcon();
775 final ApplicationInfo info = new ApplicationInfo();
777 info.filtered = filtered;
779 info.intent = intent;
780 info.customIcon = customIcon;
781 info.iconResource = iconResource;
786 void closeSystemDialogs() {
787 getWindow().closeAllPanels();
790 dismissDialog(DIALOG_CREATE_SHORTCUT);
791 // Unlock the workspace if the dialog was showing
793 } catch (Exception e) {
794 // An exception is thrown if the dialog is not visible, which is fine
798 dismissDialog(DIALOG_RENAME_FOLDER);
799 // Unlock the workspace if the dialog was showing
801 } catch (Exception e) {
802 // An exception is thrown if the dialog is not visible, which is fine
807 protected void onNewIntent(Intent intent) {
808 super.onNewIntent(intent);
811 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
812 closeSystemDialogs();
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.
819 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
820 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
822 if (!mWorkspace.isDefaultScreenShowing()) {
823 mWorkspace.moveToDefaultScreen();
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);
841 protected void onRestoreInstanceState(Bundle savedInstanceState) {
842 // NOTE: Do NOT do this. Ever. This is a terrible and horrifying hack.
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.
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.
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.
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.
862 // This is a bad example, do not do this.
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()
870 // The source code of these various methods shows what states should be kept to
871 // achieve what we want here.
873 Bundle windowState = savedInstanceState.getBundle("android:viewHierarchyState");
874 SparseArray<Parcelable> savedStates = null;
875 int focusedViewId = View.NO_ID;
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");
884 super.onRestoreInstanceState(savedInstanceState);
886 if (windowState != null) {
887 windowState.putSparseParcelableArray("android:views", savedStates);
888 windowState.putInt("android:focusedViewId", focusedViewId);
889 windowState.remove("android:Panels");
892 mSavedInstanceState = savedInstanceState;
896 protected void onSaveInstanceState(Bundle outState) {
897 super.onSaveInstanceState(outState);
899 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
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();
909 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
912 final boolean isConfigurationChange = getChangingConfigurations() != 0;
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);
920 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
921 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
922 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
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());
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);
942 public void onDestroy() {
948 mAppWidgetHost.stopListening();
949 } catch (NullPointerException ex) {
950 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
953 TextKeyListener.getInstance().release();
955 mAllAppsGrid.clearTextFilter();
956 mAllAppsGrid.setAdapter(null);
958 sModel.abortLoaders();
960 getContentResolver().unregisterContentObserver(mObserver);
961 getContentResolver().unregisterContentObserver(mWidgetObserver);
962 unregisterReceiver(mApplicationsReceiver);
963 unregisterReceiver(mCloseSystemDialogsReceiver);
967 public void startActivityForResult(Intent intent, int requestCode) {
968 if (requestCode >= 0) mWaitingForResult = true;
969 super.startActivityForResult(intent, requestCode);
973 public void startSearch(String initialQuery, boolean selectInitialQuery,
974 Bundle appSearchData, boolean globalSearch) {
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);
984 searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
985 // show the currently typed text in the search widget while sliding
986 searchWidget.setQuery(getTypedText());
991 * Show the search dialog immediately, without changing the search widget.
993 * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean)
995 void showSearchDialog(String initialQuery, boolean selectInitialQuery,
996 Bundle appSearchData, boolean globalSearch) {
998 if (initialQuery == null) {
999 // Use any text typed in the launcher as the initial query
1000 initialQuery = getTypedText();
1003 if (appSearchData == null) {
1004 appSearchData = new Bundle();
1005 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
1008 final SearchManager searchManager =
1009 (SearchManager) getSystemService(Context.SEARCH_SERVICE);
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
1015 searchManager.setOnCancelListener(new SearchManager.OnCancelListener() {
1016 public void onCancel() {
1017 searchManager.setOnCancelListener(null);
1023 searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(),
1024 appSearchData, globalSearch);
1028 * Cancel search dialog if it is open.
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);
1042 public boolean onCreateOptionsMenu(Menu menu) {
1043 if (mDesktopLocked && mSavedInstanceState == null) return false;
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');
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);
1063 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
1064 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
1065 .setIntent(settings);
1071 public boolean onPrepareOptionsMenu(Menu menu) {
1072 super.onPrepareOptionsMenu(menu);
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);
1083 public boolean onOptionsItemSelected(MenuItem item) {
1084 switch (item.getItemId()) {
1088 case MENU_WALLPAPER_SETTINGS:
1092 onSearchRequested();
1094 case MENU_NOTIFICATIONS:
1095 showNotifications();
1099 return super.onOptionsItemSelected(item);
1103 * Indicates that we want global search for this activity by setting the globalSearch
1104 * argument for {@link #startSearch} to true.
1108 public boolean onSearchRequested() {
1109 startSearch(null, false, null, true);
1113 private void addItems() {
1114 showAddDialog(mMenuAddInfo);
1117 private void removeShortcutsForPackage(String packageName) {
1118 if (packageName != null && packageName.length() > 0) {
1119 mWorkspace.removeShortcutsForPackage(packageName);
1123 private void updateShortcutsForPackage(String packageName) {
1124 if (packageName != null && packageName.length() > 0) {
1125 mWorkspace.updateShortcutsForPackage(packageName);
1129 void addAppWidget(Intent data) {
1130 // TODO: catch bad widget exception when sent
1131 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
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
1140 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
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);
1148 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
1150 // Otherwise just add it
1151 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
1157 final Widget info = Widget.makeSearch();
1158 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1160 final int[] xy = mCellCoordinates;
1161 final int spanX = info.spanX;
1162 final int spanY = info.spanY;
1164 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
1166 sModel.addDesktopItem(info);
1167 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1168 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
1170 final View view = mInflater.inflate(info.layoutResource, null);
1172 Search search = (Search) view.findViewById(R.id.widget_search);
1173 search.setLauncher(this);
1175 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
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);
1183 if (applicationName != null && applicationName.equals(shortcutName)) {
1184 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1185 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1187 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1188 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1189 startActivityForResult(pickIntent, requestCodeApplication);
1191 startActivityForResult(intent, requestCodeShortcut);
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);
1200 if (folderName != null && folderName.equals(shortcutName)) {
1201 addFolder(!mDesktopLocked);
1203 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1207 void addFolder(boolean insertAtFirst) {
1208 UserFolderInfo folderInfo = new UserFolderInfo();
1209 folderInfo.title = getText(R.string.folder_name);
1211 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1212 cellInfo.screen = mWorkspace.getCurrentScreen();
1213 if (!findSingleSlot(cellInfo)) return;
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);
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);
1228 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
1229 boolean insertAtFirst) {
1230 cellInfo.screen = mWorkspace.getCurrentScreen();
1231 if (!findSingleSlot(cellInfo)) return;
1233 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1236 sModel.addDesktopItem(info);
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);
1246 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1247 CellLayout.CellInfo cellInfo, boolean notify) {
1249 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1250 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1252 Drawable icon = null;
1253 boolean filtered = false;
1254 Intent.ShortcutIconResource iconResource = null;
1256 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1257 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
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);
1271 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1274 final LiveFolderInfo info = new LiveFolderInfo();
1276 info.filtered = filtered;
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);
1284 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1285 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1286 sModel.addFolder(info);
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];
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();
1314 private void showNotifications() {
1315 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1316 if (statusBar != null) {
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 });
1334 startActivity(chooser);
1338 * Registers various intent receivers. The current implementation registers
1339 * only a wallpaper intent receiver to let other applications change the
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);
1353 * Registers various content observers. The current implementation registers
1354 * only a favorites observer to keep track of the favorites applications.
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);
1364 public boolean dispatchKeyEvent(KeyEvent event) {
1365 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1366 switch (event.getKeyCode()) {
1367 case KeyEvent.KEYCODE_BACK:
1369 case KeyEvent.KEYCODE_HOME:
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()) {
1384 case KeyEvent.KEYCODE_HOME:
1389 return super.dispatchKeyEvent(event);
1392 private void closeDrawer() {
1396 private void closeDrawer(boolean animated) {
1397 if (mDrawer.isOpened()) {
1399 mDrawer.animateClose();
1403 if (mDrawer.hasFocus()) {
1404 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1409 private void closeFolder() {
1410 Folder folder = mWorkspace.getOpenFolder();
1411 if (folder != null) {
1412 closeFolder(folder);
1416 void closeFolder(Folder folder) {
1417 folder.getInfo().opened = false;
1418 ViewGroup parent = (ViewGroup) folder.getParent();
1419 if (parent != null) {
1420 parent.removeView(folder);
1426 * When the notification that favorites have changed is received, requests
1427 * a favorites list refresh.
1429 private void onFavoritesChanged() {
1430 mDesktopLocked = true;
1432 sModel.loadUserItems(false, this, false, false);
1436 * Re-listen when widgets are reset.
1438 private void onAppWidgetReset() {
1439 mAppWidgetHost.startListening();
1442 void onDesktopItemsLoaded(ArrayList<ItemInfo> shortcuts,
1443 ArrayList<LauncherAppWidgetInfo> appWidgets) {
1445 if (LauncherModel.DEBUG_LOADERS) {
1446 d(LauncherModel.LOG_TAG, " ------> destroyed, ignoring desktop items");
1450 bindDesktopItems(shortcuts, appWidgets);
1454 * Refreshes the shortcuts shown on the workspace.
1456 private void bindDesktopItems(ArrayList<ItemInfo> shortcuts,
1457 ArrayList<LauncherAppWidgetInfo> appWidgets) {
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");
1465 final Workspace workspace = mWorkspace;
1466 int count = workspace.getChildCount();
1467 for (int i = 0; i < count; i++) {
1468 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
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);
1476 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1477 public void onClick(View v) {
1483 // Flag any old binder to terminate early
1484 if (mBinder != null) {
1485 mBinder.mTerminate = true;
1488 mBinder = new DesktopBinder(this, shortcuts, appWidgets, drawerAdapter);
1489 mBinder.startBindingItems();
1492 private void bindItems(Launcher.DesktopBinder binder,
1493 ArrayList<ItemInfo> shortcuts, int start, int count) {
1495 final Workspace workspace = mWorkspace;
1496 final boolean desktopLocked = mDesktopLocked;
1498 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
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,
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,
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,
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);
1530 Search search = (Search) view.findViewById(R.id.widget_search);
1531 search.setLauncher(this);
1533 final Widget widget = (Widget) item;
1534 view.setTag(widget);
1536 workspace.addWidget(view, widget, !desktopLocked);
1541 workspace.requestLayout();
1544 finishBindDesktopItems();
1545 binder.startBindingDrawer();
1547 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1551 private void finishBindDesktopItems() {
1552 if (mSavedState != null) {
1553 if (!mWorkspace.hasFocus()) {
1554 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
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);
1565 final Folder openFolder = mWorkspace.getOpenFolder();
1566 if (openFolder != null) {
1567 openFolder.requestFocus();
1571 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1579 if (mSavedInstanceState != null) {
1580 super.onRestoreInstanceState(mSavedInstanceState);
1581 mSavedInstanceState = null;
1584 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1585 mDrawer.requestFocus();
1588 mDesktopLocked = false;
1592 private void bindDrawer(Launcher.DesktopBinder binder,
1593 ApplicationsAdapter drawerAdapter) {
1594 mAllAppsGrid.setAdapter(drawerAdapter);
1595 binder.startBindingAppWidgetsWhenIdle();
1598 private void bindAppWidgets(Launcher.DesktopBinder binder,
1599 LinkedList<LauncherAppWidgetInfo> appWidgets) {
1601 final Workspace workspace = mWorkspace;
1602 final boolean desktopLocked = mDesktopLocked;
1604 if (!appWidgets.isEmpty()) {
1605 final LauncherAppWidgetInfo item = appWidgets.removeFirst();
1607 final int appWidgetId = item.appWidgetId;
1608 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1609 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1612 d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s",
1613 appWidgetId, appWidgetInfo));
1616 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1617 item.hostView.setTag(item);
1619 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1620 item.cellY, item.spanX, item.spanY, !desktopLocked);
1622 workspace.requestLayout();
1625 if (appWidgets.isEmpty()) {
1626 if (PROFILE_ROTATE) {
1627 android.os.Debug.stopMethodTracing();
1630 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
1635 * Launches the intent referred by the clicked shortcut.
1637 * @param v The view representing the clicked shortcut.
1639 public void onClick(View v) {
1640 Object tag = v.getTag();
1641 if (tag instanceof ApplicationInfo) {
1643 final Intent intent = ((ApplicationInfo) tag).intent;
1644 startActivitySafely(intent);
1645 } else if (tag instanceof FolderInfo) {
1646 handleFolderClick((FolderInfo) tag);
1650 void startActivitySafely(Intent intent) {
1651 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
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);
1664 private void handleFolderClick(FolderInfo folderInfo) {
1665 if (!folderInfo.opened) {
1666 // Close any open folder
1668 // Open the requested folder
1669 openFolder(folderInfo);
1671 // Find the open folder...
1672 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1674 if (openFolder != null) {
1675 folderScreen = mWorkspace.getScreenForView(openFolder);
1677 closeFolder(openFolder);
1678 if (folderScreen != mWorkspace.getCurrentScreen()) {
1679 // Close any folder open on the current screen
1681 // Pull the folder onto this screen
1682 openFolder(folderInfo);
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
1693 * @param folderInfo The FolderInfo describing the folder to open.
1695 private void openFolder(FolderInfo folderInfo) {
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);
1706 openFolder.setDragger(mDragLayer);
1707 openFolder.setLauncher(this);
1709 openFolder.bind(folderInfo);
1710 folderInfo.opened = true;
1712 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1713 openFolder.onOpen();
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.
1720 * @return True if the workspace is locked, false otherwise.
1722 boolean isWorkspaceLocked() {
1723 return mDesktopLocked;
1726 public boolean onLongClick(View v) {
1727 if (mDesktopLocked) {
1731 if (!(v instanceof CellLayout)) {
1732 v = (View) v.getParent();
1735 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1737 // This happens when long clicking an item with the dpad/trackball
1738 if (cellInfo == null) {
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);
1750 if (!(cellInfo.cell instanceof Folder)) {
1751 // User long pressed on an item
1752 mWorkspace.startDrag(cellInfo);
1759 static LauncherModel getModel() {
1763 void closeAllApplications() {
1767 View getDrawerHandle() {
1771 boolean isDrawerDown() {
1772 return !mDrawer.isMoving() && !mDrawer.isOpened();
1775 boolean isDrawerUp() {
1776 return mDrawer.isOpened() && !mDrawer.isMoving();
1779 boolean isDrawerMoving() {
1780 return mDrawer.isMoving();
1783 Workspace getWorkspace() {
1787 GridView getApplicationsGrid() {
1788 return mAllAppsGrid;
1792 protected Dialog onCreateDialog(int id) {
1794 case DIALOG_CREATE_SHORTCUT:
1795 return new CreateShortcut().createDialog();
1796 case DIALOG_RENAME_FOLDER:
1797 return new RenameFolder().createDialog();
1800 return super.onCreateDialog(id);
1804 protected void onPrepareDialog(int id, Dialog dialog) {
1806 case DIALOG_CREATE_SHORTCUT:
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());
1819 void showRenameDialog(FolderInfo info) {
1821 mWaitingForResult = true;
1822 showDialog(DIALOG_RENAME_FOLDER);
1825 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1826 mAddItemCellInfo = cellInfo;
1827 mWaitingForResult = true;
1828 showDialog(DIALOG_CREATE_SHORTCUT);
1831 private void pickShortcut(int requestCode, int title) {
1832 Bundle bundle = new Bundle();
1834 ArrayList<String> shortcutNames = new ArrayList<String>();
1835 shortcutNames.add(getString(R.string.group_applications));
1836 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
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);
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);
1848 startActivityForResult(pickIntent, requestCode);
1851 private class RenameFolder {
1852 private EditText mInput;
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);
1859 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
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) {
1868 builder.setNegativeButton(getString(R.string.cancel_action),
1869 new Dialog.OnClickListener() {
1870 public void onClick(DialogInterface dialog, int which) {
1875 builder.setPositiveButton(getString(R.string.rename_action),
1876 new Dialog.OnClickListener() {
1877 public void onClick(DialogInterface dialog, int which) {
1882 builder.setView(layout);
1884 final AlertDialog dialog = builder.create();
1885 dialog.setOnShowListener(new DialogInterface.OnShowListener() {
1886 public void onShow(DialogInterface dialog) {
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);
1902 if (mDesktopLocked) {
1904 sModel.loadUserItems(false, Launcher.this, false, false);
1906 final FolderIcon folderIcon = (FolderIcon)
1907 mWorkspace.getViewForTag(mFolderInfo);
1908 if (folderIcon != null) {
1909 folderIcon.setText(name);
1910 getWorkspace().requestLayout();
1912 mDesktopLocked = true;
1914 sModel.loadUserItems(false, Launcher.this, false, false);
1921 private void cleanup() {
1922 mWorkspace.unlock();
1923 dismissDialog(DIALOG_RENAME_FOLDER);
1924 mWaitingForResult = false;
1930 * Displays the shortcut creation dialog and launches, if necessary, the
1931 * appropriate activity.
1933 private class CreateShortcut implements DialogInterface.OnClickListener,
1934 DialogInterface.OnCancelListener, DialogInterface.OnDismissListener,
1935 DialogInterface.OnShowListener {
1937 private AddAdapter mAdapter;
1939 Dialog createDialog() {
1940 mWaitingForResult = true;
1942 mAdapter = new AddAdapter(Launcher.this);
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);
1948 builder.setInverseBackgroundForced(true);
1950 AlertDialog dialog = builder.create();
1951 dialog.setOnCancelListener(this);
1952 dialog.setOnDismissListener(this);
1953 dialog.setOnShowListener(this);
1958 public void onCancel(DialogInterface dialog) {
1959 mWaitingForResult = false;
1963 public void onDismiss(DialogInterface dialog) {
1964 mWorkspace.unlock();
1967 private void cleanup() {
1968 mWorkspace.unlock();
1969 dismissDialog(DIALOG_CREATE_SHORTCUT);
1973 * Handle the action clicked in the "Add to home" dialog.
1975 public void onClick(DialogInterface dialog, int which) {
1976 Resources res = getResources();
1980 case AddAdapter.ITEM_SHORTCUT: {
1981 // Insert extra item to handle picking application
1982 pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut);
1986 case AddAdapter.ITEM_APPWIDGET: {
1987 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
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);
2012 case AddAdapter.ITEM_LIVE_FOLDER: {
2013 // Insert extra item to handle inserting folder
2014 Bundle bundle = new Bundle();
2016 ArrayList<String> shortcutNames = new ArrayList<String>();
2017 shortcutNames.add(res.getString(R.string.group_folder));
2018 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
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);
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);
2033 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
2037 case AddAdapter.ITEM_WALLPAPER: {
2044 public void onShow(DialogInterface dialog) {
2050 * Receives notifications when applications are added/removed.
2052 private class ApplicationsIntentReceiver extends BroadcastReceiver {
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);
2059 if (LauncherModel.DEBUG_LOADERS) {
2060 d(LauncherModel.LOG_TAG, "application intent received: " + action +
2061 ", replacing=" + replacing);
2062 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
2065 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
2066 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
2068 removeShortcutsForPackage(packageName);
2069 if (LauncherModel.DEBUG_LOADERS) {
2070 d(LauncherModel.LOG_TAG, " --> remove package");
2072 sModel.removePackage(Launcher.this, packageName);
2074 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
2075 // later, we will update the package at this time
2078 if (LauncherModel.DEBUG_LOADERS) {
2079 d(LauncherModel.LOG_TAG, " --> add package");
2081 sModel.addPackage(Launcher.this, packageName);
2083 if (LauncherModel.DEBUG_LOADERS) {
2084 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
2086 sModel.updatePackage(Launcher.this, packageName);
2087 updateShortcutsForPackage(packageName);
2090 removeDialog(DIALOG_CREATE_SHORTCUT);
2092 if (LauncherModel.DEBUG_LOADERS) {
2093 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
2095 sModel.syncPackage(Launcher.this, packageName);
2101 * Receives notifications when applications are added/removed.
2103 private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver {
2105 public void onReceive(Context context, Intent intent) {
2106 closeSystemDialogs();
2111 * Receives notifications whenever the user favorites have changed.
2113 private class FavoritesChangeObserver extends ContentObserver {
2114 public FavoritesChangeObserver() {
2115 super(new Handler());
2119 public void onChange(boolean selfChange) {
2120 onFavoritesChanged();
2125 * Receives notifications whenever the appwidgets are reset.
2127 private class AppWidgetResetObserver extends ContentObserver {
2128 public AppWidgetResetObserver() {
2129 super(new Handler());
2133 public void onChange(boolean selfChange) {
2138 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
2139 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
2140 private boolean mOpen;
2142 public void onDrawerOpened() {
2144 mHandleIcon.reverseTransition(150);
2146 final Rect bounds = mWorkspace.mDrawerBounds;
2147 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
2153 private void offsetBoundsToDragLayer(Rect bounds, View view) {
2154 view.getDrawingRect(bounds);
2156 while (view != mDragLayer) {
2157 bounds.offset(view.getLeft(), view.getTop());
2158 view = (View) view.getParent();
2162 public void onDrawerClosed() {
2164 mHandleIcon.reverseTransition(150);
2165 mWorkspace.mDrawerBounds.setEmpty();
2169 mAllAppsGrid.setSelection(0);
2170 mAllAppsGrid.clearTextFilter();
2173 public void onScrollStarted() {
2174 if (PROFILE_DRAWER) {
2175 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
2178 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
2179 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
2182 public void onScrollEnded() {
2183 if (PROFILE_DRAWER) {
2184 android.os.Debug.stopMethodTracing();
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;
2194 // Number of items to bind in every pass
2195 static final int ITEMS_COUNT = 6;
2197 private final ArrayList<ItemInfo> mShortcuts;
2198 private final LinkedList<LauncherAppWidgetInfo> mAppWidgets;
2199 private final ApplicationsAdapter mDrawerAdapter;
2200 private final WeakReference<Launcher> mLauncher;
2202 public boolean mTerminate = false;
2204 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
2205 ArrayList<LauncherAppWidgetInfo> appWidgets,
2206 ApplicationsAdapter drawerAdapter) {
2208 mLauncher = new WeakReference<Launcher>(launcher);
2209 mShortcuts = shortcuts;
2210 mDrawerAdapter = drawerAdapter;
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>();
2217 for (int i = 0; i < size; i++) {
2218 LauncherAppWidgetInfo appWidgetInfo = appWidgets.get(i);
2219 if (appWidgetInfo.screen == currentScreen) {
2220 mAppWidgets.addFirst(appWidgetInfo);
2222 mAppWidgets.addLast(appWidgetInfo);
2226 if (LauncherModel.DEBUG_LOADERS) {
2227 d(Launcher.LOG_TAG, "------> binding " + shortcuts.size() + " items");
2228 d(Launcher.LOG_TAG, "------> binding " + appWidgets.size() + " widgets");
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();
2237 public void startBindingDrawer() {
2238 obtainMessage(MESSAGE_BIND_DRAWER).sendToTarget();
2241 public void startBindingAppWidgetsWhenIdle() {
2242 // Ask for notification when message queue becomes idle
2243 final MessageQueue messageQueue = Looper.myQueue();
2244 messageQueue.addIdleHandler(this);
2247 public boolean queueIdle() {
2248 // Queue is idle, so start binding items
2249 startBindingAppWidgets();
2253 public void startBindingAppWidgets() {
2254 obtainMessage(MESSAGE_BIND_APPWIDGETS).sendToTarget();
2258 public void handleMessage(Message msg) {
2259 Launcher launcher = mLauncher.get();
2260 if (launcher == null || mTerminate) {
2265 case MESSAGE_BIND_ITEMS: {
2266 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
2269 case MESSAGE_BIND_DRAWER: {
2270 launcher.bindDrawer(this, mDrawerAdapter);
2273 case MESSAGE_BIND_APPWIDGETS: {
2274 launcher.bindAppWidgets(this, mAppWidgets);