blob: 50c785d0859bba54cbfe9ddc5400cb595c215d76 [file] [log] [blame]
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.launcher;
18
19import android.app.Activity;
20import android.app.AlertDialog;
21import android.app.Application;
22import android.app.Dialog;
23import android.app.SearchManager;
24import android.app.StatusBarManager;
25import android.content.ActivityNotFoundException;
26import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.SharedPreferences;
34import android.content.pm.ActivityInfo;
35import android.content.pm.PackageManager;
36import android.content.pm.PackageManager.NameNotFoundException;
37import android.content.res.Resources;
38import android.content.res.Configuration;
39import android.database.ContentObserver;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080040import android.graphics.Bitmap;
41import android.graphics.Rect;
42import android.graphics.drawable.BitmapDrawable;
43import android.graphics.drawable.Drawable;
44import android.graphics.drawable.TransitionDrawable;
45import android.net.Uri;
46import android.os.Bundle;
47import android.os.Handler;
48import android.os.IBinder;
49import android.os.Parcelable;
50import android.os.RemoteException;
51import android.os.ServiceManager;
52import android.os.Message;
53import android.provider.*;
54import android.telephony.PhoneNumberUtils;
55import android.text.Selection;
56import android.text.SpannableStringBuilder;
57import android.text.TextUtils;
58import android.text.method.TextKeyListener;
59import android.util.Log;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070060import static android.util.Log.*;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080061import android.view.Display;
62import android.view.Gravity;
63import android.view.KeyEvent;
64import android.view.LayoutInflater;
65import android.view.Menu;
66import android.view.MenuItem;
67import android.view.View;
68import android.view.ViewGroup;
69import android.view.WindowManager;
70import android.view.View.OnLongClickListener;
71import android.view.inputmethod.InputMethodManager;
72import android.widget.AdapterView;
73import android.widget.EditText;
74import android.widget.ListView;
75import android.widget.TextView;
76import android.widget.Toast;
77import android.widget.GridView;
78import android.widget.SlidingDrawer;
79import android.app.IWallpaperService;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070080import android.appwidget.AppWidgetManager;
81import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080082
83import java.lang.ref.WeakReference;
84import java.util.ArrayList;
85
86/**
87 * Default launcher application.
88 */
89public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
90 static final String LOG_TAG = "Launcher";
91 static final boolean LOGD = false;
92
93 private static final boolean PROFILE_STARTUP = false;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070094 private static final boolean PROFILE_DRAWER = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080095 private static final boolean DEBUG_USER_INTERFACE = false;
96
97 private static final int WALLPAPER_SCREENS_SPAN = 2;
98
99 private static final int MENU_GROUP_ADD = 1;
100 private static final int MENU_ADD = Menu.FIRST + 1;
101 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
102 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
103 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
104 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
105
106 private static final int REQUEST_CREATE_SHORTCUT = 1;
107 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700108 private static final int REQUEST_CREATE_APPWIDGET = 5;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800109 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;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700112 private static final int REQUEST_PICK_APPWIDGET = 9;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800113
114 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
115
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700116 static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
117 static final String SEARCH_WIDGET = "search_widget";
118
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119 static final int SCREEN_COUNT = 3;
120 static final int DEFAULT_SCREN = 1;
121 static final int NUMBER_CELLS_X = 4;
122 static final int NUMBER_CELLS_Y = 4;
123
124 private static final int DIALOG_CREATE_SHORTCUT = 1;
125 static final int DIALOG_RENAME_FOLDER = 2;
126
127 private static final String PREFERENCES = "launcher";
128 private static final String KEY_LOCALE = "locale";
129 private static final String KEY_MCC = "mcc";
130 private static final String KEY_MNC = "mnc";
131
132 // Type: int
133 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
134 // Type: boolean
135 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
136 // Type: long
137 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
138 // Type: int
139 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
140 // Type: int
141 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
142 // Type: int
143 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
144 // Type: int
145 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
146 // Type: int
147 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
148 // Type: int
149 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
150 // Type: int
151 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
152 // Type: int[]
153 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
154 // Type: boolean
155 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
156 // Type: long
157 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
158
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700159 private static final LauncherModel sModel = new LauncherModel();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800160
161 private static Bitmap sWallpaper;
162
163 private static final Object sLock = new Object();
164 private static int sScreen = DEFAULT_SCREN;
165
166 private static WallpaperIntentReceiver sWallpaperReceiver;
167
168 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
169 private final ContentObserver mObserver = new FavoritesChangeObserver();
170
171 private LayoutInflater mInflater;
172
173 private DragLayer mDragLayer;
174 private Workspace mWorkspace;
175
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700176 private AppWidgetManager mAppWidgetManager;
177 private LauncherAppWidgetHost mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800178
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700179 static final int APPWIDGET_HOST_ID = 1024;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180
181 private CellLayout.CellInfo mAddItemCellInfo;
182 private CellLayout.CellInfo mMenuAddInfo;
183 private final int[] mCellCoordinates = new int[2];
184 private FolderInfo mFolderInfo;
185
186 private SlidingDrawer mDrawer;
187 private TransitionDrawable mHandleIcon;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700188 private HandleView mHandleView;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800189 private AllAppsGridView mAllAppsGrid;
190
191 private boolean mDesktopLocked = true;
192 private Bundle mSavedState;
193
194 private SpannableStringBuilder mDefaultKeySsb = null;
195
196 private boolean mDestroyed;
197
198 private boolean mRestoring;
199 private boolean mWaitingForResult;
200 private boolean mLocaleChanged;
201
202 private Bundle mSavedInstanceState;
203
204 @Override
205 protected void onCreate(Bundle savedInstanceState) {
206 super.onCreate(savedInstanceState);
207 mInflater = getLayoutInflater();
208
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700209 mAppWidgetManager = AppWidgetManager.getInstance(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800210
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700211 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
212 mAppWidgetHost.startListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800213
214 if (PROFILE_STARTUP) {
215 android.os.Debug.startMethodTracing("/sdcard/launcher");
216 }
217
218 checkForLocaleChange();
219 setWallpaperDimension();
220
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221 setContentView(R.layout.launcher);
222 setupViews();
223
224 registerIntentReceivers();
225 registerContentObservers();
226
227 mSavedState = savedInstanceState;
228 restoreState(mSavedState);
229
230 if (PROFILE_STARTUP) {
231 android.os.Debug.stopMethodTracing();
232 }
233
234 if (!mRestoring) {
235 startLoaders();
236 }
237
238 // For handling default keys
239 mDefaultKeySsb = new SpannableStringBuilder();
240 Selection.setSelection(mDefaultKeySsb, 0);
241 }
242
243 private void checkForLocaleChange() {
244 final SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
245 final Configuration configuration = getResources().getConfiguration();
246
247 final String previousLocale = preferences.getString(KEY_LOCALE, null);
248 final String locale = configuration.locale.toString();
249
250 final int previousMcc = preferences.getInt(KEY_MCC, -1);
251 final int mcc = configuration.mcc;
252
253 final int previousMnc = preferences.getInt(KEY_MNC, -1);
254 final int mnc = configuration.mnc;
255
256 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
257
258 if (mLocaleChanged) {
259 final SharedPreferences.Editor editor = preferences.edit();
260 editor.putString(KEY_LOCALE, locale);
261 editor.putInt(KEY_MCC, mcc);
262 editor.putInt(KEY_MNC, mnc);
263 editor.commit();
264 }
265 }
266
267 static int getScreen() {
268 synchronized (sLock) {
269 return sScreen;
270 }
271 }
272
273 static void setScreen(int screen) {
274 synchronized (sLock) {
275 sScreen = screen;
276 }
277 }
278
279 private void startLoaders() {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700280 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
281 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
282
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800283 mRestoring = false;
284 }
285
286 private void setWallpaperDimension() {
287 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
288 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
289
290 Display display = getWindowManager().getDefaultDisplay();
291 boolean isPortrait = display.getWidth() < display.getHeight();
292
293 final int width = isPortrait ? display.getWidth() : display.getHeight();
294 final int height = isPortrait ? display.getHeight() : display.getWidth();
295 try {
296 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
297 } catch (RemoteException e) {
298 // System is dead!
299 }
300 }
301
302 @Override
303 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
304 // The pattern used here is that a user PICKs a specific application,
305 // which, depending on the target, might need to CREATE the actual target.
306
307 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
308 // launch over to the Music app to actually CREATE_SHORTCUT.
309
310 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
311 switch (requestCode) {
312 case REQUEST_PICK_APPLICATION:
313 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
314 break;
315 case REQUEST_PICK_SHORTCUT:
316 addShortcut(data);
317 break;
318 case REQUEST_CREATE_SHORTCUT:
319 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
320 break;
321 case REQUEST_PICK_LIVE_FOLDER:
322 addLiveFolder(data);
323 break;
324 case REQUEST_CREATE_LIVE_FOLDER:
325 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
326 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700327 case REQUEST_PICK_APPWIDGET:
328 addAppWidget(data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800329 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700330 case REQUEST_CREATE_APPWIDGET:
331 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800332 break;
333 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700334 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 resultCode == RESULT_CANCELED && data != null) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700336 // Clean up the appWidgetId if we canceled
337 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
338 if (appWidgetId != -1) {
339 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800340 }
341 }
342 mWaitingForResult = false;
343 }
344
345 @Override
346 protected void onResume() {
347 super.onResume();
348
349 if (mRestoring) {
350 startLoaders();
351 }
352 }
353
354 @Override
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700355 protected void onPause() {
356 super.onPause();
357 closeDrawer(false);
358 }
359
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800360 private boolean acceptFilter() {
361 final InputMethodManager inputManager = (InputMethodManager)
362 getSystemService(Context.INPUT_METHOD_SERVICE);
363 return !inputManager.isFullscreenMode();
364 }
365
366 @Override
367 public boolean onKeyDown(int keyCode, KeyEvent event) {
368 boolean handled = super.onKeyDown(keyCode, event);
369 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
370 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
371 keyCode, event);
372 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
373 // something usable has been typed - dispatch it now.
374 final String str = mDefaultKeySsb.toString();
375
376 boolean isDialable = true;
377 final int count = str.length();
378 for (int i = 0; i < count; i++) {
379 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
380 isDialable = false;
381 break;
382 }
383 }
384 Intent intent;
385 if (isDialable) {
386 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
387 } else {
388 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
389 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
390 }
391
392 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
393
394 try {
395 startActivity(intent);
396 } catch (android.content.ActivityNotFoundException ex) {
397 // Oh well... no one knows how to filter/dial. Life goes on.
398 }
399
400 mDefaultKeySsb.clear();
401 mDefaultKeySsb.clearSpans();
402 Selection.setSelection(mDefaultKeySsb, 0);
403
404 return true;
405 }
406 }
407
408 return handled;
409 }
410
411 /**
412 * Restores the previous state, if it exists.
413 *
414 * @param savedState The previous state.
415 */
416 private void restoreState(Bundle savedState) {
417 if (savedState == null) {
418 return;
419 }
420
421 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
422 if (currentScreen > -1) {
423 mWorkspace.setCurrentScreen(currentScreen);
424 }
425
426 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
427 if (addScreen > -1) {
428 mAddItemCellInfo = new CellLayout.CellInfo();
429 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
430 addItemCellInfo.valid = true;
431 addItemCellInfo.screen = addScreen;
432 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
433 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
434 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
435 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
436 addItemCellInfo.findVacantCellsFromOccupied(
437 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
438 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
439 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
440 mRestoring = true;
441 }
442
443 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
444 if (renameFolder) {
445 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
446 mFolderInfo = sModel.getFolderById(this, id);
447 mRestoring = true;
448 }
449 }
450
451 /**
452 * Finds all the views we need and configure them properly.
453 */
454 private void setupViews() {
455 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
456 final DragLayer dragLayer = mDragLayer;
457
458 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
459 final Workspace workspace = mWorkspace;
460
461 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
462 final SlidingDrawer drawer = mDrawer;
463
464 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
465 final AllAppsGridView grid = mAllAppsGrid;
466
467 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
468
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700469 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
470 mHandleView.setLauncher(this);
471 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800472 mHandleIcon.setCrossFadeEnabled(true);
473
474 drawer.lock();
475 final DrawerManager drawerManager = new DrawerManager();
476 drawer.setOnDrawerOpenListener(drawerManager);
477 drawer.setOnDrawerCloseListener(drawerManager);
478 drawer.setOnDrawerScrollListener(drawerManager);
479
480 grid.setTextFilterEnabled(true);
481 grid.setDragger(dragLayer);
482 grid.setLauncher(this);
483
484 workspace.setOnLongClickListener(this);
485 workspace.setDragger(dragLayer);
486 workspace.setLauncher(this);
487 loadWallpaper();
488
489 deleteZone.setLauncher(this);
490 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700491 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800492
493 dragLayer.setIgnoredDropTarget(grid);
494 dragLayer.setDragScoller(workspace);
495 dragLayer.setDragListener(deleteZone);
496 }
497
498 /**
499 * Creates a view representing a shortcut.
500 *
501 * @param info The data structure describing the shortcut.
502 *
503 * @return A View inflated from R.layout.application.
504 */
505 View createShortcut(ApplicationInfo info) {
506 return createShortcut(R.layout.application,
507 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
508 }
509
510 /**
511 * Creates a view representing a shortcut inflated from the specified resource.
512 *
513 * @param layoutResId The id of the XML layout used to create the shortcut.
514 * @param parent The group the shortcut belongs to.
515 * @param info The data structure describing the shortcut.
516 *
517 * @return A View inflated from layoutResId.
518 */
519 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
520 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
521
522 if (!info.filtered) {
523 info.icon = Utilities.createIconThumbnail(info.icon, this);
524 info.filtered = true;
525 }
526
527 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
528 favorite.setText(info.title);
529 favorite.setTag(info);
530 favorite.setOnClickListener(this);
531
532 return favorite;
533 }
534
535 /**
536 * Add an application shortcut to the workspace.
537 *
538 * @param data The intent describing the application.
539 * @param cellInfo The position on screen where to create the shortcut.
540 */
541 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
542 boolean insertAtFirst) {
543 cellInfo.screen = mWorkspace.getCurrentScreen();
544 if (!findSingleSlot(cellInfo)) return;
545
546 // Find details for this application
547 ComponentName component = data.getComponent();
548 PackageManager packageManager = context.getPackageManager();
549 ActivityInfo activityInfo = null;
550 try {
551 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
552 } catch (NameNotFoundException e) {
553 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
554 }
555
556 if (activityInfo != null) {
557 ApplicationInfo itemInfo = new ApplicationInfo();
558
559 itemInfo.title = activityInfo.loadLabel(packageManager);
560 if (itemInfo.title == null) {
561 itemInfo.title = activityInfo.name;
562 }
563
564 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
565 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
566 itemInfo.icon = activityInfo.loadIcon(packageManager);
567 itemInfo.container = ItemInfo.NO_ID;
568
569 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
570 }
571 }
572
573 /**
574 * Add a shortcut to the workspace.
575 *
576 * @param data The intent describing the shortcut.
577 * @param cellInfo The position on screen where to create the shortcut.
578 * @param insertAtFirst
579 */
580 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
581 boolean insertAtFirst) {
582 cellInfo.screen = mWorkspace.getCurrentScreen();
583 if (!findSingleSlot(cellInfo)) return;
584
585 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
586
587 if (!mRestoring) {
588 sModel.addDesktopItem(info);
589
590 final View view = createShortcut(info);
591 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
592 } else if (sModel.isDesktopLoaded()) {
593 sModel.addDesktopItem(info);
594 }
595 }
596
597
598 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700599 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800600 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700601 * @param data The intent describing the appWidgetId.
602 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800603 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700604 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 boolean insertAtFirst) {
606
607 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700608 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700610 d(LOG_TAG, "dumping extras content="+extras.toString());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700612 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700614 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800615 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700616 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800617
618 // Try finding open space on Launcher screen
619 final int[] xy = mCellCoordinates;
620 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
621
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700622 // Build Launcher-specific widget info and save to database
623 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 launcherInfo.spanX = spans[0];
625 launcherInfo.spanY = spans[1];
626
627 LauncherModel.addItemToDatabase(this, launcherInfo,
628 LauncherSettings.Favorites.CONTAINER_DESKTOP,
629 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
630
631 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700632 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633
634 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700635 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700637 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 launcherInfo.hostView.setTag(launcherInfo);
639
640 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
641 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
642 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700643 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800644 }
645 }
646
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700647 public LauncherAppWidgetHost getAppWidgetHost() {
648 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 }
650
651 static ApplicationInfo addShortcut(Context context, Intent data,
652 CellLayout.CellInfo cellInfo, boolean notify) {
653
654 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
655 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
656 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
657
658 Drawable icon = null;
659 boolean filtered = false;
660 boolean customIcon = false;
661 Intent.ShortcutIconResource iconResource = null;
662
663 if (bitmap != null) {
664 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
665 filtered = true;
666 customIcon = true;
667 } else {
668 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
669 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
670 try {
671 iconResource = (Intent.ShortcutIconResource) extra;
672 final PackageManager packageManager = context.getPackageManager();
673 Resources resources = packageManager.getResourcesForApplication(
674 iconResource.packageName);
675 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
676 icon = resources.getDrawable(id);
677 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700678 w(LOG_TAG, "Could not load shortcut icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800679 }
680 }
681 }
682
683 if (icon == null) {
684 icon = context.getPackageManager().getDefaultActivityIcon();
685 }
686
687 final ApplicationInfo info = new ApplicationInfo();
688 info.icon = icon;
689 info.filtered = filtered;
690 info.title = name;
691 info.intent = intent;
692 info.customIcon = customIcon;
693 info.iconResource = iconResource;
694
695 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
696 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
697 return info;
698 }
699
700 @Override
701 protected void onNewIntent(Intent intent) {
702 super.onNewIntent(intent);
703
704 // Close the menu
705 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
706 getWindow().closeAllPanels();
707
708 try {
709 dismissDialog(DIALOG_CREATE_SHORTCUT);
710 // Unlock the workspace if the dialog was showing
711 mWorkspace.unlock();
712 } catch (Exception e) {
713 // An exception is thrown if the dialog is not visible, which is fine
714 }
715
716 try {
717 dismissDialog(DIALOG_RENAME_FOLDER);
718 // Unlock the workspace if the dialog was showing
719 mWorkspace.unlock();
720 } catch (Exception e) {
721 // An exception is thrown if the dialog is not visible, which is fine
722 }
723
724 // If we are already in front we go back to the default screen,
725 // otherwise we don't
726 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
727 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
728 if (!mWorkspace.isDefaultScreenShowing()) {
729 mWorkspace.moveToDefaultScreen();
730 }
731 closeDrawer();
732 View v = getWindow().peekDecorView();
733 if (v != null && v.getWindowToken() != null) {
734 InputMethodManager imm = (InputMethodManager)getSystemService(
735 INPUT_METHOD_SERVICE);
736 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
737 }
738 } else {
739 closeDrawer(false);
740 }
741 }
742 }
743
744 @Override
745 protected void onRestoreInstanceState(Bundle savedInstanceState) {
746 // Do not call super here
747 mSavedInstanceState = savedInstanceState;
748 }
749
750 @Override
751 protected void onSaveInstanceState(Bundle outState) {
752 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
753
754 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
755 if (folders.size() > 0) {
756 final int count = folders.size();
757 long[] ids = new long[count];
758 for (int i = 0; i < count; i++) {
759 final FolderInfo info = folders.get(i).getInfo();
760 ids[i] = info.id;
761 }
762 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
763 } else {
764 super.onSaveInstanceState(outState);
765 }
766
767 if (mDrawer.isOpened()) {
768 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
769 }
770
771 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
772 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
773 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
774
775 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
776 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
777 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
778 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
779 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
780 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
781 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
782 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
783 layout.getOccupiedCells());
784 }
785
786 if (mFolderInfo != null && mWaitingForResult) {
787 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
788 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
789 }
790 }
791
792 @Override
793 public void onDestroy() {
794 mDestroyed = true;
795
796 super.onDestroy();
797
798 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700799 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800800 } catch (NullPointerException ex) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700801 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800802 }
803
804 TextKeyListener.getInstance().release();
805
806 mAllAppsGrid.clearTextFilter();
807 mAllAppsGrid.setAdapter(null);
808 sModel.unbind();
809 sModel.abortLoaders();
810
811 getContentResolver().unregisterContentObserver(mObserver);
812 unregisterReceiver(mApplicationsReceiver);
813 }
814
815 @Override
816 public void startActivityForResult(Intent intent, int requestCode) {
817 mWaitingForResult = true;
818 super.startActivityForResult(intent, requestCode);
819 }
820
821 @Override
822 public void startSearch(String initialQuery, boolean selectInitialQuery,
823 Bundle appSearchData, boolean globalSearch) {
824 if (appSearchData == null) {
825 appSearchData = new Bundle();
826 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
827 }
828 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
829 }
830
831 @Override
832 public boolean onCreateOptionsMenu(Menu menu) {
833 if (mDesktopLocked) return false;
834
835 super.onCreateOptionsMenu(menu);
836 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
837 .setIcon(android.R.drawable.ic_menu_add)
838 .setAlphabeticShortcut('A');
839 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
840 .setIcon(android.R.drawable.ic_menu_gallery)
841 .setAlphabeticShortcut('W');
842 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
843 .setIcon(android.R.drawable.ic_search_category_default)
844 .setAlphabeticShortcut(SearchManager.MENU_KEY);
845 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
846 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
847 .setAlphabeticShortcut('N');
848
849 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
850 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
851 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
852
853 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
854 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
855 .setIntent(settings);
856
857 return true;
858 }
859
860 @Override
861 public boolean onPrepareOptionsMenu(Menu menu) {
862 super.onPrepareOptionsMenu(menu);
863
864 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
865 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
866
867 return true;
868 }
869
870 @Override
871 public boolean onOptionsItemSelected(MenuItem item) {
872 switch (item.getItemId()) {
873 case MENU_ADD:
874 addItems();
875 return true;
876 case MENU_WALLPAPER_SETTINGS:
877 startWallpaper();
878 return true;
879 case MENU_SEARCH:
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700880 onSearchRequested();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800881 return true;
882 case MENU_NOTIFICATIONS:
883 showNotifications();
884 return true;
885 }
886
887 return super.onOptionsItemSelected(item);
888 }
889
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700890 @Override
891 public boolean onSearchRequested() {
892 if (mWorkspace.snapToSearch()) {
893 closeDrawer(true); // search widget: get drawer out of the way
894 return true;
895 } else {
896 return super.onSearchRequested(); // no search widget: use system search UI
897 }
898 }
899
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 private void addItems() {
901 showAddDialog(mMenuAddInfo);
902 }
903
904 private void removeShortcutsForPackage(String packageName) {
905 if (packageName != null && packageName.length() > 0) {
906 mWorkspace.removeShortcutsForPackage(packageName);
907 }
908 }
909
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700910 private void updateShortcutsForPackage(String packageName) {
911 if (packageName != null && packageName.length() > 0) {
912 mWorkspace.updateShortcutsForPackage(packageName);
913 }
914 }
915
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700916 void addAppWidget(Intent data) {
917 // TODO: catch bad widget exception when sent
918 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800919
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700920 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
921 if (SEARCH_WIDGET.equals(customWidget)) {
922 // We don't need this any more, since this isn't a real app widget.
923 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
924 // add the search widget
925 addSearch();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800926 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700927 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
928
929 if (appWidget.configure != null) {
930 // Launch over to configure widget, if needed
931 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
932 intent.setComponent(appWidget.configure);
933 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
934
935 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
936 } else {
937 // Otherwise just add it
938 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
939 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800940 }
941 }
942
943 void addSearch() {
944 final Widget info = Widget.makeSearch();
945 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
946
947 final int[] xy = mCellCoordinates;
948 final int spanX = info.spanX;
949 final int spanY = info.spanY;
950
951 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
952
953 sModel.addDesktopItem(info);
954 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
955 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
956
957 final View view = mInflater.inflate(info.layoutResource, null);
958 view.setTag(info);
959
960 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
961 }
962
963 void addShortcut(Intent intent) {
964 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
965 }
966
967 void addLiveFolder(Intent intent) {
968 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
969 }
970
971 void addFolder(boolean insertAtFirst) {
972 UserFolderInfo folderInfo = new UserFolderInfo();
973 folderInfo.title = getText(R.string.folder_name);
974
975 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
976 cellInfo.screen = mWorkspace.getCurrentScreen();
977 if (!findSingleSlot(cellInfo)) return;
978
979 // Update the model
980 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
981 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
982 sModel.addDesktopItem(folderInfo);
983 sModel.addFolder(folderInfo);
984
985 // Create the view
986 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
987 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
988 mWorkspace.addInCurrentScreen(newFolder,
989 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
990 }
991
992 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
993 boolean insertAtFirst) {
994 cellInfo.screen = mWorkspace.getCurrentScreen();
995 if (!findSingleSlot(cellInfo)) return;
996
997 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
998
999 if (!mRestoring) {
1000 sModel.addDesktopItem(info);
1001
1002 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1003 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1004 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1005 } else if (sModel.isDesktopLoaded()) {
1006 sModel.addDesktopItem(info);
1007 }
1008 }
1009
1010 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1011 CellLayout.CellInfo cellInfo, boolean notify) {
1012
1013 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1014 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1015
1016 Drawable icon = null;
1017 boolean filtered = false;
1018 Intent.ShortcutIconResource iconResource = null;
1019
1020 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1021 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1022 try {
1023 iconResource = (Intent.ShortcutIconResource) extra;
1024 final PackageManager packageManager = context.getPackageManager();
1025 Resources resources = packageManager.getResourcesForApplication(
1026 iconResource.packageName);
1027 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1028 icon = resources.getDrawable(id);
1029 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001030 w(LOG_TAG, "Could not load live folder icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001031 }
1032 }
1033
1034 if (icon == null) {
1035 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1036 }
1037
1038 final LiveFolderInfo info = new LiveFolderInfo();
1039 info.icon = icon;
1040 info.filtered = filtered;
1041 info.title = name;
1042 info.iconResource = iconResource;
1043 info.uri = data.getData();
1044 info.baseIntent = baseIntent;
1045 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1046 LiveFolders.DISPLAY_MODE_GRID);
1047
1048 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1049 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1050 sModel.addFolder(info);
1051
1052 return info;
1053 }
1054
1055 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1056 final int[] xy = new int[2];
1057 if (findSlot(cellInfo, xy, 1, 1)) {
1058 cellInfo.cellX = xy[0];
1059 cellInfo.cellY = xy[1];
1060 return true;
1061 }
1062 return false;
1063 }
1064
1065 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1066 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1067 boolean[] occupied = mSavedState != null ?
1068 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1069 cellInfo = mWorkspace.findAllVacantCells(occupied);
1070 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1071 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1072 return false;
1073 }
1074 }
1075 return true;
1076 }
1077
1078 private void showNotifications() {
1079 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1080 if (statusBar != null) {
1081 statusBar.expand();
1082 }
1083 }
1084
1085 private void startWallpaper() {
1086 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1087 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1088 }
1089
1090 /**
1091 * Registers various intent receivers. The current implementation registers
1092 * only a wallpaper intent receiver to let other applications change the
1093 * wallpaper.
1094 */
1095 private void registerIntentReceivers() {
1096 if (sWallpaperReceiver == null) {
1097 final Application application = getApplication();
1098
1099 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1100
1101 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1102 application.registerReceiver(sWallpaperReceiver, filter);
1103 } else {
1104 sWallpaperReceiver.setLauncher(this);
1105 }
1106
1107 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1108 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1109 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1110 filter.addDataScheme("package");
1111 registerReceiver(mApplicationsReceiver, filter);
1112 }
1113
1114 /**
1115 * Registers various content observers. The current implementation registers
1116 * only a favorites observer to keep track of the favorites applications.
1117 */
1118 private void registerContentObservers() {
1119 ContentResolver resolver = getContentResolver();
1120 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1121 }
1122
1123 @Override
1124 public boolean dispatchKeyEvent(KeyEvent event) {
1125 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1126 switch (event.getKeyCode()) {
1127 case KeyEvent.KEYCODE_BACK:
1128 mWorkspace.dispatchKeyEvent(event);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001129 if (mDrawer.isOpened()) {
1130 closeDrawer();
1131 } else {
1132 closeFolder();
1133 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001134 return true;
1135 case KeyEvent.KEYCODE_HOME:
1136 return true;
1137 }
1138 }
1139
1140 return super.dispatchKeyEvent(event);
1141 }
1142
1143 private void closeDrawer() {
1144 closeDrawer(true);
1145 }
1146
1147 private void closeDrawer(boolean animated) {
1148 if (mDrawer.isOpened()) {
1149 if (animated) {
1150 mDrawer.animateClose();
1151 } else {
1152 mDrawer.close();
1153 }
1154 if (mDrawer.hasFocus()) {
1155 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1156 }
1157 }
1158 }
1159
1160 private void closeFolder() {
1161 Folder folder = mWorkspace.getOpenFolder();
1162 if (folder != null) {
1163 closeFolder(folder);
1164 }
1165 }
1166
1167 void closeFolder(Folder folder) {
1168 folder.getInfo().opened = false;
1169 ViewGroup parent = (ViewGroup) folder.getParent();
1170 if (parent != null) {
1171 parent.removeView(folder);
1172 }
1173 folder.onClose();
1174 }
1175
1176 /**
1177 * When the notification that favorites have changed is received, requests
1178 * a favorites list refresh.
1179 */
1180 private void onFavoritesChanged() {
1181 mDesktopLocked = true;
1182 mDrawer.lock();
1183 sModel.loadUserItems(false, this, false, false);
1184 }
1185
1186 void onDesktopItemsLoaded() {
1187 if (mDestroyed) return;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001188d("Home", "setting grid adapter");
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001189 mAllAppsGrid.setAdapter(sModel.getApplicationsAdapter());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001190 bindDesktopItems();
1191 }
1192
1193 /**
1194 * Refreshes the shortcuts shown on the workspace.
1195 */
1196 private void bindDesktopItems() {
1197 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001198 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
1199 if (shortcuts == null || appWidgets == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001200 return;
1201 }
1202
1203 final Workspace workspace = mWorkspace;
1204 int count = workspace.getChildCount();
1205 for (int i = 0; i < count; i++) {
1206 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1207 }
1208
1209 if (DEBUG_USER_INTERFACE) {
1210 android.widget.Button finishButton = new android.widget.Button(this);
1211 finishButton.setText("Finish");
1212 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1213
1214 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1215 public void onClick(View v) {
1216 finish();
1217 }
1218 });
1219 }
1220
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001221 final DesktopBinder binder = new DesktopBinder(this, shortcuts, appWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001222 binder.startBindingItems();
1223 }
1224
1225 private void bindItems(Launcher.DesktopBinder binder,
1226 ArrayList<ItemInfo> shortcuts, int start, int count) {
1227
1228 final Workspace workspace = mWorkspace;
1229 final boolean desktopLocked = mDesktopLocked;
1230
1231 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1232 int i = start;
1233
1234 for ( ; i < end; i++) {
1235 final ItemInfo item = shortcuts.get(i);
1236 switch (item.itemType) {
1237 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1238 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1239 final View shortcut = createShortcut((ApplicationInfo) item);
1240 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1241 !desktopLocked);
1242 break;
1243 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1244 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1245 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1246 (UserFolderInfo) item);
1247 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1248 !desktopLocked);
1249 break;
1250 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1251 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1252 R.layout.live_folder_icon, this,
1253 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1254 (LiveFolderInfo) item);
1255 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1256 !desktopLocked);
1257 break;
1258 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1259 final int screen = workspace.getCurrentScreen();
1260 final View view = mInflater.inflate(R.layout.widget_search,
1261 (ViewGroup) workspace.getChildAt(screen), false);
1262
1263 final Widget widget = (Widget) item;
1264 view.setTag(widget);
1265
1266 workspace.addWidget(view, widget, !desktopLocked);
1267 break;
1268 }
1269 }
1270
1271 workspace.requestLayout();
1272
1273 if (end >= count) {
1274 finishBindDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001275 binder.startBindingAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001276 } else {
1277 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1278 }
1279 }
1280
1281 private void finishBindDesktopItems() {
1282 if (mSavedState != null) {
1283 if (!mWorkspace.hasFocus()) {
1284 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1285 }
1286
1287 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1288 if (userFolders != null) {
1289 for (long folderId : userFolders) {
1290 final FolderInfo info = sModel.findFolderById(folderId);
1291 if (info != null) {
1292 openFolder(info);
1293 }
1294 }
1295 final Folder openFolder = mWorkspace.getOpenFolder();
1296 if (openFolder != null) {
1297 openFolder.requestFocus();
1298 }
1299 }
1300
1301 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1302 if (allApps) {
1303 mDrawer.open();
1304 }
1305
1306 mSavedState = null;
1307 }
1308
1309 if (mSavedInstanceState != null) {
1310 super.onRestoreInstanceState(mSavedInstanceState);
1311 mSavedInstanceState = null;
1312 }
1313
1314 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1315 mDrawer.requestFocus();
1316 }
1317
1318 mDesktopLocked = false;
1319 mDrawer.unlock();
1320 }
1321
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001322 private void bindAppWidgets(Launcher.DesktopBinder binder,
1323 ArrayList<LauncherAppWidgetInfo> appWidgets, int start, int count) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001324
1325 final Workspace workspace = mWorkspace;
1326 final boolean desktopLocked = mDesktopLocked;
1327
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001328 final int end = Math.min(start + DesktopBinder.APPWIDGETS_COUNT, count);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001329 int i = start;
1330
1331 for ( ; i < end; i++) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001332 final LauncherAppWidgetInfo item = appWidgets.get(i);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001333
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001334 final int appWidgetId = item.appWidgetId;
1335 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1336 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001337
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001338 if (LOGD) d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s", appWidgetId, appWidgetInfo));
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001339
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001340 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001341 item.hostView.setTag(item);
1342
1343 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1344 item.cellY, item.spanX, item.spanY, !desktopLocked);
1345 }
1346
1347 workspace.requestLayout();
1348
1349 if (end >= count) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001350 finishBindDesktopAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001351 } else {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001352 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS, i, count).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001353 }
1354 }
1355
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001356 private void finishBindDesktopAppWidgets() {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001357 }
1358
1359 DragController getDragController() {
1360 return mDragLayer;
1361 }
1362
1363 /**
1364 * Launches the intent referred by the clicked shortcut.
1365 *
1366 * @param v The view representing the clicked shortcut.
1367 */
1368 public void onClick(View v) {
1369 Object tag = v.getTag();
1370 if (tag instanceof ApplicationInfo) {
1371 // Open shortcut
1372 final Intent intent = ((ApplicationInfo) tag).intent;
1373 startActivitySafely(intent);
1374 } else if (tag instanceof FolderInfo) {
1375 handleFolderClick((FolderInfo) tag);
1376 }
1377 }
1378
1379 void startActivitySafely(Intent intent) {
1380 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1381 try {
1382 startActivity(intent);
1383 } catch (ActivityNotFoundException e) {
1384 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1385 } catch (SecurityException e) {
1386 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1387 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1388 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1389 "or use the exported attribute for this activity.", e);
1390 }
1391 }
1392
1393 private void handleFolderClick(FolderInfo folderInfo) {
1394 if (!folderInfo.opened) {
1395 // Close any open folder
1396 closeFolder();
1397 // Open the requested folder
1398 openFolder(folderInfo);
1399 } else {
1400 // Find the open folder...
1401 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1402 int folderScreen;
1403 if (openFolder != null) {
1404 folderScreen = mWorkspace.getScreenForView(openFolder);
1405 // .. and close it
1406 closeFolder(openFolder);
1407 if (folderScreen != mWorkspace.getCurrentScreen()) {
1408 // Close any folder open on the current screen
1409 closeFolder();
1410 // Pull the folder onto this screen
1411 openFolder(folderInfo);
1412 }
1413 }
1414 }
1415 }
1416
1417 private void loadWallpaper() {
1418 // The first time the application is started, we load the wallpaper from
1419 // the ApplicationContext
1420 if (sWallpaper == null) {
1421 final Drawable drawable = getWallpaper();
1422 if (drawable instanceof BitmapDrawable) {
1423 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1424 } else {
1425 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1426 }
1427 }
1428 mWorkspace.loadWallpaper(sWallpaper);
1429 }
1430
1431 /**
1432 * Opens the user fodler described by the specified tag. The opening of the folder
1433 * is animated relative to the specified View. If the View is null, no animation
1434 * is played.
1435 *
1436 * @param folderInfo The FolderInfo describing the folder to open.
1437 */
1438 private void openFolder(FolderInfo folderInfo) {
1439 Folder openFolder;
1440
1441 if (folderInfo instanceof UserFolderInfo) {
1442 openFolder = UserFolder.fromXml(this);
1443 } else if (folderInfo instanceof LiveFolderInfo) {
1444 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1445 } else {
1446 return;
1447 }
1448
1449 openFolder.setDragger(mDragLayer);
1450 openFolder.setLauncher(this);
1451
1452 openFolder.bind(folderInfo);
1453 folderInfo.opened = true;
1454
1455 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1456 openFolder.onOpen();
1457 }
1458
1459 /**
1460 * Returns true if the workspace is being loaded. When the workspace is loading,
1461 * no user interaction should be allowed to avoid any conflict.
1462 *
1463 * @return True if the workspace is locked, false otherwise.
1464 */
1465 boolean isWorkspaceLocked() {
1466 return mDesktopLocked;
1467 }
1468
1469 public boolean onLongClick(View v) {
1470 if (mDesktopLocked) {
1471 return false;
1472 }
1473
1474 if (!(v instanceof CellLayout)) {
1475 v = (View) v.getParent();
1476 }
1477
1478 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1479
1480 // This happens when long clicking an item with the dpad/trackball
1481 if (cellInfo == null) {
1482 return true;
1483 }
1484
1485 if (mWorkspace.allowLongPress()) {
1486 if (cellInfo.cell == null) {
1487 if (cellInfo.valid) {
1488 // User long pressed on empty space
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001489 mWorkspace.setAllowLongPress(false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001490 showAddDialog(cellInfo);
1491 }
1492 } else {
1493 if (!(cellInfo.cell instanceof Folder)) {
1494 // User long pressed on an item
1495 mWorkspace.startDrag(cellInfo);
1496 }
1497 }
1498 }
1499 return true;
1500 }
1501
1502 static LauncherModel getModel() {
1503 return sModel;
1504 }
1505
1506 void closeAllApplications() {
1507 mDrawer.close();
1508 }
1509
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001510 View getDrawerHandle() {
1511 return mHandleView;
1512 }
1513
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001514 boolean isDrawerDown() {
1515 return !mDrawer.isMoving() && !mDrawer.isOpened();
1516 }
1517
1518 boolean isDrawerUp() {
1519 return mDrawer.isOpened() && !mDrawer.isMoving();
1520 }
1521
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001522 boolean isDrawerMoving() {
1523 return mDrawer.isMoving();
1524 }
1525
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001526 Workspace getWorkspace() {
1527 return mWorkspace;
1528 }
1529
1530 GridView getApplicationsGrid() {
1531 return mAllAppsGrid;
1532 }
1533
1534 @Override
1535 protected Dialog onCreateDialog(int id) {
1536 switch (id) {
1537 case DIALOG_CREATE_SHORTCUT:
1538 return new CreateShortcut().createDialog();
1539 case DIALOG_RENAME_FOLDER:
1540 return new RenameFolder().createDialog();
1541 }
1542
1543 return super.onCreateDialog(id);
1544 }
1545
1546 @Override
1547 protected void onPrepareDialog(int id, Dialog dialog) {
1548 switch (id) {
1549 case DIALOG_CREATE_SHORTCUT:
1550 mWorkspace.lock();
1551 break;
1552 case DIALOG_RENAME_FOLDER:
1553 mWorkspace.lock();
1554 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1555 final CharSequence text = mFolderInfo.title;
1556 input.setText(text);
1557 input.setSelection(0, text.length());
1558 break;
1559 }
1560 }
1561
1562 void showRenameDialog(FolderInfo info) {
1563 mFolderInfo = info;
1564 mWaitingForResult = true;
1565 showDialog(DIALOG_RENAME_FOLDER);
1566 }
1567
1568 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1569 mAddItemCellInfo = cellInfo;
1570 mWaitingForResult = true;
1571 showDialog(DIALOG_CREATE_SHORTCUT);
1572 }
1573
1574 private class RenameFolder {
1575 private EditText mInput;
1576
1577 Dialog createDialog() {
1578 mWaitingForResult = true;
1579 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1580 mInput = (EditText) layout.findViewById(R.id.folder_name);
1581
1582 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1583 builder.setIcon(0);
1584 builder.setTitle(getString(R.string.rename_folder_title));
1585 builder.setCancelable(true);
1586 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1587 public void onCancel(DialogInterface dialog) {
1588 cleanup();
1589 }
1590 });
1591 builder.setNegativeButton(getString(R.string.cancel_action),
1592 new Dialog.OnClickListener() {
1593 public void onClick(DialogInterface dialog, int which) {
1594 cleanup();
1595 }
1596 }
1597 );
1598 builder.setPositiveButton(getString(R.string.rename_action),
1599 new Dialog.OnClickListener() {
1600 public void onClick(DialogInterface dialog, int which) {
1601 changeFolderName();
1602 }
1603 }
1604 );
1605 builder.setView(layout);
1606 return builder.create();
1607 }
1608
1609 private void changeFolderName() {
1610 final String name = mInput.getText().toString();
1611 if (!TextUtils.isEmpty(name)) {
1612 // Make sure we have the right folder info
1613 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1614 mFolderInfo.title = name;
1615 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1616
1617 if (mDesktopLocked) {
1618 mDrawer.lock();
1619 sModel.loadUserItems(false, Launcher.this, false, false);
1620 } else {
1621 final FolderIcon folderIcon = (FolderIcon)
1622 mWorkspace.getViewForTag(mFolderInfo);
1623 if (folderIcon != null) {
1624 folderIcon.setText(name);
1625 getWorkspace().requestLayout();
1626 } else {
1627 mDesktopLocked = true;
1628 mDrawer.lock();
1629 sModel.loadUserItems(false, Launcher.this, false, false);
1630 }
1631 }
1632 }
1633 cleanup();
1634 }
1635
1636 private void cleanup() {
1637 mWorkspace.unlock();
1638 dismissDialog(DIALOG_RENAME_FOLDER);
1639 mWaitingForResult = false;
1640 mFolderInfo = null;
1641 }
1642 }
1643
1644 /**
1645 * Displays the shortcut creation dialog and launches, if necessary, the
1646 * appropriate activity.
1647 */
1648 private class CreateShortcut implements AdapterView.OnItemClickListener,
1649 DialogInterface.OnCancelListener {
1650 private AddAdapter mAdapter;
1651 private ListView mList;
1652
1653 Dialog createDialog() {
1654 mWaitingForResult = true;
1655
1656 mAdapter = new AddAdapter(Launcher.this);
1657
1658 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1659 builder.setTitle(getString(R.string.menu_item_add_item));
1660 builder.setIcon(0);
1661
1662 mList = (ListView)
1663 View.inflate(Launcher.this, R.layout.create_shortcut_list, null);
1664 mList.setAdapter(mAdapter);
1665 mList.setOnItemClickListener(this);
1666 builder.setView(mList);
1667 builder.setInverseBackgroundForced(true);
1668
1669 AlertDialog dialog = builder.create();
1670 dialog.setOnCancelListener(this);
1671
1672 WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
1673 attributes.gravity = Gravity.TOP;
1674 dialog.onWindowAttributesChanged(attributes);
1675
1676 return dialog;
1677 }
1678
1679 public void onCancel(DialogInterface dialog) {
1680 mWaitingForResult = false;
1681 cleanup();
1682 }
1683
1684 private void cleanup() {
1685 mWorkspace.unlock();
1686 dismissDialog(DIALOG_CREATE_SHORTCUT);
1687 }
1688
1689 public void onItemClick(AdapterView parent, View view, int position, long id) {
1690 // handle which item was clicked based on position
1691 // this will launch off pick intent
1692
1693 Object tag = view.getTag();
1694 if (tag instanceof AddAdapter.ListItem) {
1695 AddAdapter.ListItem item = (AddAdapter.ListItem) tag;
1696 cleanup();
1697 switch (item.actionTag) {
1698 case AddAdapter.ITEM_APPLICATION: {
1699 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1700 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1701
1702 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1703 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1704 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
1705 break;
1706 }
1707
1708 case AddAdapter.ITEM_SHORTCUT: {
1709 Intent shortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1710
1711 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1712 pickIntent.putExtra(Intent.EXTRA_INTENT, shortcutIntent);
1713 pickIntent.putExtra(Intent.EXTRA_TITLE,
1714 getText(R.string.title_select_shortcut));
1715 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1716 break;
1717 }
1718
1719 case AddAdapter.ITEM_SEARCH: {
1720 addSearch();
1721 break;
1722 }
1723
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001724 case AddAdapter.ITEM_APPWIDGET: {
1725 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001726
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001727 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1728 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001729 // add the search widget
1730 ArrayList<AppWidgetProviderInfo> customInfo =
1731 new ArrayList<AppWidgetProviderInfo>();
1732 AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1733 info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1734 info.label = getString(R.string.group_search);
1735 info.icon = R.drawable.ic_search_widget;
1736 customInfo.add(info);
1737 pickIntent.putParcelableArrayListExtra(
1738 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1739 ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1740 Bundle b = new Bundle();
1741 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1742 customExtras.add(b);
1743 pickIntent.putParcelableArrayListExtra(
1744 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1745 // start the pick activity
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001746 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001747 break;
1748 }
1749
1750 case AddAdapter.ITEM_LIVE_FOLDER: {
1751 Intent liveFolderIntent = new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER);
1752
1753 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1754 pickIntent.putExtra(Intent.EXTRA_INTENT, liveFolderIntent);
1755 pickIntent.putExtra(Intent.EXTRA_TITLE,
1756 getText(R.string.title_select_live_folder));
1757 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1758 break;
1759 }
1760
1761 case AddAdapter.ITEM_FOLDER: {
1762 addFolder(!mDesktopLocked);
1763 dismissDialog(DIALOG_CREATE_SHORTCUT);
1764 break;
1765 }
1766
1767 case AddAdapter.ITEM_WALLPAPER: {
1768 startWallpaper();
1769 break;
1770 }
1771
1772 }
1773
1774 }
1775 }
1776 }
1777
1778 /**
1779 * Receives notifications when applications are added/removed.
1780 */
1781 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1782 @Override
1783 public void onReceive(Context context, Intent intent) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001784 final String action = intent.getAction();
1785 final String packageName = intent.getData().getSchemeSpecificPart();
1786 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1787
1788 if (LauncherModel.DEBUG_LOADERS) {
1789 d(LauncherModel.LOG_TAG, "application intent received: " + action +
1790 ", replacing=" + replacing);
1791 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001792 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001793
1794 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1795 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1796 if (!replacing) {
1797 removeShortcutsForPackage(packageName);
1798 if (LauncherModel.DEBUG_LOADERS) {
1799 d(LauncherModel.LOG_TAG, " --> remove package");
1800 }
1801 sModel.removePackage(Launcher.this, packageName);
1802 }
1803 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1804 // later, we will update the package at this time
1805 } else {
1806 if (!replacing) {
1807 if (LauncherModel.DEBUG_LOADERS) {
1808 d(LauncherModel.LOG_TAG, " --> add package");
1809 }
1810 sModel.addPackage(Launcher.this, packageName);
1811 } else {
1812 if (LauncherModel.DEBUG_LOADERS) {
1813 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
1814 }
1815 sModel.updatePackage(Launcher.this, packageName);
1816 updateShortcutsForPackage(packageName);
1817 }
1818 }
1819 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001820 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001821 if (LauncherModel.DEBUG_LOADERS) {
1822 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
1823 }
1824 sModel.syncPackage(Launcher.this, packageName);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001825 }
1826 }
1827 }
1828
1829 /**
1830 * Receives notifications whenever the user favorites have changed.
1831 */
1832 private class FavoritesChangeObserver extends ContentObserver {
1833 public FavoritesChangeObserver() {
1834 super(new Handler());
1835 }
1836
1837 @Override
1838 public void onChange(boolean selfChange) {
1839 onFavoritesChanged();
1840 }
1841 }
1842
1843 /**
1844 * Receives intents from other applications to change the wallpaper.
1845 */
1846 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1847 private final Application mApplication;
1848 private WeakReference<Launcher> mLauncher;
1849
1850 WallpaperIntentReceiver(Application application, Launcher launcher) {
1851 mApplication = application;
1852 setLauncher(launcher);
1853 }
1854
1855 void setLauncher(Launcher launcher) {
1856 mLauncher = new WeakReference<Launcher>(launcher);
1857 }
1858
1859 @Override
1860 public void onReceive(Context context, Intent intent) {
1861 // Load the wallpaper from the ApplicationContext and store it locally
1862 // until the Launcher Activity is ready to use it
1863 final Drawable drawable = mApplication.getWallpaper();
1864 if (drawable instanceof BitmapDrawable) {
1865 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1866 } else {
1867 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1868 }
1869
1870 // If Launcher is alive, notify we have a new wallpaper
1871 if (mLauncher != null) {
1872 final Launcher launcher = mLauncher.get();
1873 if (launcher != null) {
1874 launcher.loadWallpaper();
1875 }
1876 }
1877 }
1878 }
1879
1880 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1881 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1882 private boolean mOpen;
1883
1884 public void onDrawerOpened() {
1885 if (!mOpen) {
1886 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001887
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001888 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001889 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001890
1891 mOpen = true;
1892 }
1893 }
1894
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001895 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1896 view.getDrawingRect(bounds);
1897
1898 while (view != mDragLayer) {
1899 bounds.offset(view.getLeft(), view.getTop());
1900 view = (View) view.getParent();
1901 }
1902 }
1903
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001904 public void onDrawerClosed() {
1905 if (mOpen) {
1906 mHandleIcon.reverseTransition(150);
1907 mWorkspace.mDrawerBounds.setEmpty();
1908 mOpen = false;
1909 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001910
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001911 mAllAppsGrid.setSelection(0);
1912 mAllAppsGrid.clearTextFilter();
1913 }
1914
1915 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001916 if (PROFILE_DRAWER) {
1917 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1918 }
1919
1920 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1921 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001922 }
1923
1924 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001925 if (PROFILE_DRAWER) {
1926 android.os.Debug.stopMethodTracing();
1927 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001928 }
1929 }
1930
1931 private static class DesktopBinder extends Handler {
1932 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001933 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001934 // Number of items to bind in every pass
1935 static final int ITEMS_COUNT = 6;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001936 static final int APPWIDGETS_COUNT = 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001937
1938 private final ArrayList<ItemInfo> mShortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001939 private final ArrayList<LauncherAppWidgetInfo> mAppWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001940 private final WeakReference<Launcher> mLauncher;
1941
1942 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001943 ArrayList<LauncherAppWidgetInfo> appWidgets) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001944
1945 mLauncher = new WeakReference<Launcher>(launcher);
1946 mShortcuts = shortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001947 mAppWidgets = appWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001948 }
1949
1950 public void startBindingItems() {
1951 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
1952 }
1953
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001954 public void startBindingAppWidgets() {
1955 obtainMessage(MESSAGE_BIND_APPWIDGETS, 0, mAppWidgets.size()).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001956 }
1957
1958 @Override
1959 public void handleMessage(Message msg) {
1960 Launcher launcher = mLauncher.get();
1961 if (launcher == null) {
1962 return;
1963 }
1964
1965 switch (msg.what) {
1966 case MESSAGE_BIND_ITEMS: {
1967 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
1968 break;
1969 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001970 case MESSAGE_BIND_APPWIDGETS: {
1971 launcher.bindAppWidgets(this, mAppWidgets, msg.arg1, msg.arg2);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001972 break;
1973 }
1974 }
1975 }
1976 }
1977}