blob: 99182f1dce87b5f443baafe4b546ebccf8a1d7a6 [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;
60import android.view.Display;
61import android.view.Gravity;
62import android.view.KeyEvent;
63import android.view.LayoutInflater;
64import android.view.Menu;
65import android.view.MenuItem;
66import android.view.View;
67import android.view.ViewGroup;
68import android.view.WindowManager;
69import android.view.View.OnLongClickListener;
70import android.view.inputmethod.InputMethodManager;
71import android.widget.AdapterView;
72import android.widget.EditText;
73import android.widget.ListView;
74import android.widget.TextView;
75import android.widget.Toast;
76import android.widget.GridView;
77import android.widget.SlidingDrawer;
78import android.app.IWallpaperService;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070079import android.appwidget.AppWidgetManager;
80import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
82import java.lang.ref.WeakReference;
83import java.util.ArrayList;
84
85/**
86 * Default launcher application.
87 */
88public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
89 static final String LOG_TAG = "Launcher";
90 static final boolean LOGD = false;
91
92 private static final boolean PROFILE_STARTUP = false;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070093 private static final boolean PROFILE_DRAWER = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080094 private static final boolean DEBUG_USER_INTERFACE = false;
95
96 private static final int WALLPAPER_SCREENS_SPAN = 2;
97
98 private static final int MENU_GROUP_ADD = 1;
99 private static final int MENU_ADD = Menu.FIRST + 1;
100 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
101 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
102 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
103 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
104
105 private static final int REQUEST_CREATE_SHORTCUT = 1;
106 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700107 private static final int REQUEST_CREATE_APPWIDGET = 5;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800108 private static final int REQUEST_PICK_APPLICATION = 6;
109 private static final int REQUEST_PICK_SHORTCUT = 7;
110 private static final int REQUEST_PICK_LIVE_FOLDER = 8;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700111 private static final int REQUEST_PICK_APPWIDGET = 9;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800112
113 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
114
115 static final int SCREEN_COUNT = 3;
116 static final int DEFAULT_SCREN = 1;
117 static final int NUMBER_CELLS_X = 4;
118 static final int NUMBER_CELLS_Y = 4;
119
120 private static final int DIALOG_CREATE_SHORTCUT = 1;
121 static final int DIALOG_RENAME_FOLDER = 2;
122
123 private static final String PREFERENCES = "launcher";
124 private static final String KEY_LOCALE = "locale";
125 private static final String KEY_MCC = "mcc";
126 private static final String KEY_MNC = "mnc";
127
128 // Type: int
129 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
130 // Type: boolean
131 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
132 // Type: long
133 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
134 // Type: int
135 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
136 // Type: int
137 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
138 // Type: int
139 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
140 // Type: int
141 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
142 // Type: int
143 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
144 // Type: int
145 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
146 // Type: int
147 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
148 // Type: int[]
149 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
150 // Type: boolean
151 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
152 // Type: long
153 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
154
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700155 private static final LauncherModel sModel = new LauncherModel();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800156
157 private static Bitmap sWallpaper;
158
159 private static final Object sLock = new Object();
160 private static int sScreen = DEFAULT_SCREN;
161
162 private static WallpaperIntentReceiver sWallpaperReceiver;
163
164 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
165 private final ContentObserver mObserver = new FavoritesChangeObserver();
166
167 private LayoutInflater mInflater;
168
169 private DragLayer mDragLayer;
170 private Workspace mWorkspace;
171
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700172 private AppWidgetManager mAppWidgetManager;
173 private LauncherAppWidgetHost mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800174
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700175 static final int APPWIDGET_HOST_ID = 1024;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800176
177 private CellLayout.CellInfo mAddItemCellInfo;
178 private CellLayout.CellInfo mMenuAddInfo;
179 private final int[] mCellCoordinates = new int[2];
180 private FolderInfo mFolderInfo;
181
182 private SlidingDrawer mDrawer;
183 private TransitionDrawable mHandleIcon;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700184 private HandleView mHandleView;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800185 private AllAppsGridView mAllAppsGrid;
186
187 private boolean mDesktopLocked = true;
188 private Bundle mSavedState;
189
190 private SpannableStringBuilder mDefaultKeySsb = null;
191
192 private boolean mDestroyed;
193
194 private boolean mRestoring;
195 private boolean mWaitingForResult;
196 private boolean mLocaleChanged;
197
198 private Bundle mSavedInstanceState;
199
200 @Override
201 protected void onCreate(Bundle savedInstanceState) {
202 super.onCreate(savedInstanceState);
203 mInflater = getLayoutInflater();
204
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700205 mAppWidgetManager = AppWidgetManager.getInstance(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800206
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700207 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
208 mAppWidgetHost.startListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800209
210 if (PROFILE_STARTUP) {
211 android.os.Debug.startMethodTracing("/sdcard/launcher");
212 }
213
214 checkForLocaleChange();
215 setWallpaperDimension();
216
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217 setContentView(R.layout.launcher);
218 setupViews();
219
220 registerIntentReceivers();
221 registerContentObservers();
222
223 mSavedState = savedInstanceState;
224 restoreState(mSavedState);
225
226 if (PROFILE_STARTUP) {
227 android.os.Debug.stopMethodTracing();
228 }
229
230 if (!mRestoring) {
231 startLoaders();
232 }
233
234 // For handling default keys
235 mDefaultKeySsb = new SpannableStringBuilder();
236 Selection.setSelection(mDefaultKeySsb, 0);
237 }
238
239 private void checkForLocaleChange() {
240 final SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
241 final Configuration configuration = getResources().getConfiguration();
242
243 final String previousLocale = preferences.getString(KEY_LOCALE, null);
244 final String locale = configuration.locale.toString();
245
246 final int previousMcc = preferences.getInt(KEY_MCC, -1);
247 final int mcc = configuration.mcc;
248
249 final int previousMnc = preferences.getInt(KEY_MNC, -1);
250 final int mnc = configuration.mnc;
251
252 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
253
254 if (mLocaleChanged) {
255 final SharedPreferences.Editor editor = preferences.edit();
256 editor.putString(KEY_LOCALE, locale);
257 editor.putInt(KEY_MCC, mcc);
258 editor.putInt(KEY_MNC, mnc);
259 editor.commit();
260 }
261 }
262
263 static int getScreen() {
264 synchronized (sLock) {
265 return sScreen;
266 }
267 }
268
269 static void setScreen(int screen) {
270 synchronized (sLock) {
271 sScreen = screen;
272 }
273 }
274
275 private void startLoaders() {
276 sModel.loadApplications(true, this, mLocaleChanged);
277 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, true);
278 mRestoring = false;
279 }
280
281 private void setWallpaperDimension() {
282 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
283 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
284
285 Display display = getWindowManager().getDefaultDisplay();
286 boolean isPortrait = display.getWidth() < display.getHeight();
287
288 final int width = isPortrait ? display.getWidth() : display.getHeight();
289 final int height = isPortrait ? display.getHeight() : display.getWidth();
290 try {
291 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
292 } catch (RemoteException e) {
293 // System is dead!
294 }
295 }
296
297 @Override
298 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
299 // The pattern used here is that a user PICKs a specific application,
300 // which, depending on the target, might need to CREATE the actual target.
301
302 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
303 // launch over to the Music app to actually CREATE_SHORTCUT.
304
305 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
306 switch (requestCode) {
307 case REQUEST_PICK_APPLICATION:
308 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
309 break;
310 case REQUEST_PICK_SHORTCUT:
311 addShortcut(data);
312 break;
313 case REQUEST_CREATE_SHORTCUT:
314 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
315 break;
316 case REQUEST_PICK_LIVE_FOLDER:
317 addLiveFolder(data);
318 break;
319 case REQUEST_CREATE_LIVE_FOLDER:
320 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
321 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700322 case REQUEST_PICK_APPWIDGET:
323 addAppWidget(data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800324 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700325 case REQUEST_CREATE_APPWIDGET:
326 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800327 break;
328 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700329 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800330 resultCode == RESULT_CANCELED && data != null) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700331 // Clean up the appWidgetId if we canceled
332 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
333 if (appWidgetId != -1) {
334 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800335 }
336 }
337 mWaitingForResult = false;
338 }
339
340 @Override
341 protected void onResume() {
342 super.onResume();
343
344 if (mRestoring) {
345 startLoaders();
346 }
347 }
348
349 @Override
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700350 protected void onPause() {
351 super.onPause();
352 closeDrawer(false);
353 }
354
355 @Override
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 public boolean onKeyUp(int keyCode, KeyEvent event) {
357 boolean handled = super.onKeyUp(keyCode, event);
358 if (keyCode == KeyEvent.KEYCODE_SEARCH) {
359 handled = mWorkspace.snapToSearch();
360 if (handled) closeDrawer(true);
361 }
362 return handled;
363 }
364
365 private boolean acceptFilter() {
366 final InputMethodManager inputManager = (InputMethodManager)
367 getSystemService(Context.INPUT_METHOD_SERVICE);
368 return !inputManager.isFullscreenMode();
369 }
370
371 @Override
372 public boolean onKeyDown(int keyCode, KeyEvent event) {
373 boolean handled = super.onKeyDown(keyCode, event);
374 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
375 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
376 keyCode, event);
377 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
378 // something usable has been typed - dispatch it now.
379 final String str = mDefaultKeySsb.toString();
380
381 boolean isDialable = true;
382 final int count = str.length();
383 for (int i = 0; i < count; i++) {
384 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
385 isDialable = false;
386 break;
387 }
388 }
389 Intent intent;
390 if (isDialable) {
391 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
392 } else {
393 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
394 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
395 }
396
397 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
398
399 try {
400 startActivity(intent);
401 } catch (android.content.ActivityNotFoundException ex) {
402 // Oh well... no one knows how to filter/dial. Life goes on.
403 }
404
405 mDefaultKeySsb.clear();
406 mDefaultKeySsb.clearSpans();
407 Selection.setSelection(mDefaultKeySsb, 0);
408
409 return true;
410 }
411 }
412
413 return handled;
414 }
415
416 /**
417 * Restores the previous state, if it exists.
418 *
419 * @param savedState The previous state.
420 */
421 private void restoreState(Bundle savedState) {
422 if (savedState == null) {
423 return;
424 }
425
426 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
427 if (currentScreen > -1) {
428 mWorkspace.setCurrentScreen(currentScreen);
429 }
430
431 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
432 if (addScreen > -1) {
433 mAddItemCellInfo = new CellLayout.CellInfo();
434 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
435 addItemCellInfo.valid = true;
436 addItemCellInfo.screen = addScreen;
437 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
438 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
439 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
440 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
441 addItemCellInfo.findVacantCellsFromOccupied(
442 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
443 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
444 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
445 mRestoring = true;
446 }
447
448 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
449 if (renameFolder) {
450 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
451 mFolderInfo = sModel.getFolderById(this, id);
452 mRestoring = true;
453 }
454 }
455
456 /**
457 * Finds all the views we need and configure them properly.
458 */
459 private void setupViews() {
460 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
461 final DragLayer dragLayer = mDragLayer;
462
463 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
464 final Workspace workspace = mWorkspace;
465
466 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
467 final SlidingDrawer drawer = mDrawer;
468
469 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
470 final AllAppsGridView grid = mAllAppsGrid;
471
472 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
473
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700474 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
475 mHandleView.setLauncher(this);
476 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800477 mHandleIcon.setCrossFadeEnabled(true);
478
479 drawer.lock();
480 final DrawerManager drawerManager = new DrawerManager();
481 drawer.setOnDrawerOpenListener(drawerManager);
482 drawer.setOnDrawerCloseListener(drawerManager);
483 drawer.setOnDrawerScrollListener(drawerManager);
484
485 grid.setTextFilterEnabled(true);
486 grid.setDragger(dragLayer);
487 grid.setLauncher(this);
488
489 workspace.setOnLongClickListener(this);
490 workspace.setDragger(dragLayer);
491 workspace.setLauncher(this);
492 loadWallpaper();
493
494 deleteZone.setLauncher(this);
495 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700496 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800497
498 dragLayer.setIgnoredDropTarget(grid);
499 dragLayer.setDragScoller(workspace);
500 dragLayer.setDragListener(deleteZone);
501 }
502
503 /**
504 * Creates a view representing a shortcut.
505 *
506 * @param info The data structure describing the shortcut.
507 *
508 * @return A View inflated from R.layout.application.
509 */
510 View createShortcut(ApplicationInfo info) {
511 return createShortcut(R.layout.application,
512 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
513 }
514
515 /**
516 * Creates a view representing a shortcut inflated from the specified resource.
517 *
518 * @param layoutResId The id of the XML layout used to create the shortcut.
519 * @param parent The group the shortcut belongs to.
520 * @param info The data structure describing the shortcut.
521 *
522 * @return A View inflated from layoutResId.
523 */
524 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
525 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
526
527 if (!info.filtered) {
528 info.icon = Utilities.createIconThumbnail(info.icon, this);
529 info.filtered = true;
530 }
531
532 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
533 favorite.setText(info.title);
534 favorite.setTag(info);
535 favorite.setOnClickListener(this);
536
537 return favorite;
538 }
539
540 /**
541 * Add an application shortcut to the workspace.
542 *
543 * @param data The intent describing the application.
544 * @param cellInfo The position on screen where to create the shortcut.
545 */
546 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
547 boolean insertAtFirst) {
548 cellInfo.screen = mWorkspace.getCurrentScreen();
549 if (!findSingleSlot(cellInfo)) return;
550
551 // Find details for this application
552 ComponentName component = data.getComponent();
553 PackageManager packageManager = context.getPackageManager();
554 ActivityInfo activityInfo = null;
555 try {
556 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
557 } catch (NameNotFoundException e) {
558 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
559 }
560
561 if (activityInfo != null) {
562 ApplicationInfo itemInfo = new ApplicationInfo();
563
564 itemInfo.title = activityInfo.loadLabel(packageManager);
565 if (itemInfo.title == null) {
566 itemInfo.title = activityInfo.name;
567 }
568
569 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
570 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
571 itemInfo.icon = activityInfo.loadIcon(packageManager);
572 itemInfo.container = ItemInfo.NO_ID;
573
574 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
575 }
576 }
577
578 /**
579 * Add a shortcut to the workspace.
580 *
581 * @param data The intent describing the shortcut.
582 * @param cellInfo The position on screen where to create the shortcut.
583 * @param insertAtFirst
584 */
585 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
586 boolean insertAtFirst) {
587 cellInfo.screen = mWorkspace.getCurrentScreen();
588 if (!findSingleSlot(cellInfo)) return;
589
590 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
591
592 if (!mRestoring) {
593 sModel.addDesktopItem(info);
594
595 final View view = createShortcut(info);
596 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
597 } else if (sModel.isDesktopLoaded()) {
598 sModel.addDesktopItem(info);
599 }
600 }
601
602
603 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700604 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700606 * @param data The intent describing the appWidgetId.
607 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800608 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700609 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800610 boolean insertAtFirst) {
611
612 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700613 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800614
615 Log.d(LOG_TAG, "dumping extras content="+extras.toString());
616
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700617 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800618
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700619 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700621 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800622
623 // Try finding open space on Launcher screen
624 final int[] xy = mCellCoordinates;
625 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
626
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700627 // Build Launcher-specific widget info and save to database
628 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 launcherInfo.spanX = spans[0];
630 launcherInfo.spanY = spans[1];
631
632 LauncherModel.addItemToDatabase(this, launcherInfo,
633 LauncherSettings.Favorites.CONTAINER_DESKTOP,
634 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
635
636 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700637 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638
639 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700640 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700642 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800643 launcherInfo.hostView.setTag(launcherInfo);
644
645 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
646 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
647 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700648 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800649 }
650 }
651
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700652 public LauncherAppWidgetHost getAppWidgetHost() {
653 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654 }
655
656 static ApplicationInfo addShortcut(Context context, Intent data,
657 CellLayout.CellInfo cellInfo, boolean notify) {
658
659 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
660 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
661 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
662
663 Drawable icon = null;
664 boolean filtered = false;
665 boolean customIcon = false;
666 Intent.ShortcutIconResource iconResource = null;
667
668 if (bitmap != null) {
669 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
670 filtered = true;
671 customIcon = true;
672 } else {
673 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
674 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
675 try {
676 iconResource = (Intent.ShortcutIconResource) extra;
677 final PackageManager packageManager = context.getPackageManager();
678 Resources resources = packageManager.getResourcesForApplication(
679 iconResource.packageName);
680 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
681 icon = resources.getDrawable(id);
682 } catch (Exception e) {
683 Log.w(LOG_TAG, "Could not load shortcut icon: " + extra);
684 }
685 }
686 }
687
688 if (icon == null) {
689 icon = context.getPackageManager().getDefaultActivityIcon();
690 }
691
692 final ApplicationInfo info = new ApplicationInfo();
693 info.icon = icon;
694 info.filtered = filtered;
695 info.title = name;
696 info.intent = intent;
697 info.customIcon = customIcon;
698 info.iconResource = iconResource;
699
700 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
701 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
702 return info;
703 }
704
705 @Override
706 protected void onNewIntent(Intent intent) {
707 super.onNewIntent(intent);
708
709 // Close the menu
710 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
711 getWindow().closeAllPanels();
712
713 try {
714 dismissDialog(DIALOG_CREATE_SHORTCUT);
715 // Unlock the workspace if the dialog was showing
716 mWorkspace.unlock();
717 } catch (Exception e) {
718 // An exception is thrown if the dialog is not visible, which is fine
719 }
720
721 try {
722 dismissDialog(DIALOG_RENAME_FOLDER);
723 // Unlock the workspace if the dialog was showing
724 mWorkspace.unlock();
725 } catch (Exception e) {
726 // An exception is thrown if the dialog is not visible, which is fine
727 }
728
729 // If we are already in front we go back to the default screen,
730 // otherwise we don't
731 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
732 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
733 if (!mWorkspace.isDefaultScreenShowing()) {
734 mWorkspace.moveToDefaultScreen();
735 }
736 closeDrawer();
737 View v = getWindow().peekDecorView();
738 if (v != null && v.getWindowToken() != null) {
739 InputMethodManager imm = (InputMethodManager)getSystemService(
740 INPUT_METHOD_SERVICE);
741 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
742 }
743 } else {
744 closeDrawer(false);
745 }
746 }
747 }
748
749 @Override
750 protected void onRestoreInstanceState(Bundle savedInstanceState) {
751 // Do not call super here
752 mSavedInstanceState = savedInstanceState;
753 }
754
755 @Override
756 protected void onSaveInstanceState(Bundle outState) {
757 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
758
759 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
760 if (folders.size() > 0) {
761 final int count = folders.size();
762 long[] ids = new long[count];
763 for (int i = 0; i < count; i++) {
764 final FolderInfo info = folders.get(i).getInfo();
765 ids[i] = info.id;
766 }
767 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
768 } else {
769 super.onSaveInstanceState(outState);
770 }
771
772 if (mDrawer.isOpened()) {
773 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
774 }
775
776 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
777 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
778 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
779
780 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
781 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
782 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
783 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
784 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
785 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
786 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
787 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
788 layout.getOccupiedCells());
789 }
790
791 if (mFolderInfo != null && mWaitingForResult) {
792 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
793 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
794 }
795 }
796
797 @Override
798 public void onDestroy() {
799 mDestroyed = true;
800
801 super.onDestroy();
802
803 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700804 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800805 } catch (NullPointerException ex) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700806 Log.w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800807 }
808
809 TextKeyListener.getInstance().release();
810
811 mAllAppsGrid.clearTextFilter();
812 mAllAppsGrid.setAdapter(null);
813 sModel.unbind();
814 sModel.abortLoaders();
815
816 getContentResolver().unregisterContentObserver(mObserver);
817 unregisterReceiver(mApplicationsReceiver);
818 }
819
820 @Override
821 public void startActivityForResult(Intent intent, int requestCode) {
822 mWaitingForResult = true;
823 super.startActivityForResult(intent, requestCode);
824 }
825
826 @Override
827 public void startSearch(String initialQuery, boolean selectInitialQuery,
828 Bundle appSearchData, boolean globalSearch) {
829 if (appSearchData == null) {
830 appSearchData = new Bundle();
831 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
832 }
833 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
834 }
835
836 @Override
837 public boolean onCreateOptionsMenu(Menu menu) {
838 if (mDesktopLocked) return false;
839
840 super.onCreateOptionsMenu(menu);
841 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
842 .setIcon(android.R.drawable.ic_menu_add)
843 .setAlphabeticShortcut('A');
844 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
845 .setIcon(android.R.drawable.ic_menu_gallery)
846 .setAlphabeticShortcut('W');
847 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
848 .setIcon(android.R.drawable.ic_search_category_default)
849 .setAlphabeticShortcut(SearchManager.MENU_KEY);
850 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
851 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
852 .setAlphabeticShortcut('N');
853
854 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
855 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
856 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
857
858 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
859 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
860 .setIntent(settings);
861
862 return true;
863 }
864
865 @Override
866 public boolean onPrepareOptionsMenu(Menu menu) {
867 super.onPrepareOptionsMenu(menu);
868
869 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
870 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
871
872 return true;
873 }
874
875 @Override
876 public boolean onOptionsItemSelected(MenuItem item) {
877 switch (item.getItemId()) {
878 case MENU_ADD:
879 addItems();
880 return true;
881 case MENU_WALLPAPER_SETTINGS:
882 startWallpaper();
883 return true;
884 case MENU_SEARCH:
885 if (mWorkspace.snapToSearch()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700886 closeDrawer(true); // search widget: get drawer out of the way
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800887 } else {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700888 onSearchRequested(); // no search widget: use system search UI
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800889 }
890 return true;
891 case MENU_NOTIFICATIONS:
892 showNotifications();
893 return true;
894 }
895
896 return super.onOptionsItemSelected(item);
897 }
898
899 private void addItems() {
900 showAddDialog(mMenuAddInfo);
901 }
902
903 private void removeShortcutsForPackage(String packageName) {
904 if (packageName != null && packageName.length() > 0) {
905 mWorkspace.removeShortcutsForPackage(packageName);
906 }
907 }
908
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700909 void addAppWidget(Intent data) {
910 // TODO: catch bad widget exception when sent
911 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
912 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800913
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700914 if (appWidget.configure != null) {
915 // Launch over to configure widget, if needed
916 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
917 intent.setComponent(appWidget.configure);
918 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800919
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700920 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800921 } else {
922 // Otherwise just add it
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700923 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800924 }
925 }
926
927 void addSearch() {
928 final Widget info = Widget.makeSearch();
929 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
930
931 final int[] xy = mCellCoordinates;
932 final int spanX = info.spanX;
933 final int spanY = info.spanY;
934
935 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
936
937 sModel.addDesktopItem(info);
938 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
939 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
940
941 final View view = mInflater.inflate(info.layoutResource, null);
942 view.setTag(info);
943
944 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
945 }
946
947 void addShortcut(Intent intent) {
948 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
949 }
950
951 void addLiveFolder(Intent intent) {
952 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
953 }
954
955 void addFolder(boolean insertAtFirst) {
956 UserFolderInfo folderInfo = new UserFolderInfo();
957 folderInfo.title = getText(R.string.folder_name);
958
959 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
960 cellInfo.screen = mWorkspace.getCurrentScreen();
961 if (!findSingleSlot(cellInfo)) return;
962
963 // Update the model
964 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
965 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
966 sModel.addDesktopItem(folderInfo);
967 sModel.addFolder(folderInfo);
968
969 // Create the view
970 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
971 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
972 mWorkspace.addInCurrentScreen(newFolder,
973 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
974 }
975
976 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
977 boolean insertAtFirst) {
978 cellInfo.screen = mWorkspace.getCurrentScreen();
979 if (!findSingleSlot(cellInfo)) return;
980
981 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
982
983 if (!mRestoring) {
984 sModel.addDesktopItem(info);
985
986 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
987 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
988 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
989 } else if (sModel.isDesktopLoaded()) {
990 sModel.addDesktopItem(info);
991 }
992 }
993
994 static LiveFolderInfo addLiveFolder(Context context, Intent data,
995 CellLayout.CellInfo cellInfo, boolean notify) {
996
997 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
998 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
999
1000 Drawable icon = null;
1001 boolean filtered = false;
1002 Intent.ShortcutIconResource iconResource = null;
1003
1004 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1005 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1006 try {
1007 iconResource = (Intent.ShortcutIconResource) extra;
1008 final PackageManager packageManager = context.getPackageManager();
1009 Resources resources = packageManager.getResourcesForApplication(
1010 iconResource.packageName);
1011 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1012 icon = resources.getDrawable(id);
1013 } catch (Exception e) {
1014 Log.w(LOG_TAG, "Could not load live folder icon: " + extra);
1015 }
1016 }
1017
1018 if (icon == null) {
1019 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1020 }
1021
1022 final LiveFolderInfo info = new LiveFolderInfo();
1023 info.icon = icon;
1024 info.filtered = filtered;
1025 info.title = name;
1026 info.iconResource = iconResource;
1027 info.uri = data.getData();
1028 info.baseIntent = baseIntent;
1029 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1030 LiveFolders.DISPLAY_MODE_GRID);
1031
1032 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1033 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1034 sModel.addFolder(info);
1035
1036 return info;
1037 }
1038
1039 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1040 final int[] xy = new int[2];
1041 if (findSlot(cellInfo, xy, 1, 1)) {
1042 cellInfo.cellX = xy[0];
1043 cellInfo.cellY = xy[1];
1044 return true;
1045 }
1046 return false;
1047 }
1048
1049 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1050 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1051 boolean[] occupied = mSavedState != null ?
1052 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1053 cellInfo = mWorkspace.findAllVacantCells(occupied);
1054 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1055 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1056 return false;
1057 }
1058 }
1059 return true;
1060 }
1061
1062 private void showNotifications() {
1063 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1064 if (statusBar != null) {
1065 statusBar.expand();
1066 }
1067 }
1068
1069 private void startWallpaper() {
1070 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1071 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1072 }
1073
1074 /**
1075 * Registers various intent receivers. The current implementation registers
1076 * only a wallpaper intent receiver to let other applications change the
1077 * wallpaper.
1078 */
1079 private void registerIntentReceivers() {
1080 if (sWallpaperReceiver == null) {
1081 final Application application = getApplication();
1082
1083 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1084
1085 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1086 application.registerReceiver(sWallpaperReceiver, filter);
1087 } else {
1088 sWallpaperReceiver.setLauncher(this);
1089 }
1090
1091 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1092 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1093 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1094 filter.addDataScheme("package");
1095 registerReceiver(mApplicationsReceiver, filter);
1096 }
1097
1098 /**
1099 * Registers various content observers. The current implementation registers
1100 * only a favorites observer to keep track of the favorites applications.
1101 */
1102 private void registerContentObservers() {
1103 ContentResolver resolver = getContentResolver();
1104 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1105 }
1106
1107 @Override
1108 public boolean dispatchKeyEvent(KeyEvent event) {
1109 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1110 switch (event.getKeyCode()) {
1111 case KeyEvent.KEYCODE_BACK:
1112 mWorkspace.dispatchKeyEvent(event);
1113 closeFolder();
1114 closeDrawer();
1115 return true;
1116 case KeyEvent.KEYCODE_HOME:
1117 return true;
1118 }
1119 }
1120
1121 return super.dispatchKeyEvent(event);
1122 }
1123
1124 private void closeDrawer() {
1125 closeDrawer(true);
1126 }
1127
1128 private void closeDrawer(boolean animated) {
1129 if (mDrawer.isOpened()) {
1130 if (animated) {
1131 mDrawer.animateClose();
1132 } else {
1133 mDrawer.close();
1134 }
1135 if (mDrawer.hasFocus()) {
1136 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1137 }
1138 }
1139 }
1140
1141 private void closeFolder() {
1142 Folder folder = mWorkspace.getOpenFolder();
1143 if (folder != null) {
1144 closeFolder(folder);
1145 }
1146 }
1147
1148 void closeFolder(Folder folder) {
1149 folder.getInfo().opened = false;
1150 ViewGroup parent = (ViewGroup) folder.getParent();
1151 if (parent != null) {
1152 parent.removeView(folder);
1153 }
1154 folder.onClose();
1155 }
1156
1157 /**
1158 * When the notification that favorites have changed is received, requests
1159 * a favorites list refresh.
1160 */
1161 private void onFavoritesChanged() {
1162 mDesktopLocked = true;
1163 mDrawer.lock();
1164 sModel.loadUserItems(false, this, false, false);
1165 }
1166
1167 void onDesktopItemsLoaded() {
1168 if (mDestroyed) return;
1169
1170 mAllAppsGrid.setAdapter(Launcher.getModel().getApplicationsAdapter());
1171 bindDesktopItems();
1172 }
1173
1174 /**
1175 * Refreshes the shortcuts shown on the workspace.
1176 */
1177 private void bindDesktopItems() {
1178 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001179 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
1180 if (shortcuts == null || appWidgets == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001181 return;
1182 }
1183
1184 final Workspace workspace = mWorkspace;
1185 int count = workspace.getChildCount();
1186 for (int i = 0; i < count; i++) {
1187 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1188 }
1189
1190 if (DEBUG_USER_INTERFACE) {
1191 android.widget.Button finishButton = new android.widget.Button(this);
1192 finishButton.setText("Finish");
1193 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1194
1195 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1196 public void onClick(View v) {
1197 finish();
1198 }
1199 });
1200 }
1201
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001202 final DesktopBinder binder = new DesktopBinder(this, shortcuts, appWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001203 binder.startBindingItems();
1204 }
1205
1206 private void bindItems(Launcher.DesktopBinder binder,
1207 ArrayList<ItemInfo> shortcuts, int start, int count) {
1208
1209 final Workspace workspace = mWorkspace;
1210 final boolean desktopLocked = mDesktopLocked;
1211
1212 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1213 int i = start;
1214
1215 for ( ; i < end; i++) {
1216 final ItemInfo item = shortcuts.get(i);
1217 switch (item.itemType) {
1218 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1219 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1220 final View shortcut = createShortcut((ApplicationInfo) item);
1221 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1222 !desktopLocked);
1223 break;
1224 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1225 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1226 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1227 (UserFolderInfo) item);
1228 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1229 !desktopLocked);
1230 break;
1231 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1232 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1233 R.layout.live_folder_icon, this,
1234 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1235 (LiveFolderInfo) item);
1236 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1237 !desktopLocked);
1238 break;
1239 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1240 final int screen = workspace.getCurrentScreen();
1241 final View view = mInflater.inflate(R.layout.widget_search,
1242 (ViewGroup) workspace.getChildAt(screen), false);
1243
1244 final Widget widget = (Widget) item;
1245 view.setTag(widget);
1246
1247 workspace.addWidget(view, widget, !desktopLocked);
1248 break;
1249 }
1250 }
1251
1252 workspace.requestLayout();
1253
1254 if (end >= count) {
1255 finishBindDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001256 binder.startBindingAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001257 } else {
1258 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1259 }
1260 }
1261
1262 private void finishBindDesktopItems() {
1263 if (mSavedState != null) {
1264 if (!mWorkspace.hasFocus()) {
1265 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1266 }
1267
1268 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1269 if (userFolders != null) {
1270 for (long folderId : userFolders) {
1271 final FolderInfo info = sModel.findFolderById(folderId);
1272 if (info != null) {
1273 openFolder(info);
1274 }
1275 }
1276 final Folder openFolder = mWorkspace.getOpenFolder();
1277 if (openFolder != null) {
1278 openFolder.requestFocus();
1279 }
1280 }
1281
1282 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1283 if (allApps) {
1284 mDrawer.open();
1285 }
1286
1287 mSavedState = null;
1288 }
1289
1290 if (mSavedInstanceState != null) {
1291 super.onRestoreInstanceState(mSavedInstanceState);
1292 mSavedInstanceState = null;
1293 }
1294
1295 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1296 mDrawer.requestFocus();
1297 }
1298
1299 mDesktopLocked = false;
1300 mDrawer.unlock();
1301 }
1302
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001303 private void bindAppWidgets(Launcher.DesktopBinder binder,
1304 ArrayList<LauncherAppWidgetInfo> appWidgets, int start, int count) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001305
1306 final Workspace workspace = mWorkspace;
1307 final boolean desktopLocked = mDesktopLocked;
1308
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001309 final int end = Math.min(start + DesktopBinder.APPWIDGETS_COUNT, count);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001310 int i = start;
1311
1312 for ( ; i < end; i++) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001313 final LauncherAppWidgetInfo item = appWidgets.get(i);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001314
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001315 final int appWidgetId = item.appWidgetId;
1316 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1317 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001318
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001319 if (LOGD) Log.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 -08001320
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001321 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001322 item.hostView.setTag(item);
1323
1324 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1325 item.cellY, item.spanX, item.spanY, !desktopLocked);
1326 }
1327
1328 workspace.requestLayout();
1329
1330 if (end >= count) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001331 finishBindDesktopAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001332 } else {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001333 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS, i, count).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001334 }
1335 }
1336
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001337 private void finishBindDesktopAppWidgets() {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001338 }
1339
1340 DragController getDragController() {
1341 return mDragLayer;
1342 }
1343
1344 /**
1345 * Launches the intent referred by the clicked shortcut.
1346 *
1347 * @param v The view representing the clicked shortcut.
1348 */
1349 public void onClick(View v) {
1350 Object tag = v.getTag();
1351 if (tag instanceof ApplicationInfo) {
1352 // Open shortcut
1353 final Intent intent = ((ApplicationInfo) tag).intent;
1354 startActivitySafely(intent);
1355 } else if (tag instanceof FolderInfo) {
1356 handleFolderClick((FolderInfo) tag);
1357 }
1358 }
1359
1360 void startActivitySafely(Intent intent) {
1361 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1362 try {
1363 startActivity(intent);
1364 } catch (ActivityNotFoundException e) {
1365 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1366 } catch (SecurityException e) {
1367 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1368 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1369 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1370 "or use the exported attribute for this activity.", e);
1371 }
1372 }
1373
1374 private void handleFolderClick(FolderInfo folderInfo) {
1375 if (!folderInfo.opened) {
1376 // Close any open folder
1377 closeFolder();
1378 // Open the requested folder
1379 openFolder(folderInfo);
1380 } else {
1381 // Find the open folder...
1382 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1383 int folderScreen;
1384 if (openFolder != null) {
1385 folderScreen = mWorkspace.getScreenForView(openFolder);
1386 // .. and close it
1387 closeFolder(openFolder);
1388 if (folderScreen != mWorkspace.getCurrentScreen()) {
1389 // Close any folder open on the current screen
1390 closeFolder();
1391 // Pull the folder onto this screen
1392 openFolder(folderInfo);
1393 }
1394 }
1395 }
1396 }
1397
1398 private void loadWallpaper() {
1399 // The first time the application is started, we load the wallpaper from
1400 // the ApplicationContext
1401 if (sWallpaper == null) {
1402 final Drawable drawable = getWallpaper();
1403 if (drawable instanceof BitmapDrawable) {
1404 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1405 } else {
1406 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1407 }
1408 }
1409 mWorkspace.loadWallpaper(sWallpaper);
1410 }
1411
1412 /**
1413 * Opens the user fodler described by the specified tag. The opening of the folder
1414 * is animated relative to the specified View. If the View is null, no animation
1415 * is played.
1416 *
1417 * @param folderInfo The FolderInfo describing the folder to open.
1418 */
1419 private void openFolder(FolderInfo folderInfo) {
1420 Folder openFolder;
1421
1422 if (folderInfo instanceof UserFolderInfo) {
1423 openFolder = UserFolder.fromXml(this);
1424 } else if (folderInfo instanceof LiveFolderInfo) {
1425 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1426 } else {
1427 return;
1428 }
1429
1430 openFolder.setDragger(mDragLayer);
1431 openFolder.setLauncher(this);
1432
1433 openFolder.bind(folderInfo);
1434 folderInfo.opened = true;
1435
1436 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1437 openFolder.onOpen();
1438 }
1439
1440 /**
1441 * Returns true if the workspace is being loaded. When the workspace is loading,
1442 * no user interaction should be allowed to avoid any conflict.
1443 *
1444 * @return True if the workspace is locked, false otherwise.
1445 */
1446 boolean isWorkspaceLocked() {
1447 return mDesktopLocked;
1448 }
1449
1450 public boolean onLongClick(View v) {
1451 if (mDesktopLocked) {
1452 return false;
1453 }
1454
1455 if (!(v instanceof CellLayout)) {
1456 v = (View) v.getParent();
1457 }
1458
1459 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1460
1461 // This happens when long clicking an item with the dpad/trackball
1462 if (cellInfo == null) {
1463 return true;
1464 }
1465
1466 if (mWorkspace.allowLongPress()) {
1467 if (cellInfo.cell == null) {
1468 if (cellInfo.valid) {
1469 // User long pressed on empty space
1470 showAddDialog(cellInfo);
1471 }
1472 } else {
1473 if (!(cellInfo.cell instanceof Folder)) {
1474 // User long pressed on an item
1475 mWorkspace.startDrag(cellInfo);
1476 }
1477 }
1478 }
1479 return true;
1480 }
1481
1482 static LauncherModel getModel() {
1483 return sModel;
1484 }
1485
1486 void closeAllApplications() {
1487 mDrawer.close();
1488 }
1489
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001490 View getDrawerHandle() {
1491 return mHandleView;
1492 }
1493
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001494 boolean isDrawerDown() {
1495 return !mDrawer.isMoving() && !mDrawer.isOpened();
1496 }
1497
1498 boolean isDrawerUp() {
1499 return mDrawer.isOpened() && !mDrawer.isMoving();
1500 }
1501
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001502 boolean isDrawerMoving() {
1503 return mDrawer.isMoving();
1504 }
1505
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001506 Workspace getWorkspace() {
1507 return mWorkspace;
1508 }
1509
1510 GridView getApplicationsGrid() {
1511 return mAllAppsGrid;
1512 }
1513
1514 @Override
1515 protected Dialog onCreateDialog(int id) {
1516 switch (id) {
1517 case DIALOG_CREATE_SHORTCUT:
1518 return new CreateShortcut().createDialog();
1519 case DIALOG_RENAME_FOLDER:
1520 return new RenameFolder().createDialog();
1521 }
1522
1523 return super.onCreateDialog(id);
1524 }
1525
1526 @Override
1527 protected void onPrepareDialog(int id, Dialog dialog) {
1528 switch (id) {
1529 case DIALOG_CREATE_SHORTCUT:
1530 mWorkspace.lock();
1531 break;
1532 case DIALOG_RENAME_FOLDER:
1533 mWorkspace.lock();
1534 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1535 final CharSequence text = mFolderInfo.title;
1536 input.setText(text);
1537 input.setSelection(0, text.length());
1538 break;
1539 }
1540 }
1541
1542 void showRenameDialog(FolderInfo info) {
1543 mFolderInfo = info;
1544 mWaitingForResult = true;
1545 showDialog(DIALOG_RENAME_FOLDER);
1546 }
1547
1548 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1549 mAddItemCellInfo = cellInfo;
1550 mWaitingForResult = true;
1551 showDialog(DIALOG_CREATE_SHORTCUT);
1552 }
1553
1554 private class RenameFolder {
1555 private EditText mInput;
1556
1557 Dialog createDialog() {
1558 mWaitingForResult = true;
1559 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1560 mInput = (EditText) layout.findViewById(R.id.folder_name);
1561
1562 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1563 builder.setIcon(0);
1564 builder.setTitle(getString(R.string.rename_folder_title));
1565 builder.setCancelable(true);
1566 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1567 public void onCancel(DialogInterface dialog) {
1568 cleanup();
1569 }
1570 });
1571 builder.setNegativeButton(getString(R.string.cancel_action),
1572 new Dialog.OnClickListener() {
1573 public void onClick(DialogInterface dialog, int which) {
1574 cleanup();
1575 }
1576 }
1577 );
1578 builder.setPositiveButton(getString(R.string.rename_action),
1579 new Dialog.OnClickListener() {
1580 public void onClick(DialogInterface dialog, int which) {
1581 changeFolderName();
1582 }
1583 }
1584 );
1585 builder.setView(layout);
1586 return builder.create();
1587 }
1588
1589 private void changeFolderName() {
1590 final String name = mInput.getText().toString();
1591 if (!TextUtils.isEmpty(name)) {
1592 // Make sure we have the right folder info
1593 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1594 mFolderInfo.title = name;
1595 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1596
1597 if (mDesktopLocked) {
1598 mDrawer.lock();
1599 sModel.loadUserItems(false, Launcher.this, false, false);
1600 } else {
1601 final FolderIcon folderIcon = (FolderIcon)
1602 mWorkspace.getViewForTag(mFolderInfo);
1603 if (folderIcon != null) {
1604 folderIcon.setText(name);
1605 getWorkspace().requestLayout();
1606 } else {
1607 mDesktopLocked = true;
1608 mDrawer.lock();
1609 sModel.loadUserItems(false, Launcher.this, false, false);
1610 }
1611 }
1612 }
1613 cleanup();
1614 }
1615
1616 private void cleanup() {
1617 mWorkspace.unlock();
1618 dismissDialog(DIALOG_RENAME_FOLDER);
1619 mWaitingForResult = false;
1620 mFolderInfo = null;
1621 }
1622 }
1623
1624 /**
1625 * Displays the shortcut creation dialog and launches, if necessary, the
1626 * appropriate activity.
1627 */
1628 private class CreateShortcut implements AdapterView.OnItemClickListener,
1629 DialogInterface.OnCancelListener {
1630 private AddAdapter mAdapter;
1631 private ListView mList;
1632
1633 Dialog createDialog() {
1634 mWaitingForResult = true;
1635
1636 mAdapter = new AddAdapter(Launcher.this);
1637
1638 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1639 builder.setTitle(getString(R.string.menu_item_add_item));
1640 builder.setIcon(0);
1641
1642 mList = (ListView)
1643 View.inflate(Launcher.this, R.layout.create_shortcut_list, null);
1644 mList.setAdapter(mAdapter);
1645 mList.setOnItemClickListener(this);
1646 builder.setView(mList);
1647 builder.setInverseBackgroundForced(true);
1648
1649 AlertDialog dialog = builder.create();
1650 dialog.setOnCancelListener(this);
1651
1652 WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
1653 attributes.gravity = Gravity.TOP;
1654 dialog.onWindowAttributesChanged(attributes);
1655
1656 return dialog;
1657 }
1658
1659 public void onCancel(DialogInterface dialog) {
1660 mWaitingForResult = false;
1661 cleanup();
1662 }
1663
1664 private void cleanup() {
1665 mWorkspace.unlock();
1666 dismissDialog(DIALOG_CREATE_SHORTCUT);
1667 }
1668
1669 public void onItemClick(AdapterView parent, View view, int position, long id) {
1670 // handle which item was clicked based on position
1671 // this will launch off pick intent
1672
1673 Object tag = view.getTag();
1674 if (tag instanceof AddAdapter.ListItem) {
1675 AddAdapter.ListItem item = (AddAdapter.ListItem) tag;
1676 cleanup();
1677 switch (item.actionTag) {
1678 case AddAdapter.ITEM_APPLICATION: {
1679 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1680 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1681
1682 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1683 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1684 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
1685 break;
1686 }
1687
1688 case AddAdapter.ITEM_SHORTCUT: {
1689 Intent shortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1690
1691 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1692 pickIntent.putExtra(Intent.EXTRA_INTENT, shortcutIntent);
1693 pickIntent.putExtra(Intent.EXTRA_TITLE,
1694 getText(R.string.title_select_shortcut));
1695 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1696 break;
1697 }
1698
1699 case AddAdapter.ITEM_SEARCH: {
1700 addSearch();
1701 break;
1702 }
1703
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001704 case AddAdapter.ITEM_APPWIDGET: {
1705 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001706
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001707 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1708 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1709 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001710 break;
1711 }
1712
1713 case AddAdapter.ITEM_LIVE_FOLDER: {
1714 Intent liveFolderIntent = new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER);
1715
1716 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1717 pickIntent.putExtra(Intent.EXTRA_INTENT, liveFolderIntent);
1718 pickIntent.putExtra(Intent.EXTRA_TITLE,
1719 getText(R.string.title_select_live_folder));
1720 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1721 break;
1722 }
1723
1724 case AddAdapter.ITEM_FOLDER: {
1725 addFolder(!mDesktopLocked);
1726 dismissDialog(DIALOG_CREATE_SHORTCUT);
1727 break;
1728 }
1729
1730 case AddAdapter.ITEM_WALLPAPER: {
1731 startWallpaper();
1732 break;
1733 }
1734
1735 }
1736
1737 }
1738 }
1739 }
1740
1741 /**
1742 * Receives notifications when applications are added/removed.
1743 */
1744 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1745 @Override
1746 public void onReceive(Context context, Intent intent) {
1747 boolean reloadWorkspace = false;
1748 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
1749 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
1750 removeShortcutsForPackage(intent.getData().getSchemeSpecificPart());
1751 } else {
1752 reloadWorkspace = true;
1753 }
1754 }
1755 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Projectbc219c32009-03-09 11:52:14 -07001756 sModel.dropApplicationCache();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001757 if (!reloadWorkspace) {
1758 sModel.loadApplications(false, Launcher.this, false);
1759 } else {
1760 sModel.loadUserItems(false, Launcher.this, false, true);
1761 }
1762 }
1763 }
1764
1765 /**
1766 * Receives notifications whenever the user favorites have changed.
1767 */
1768 private class FavoritesChangeObserver extends ContentObserver {
1769 public FavoritesChangeObserver() {
1770 super(new Handler());
1771 }
1772
1773 @Override
1774 public void onChange(boolean selfChange) {
1775 onFavoritesChanged();
1776 }
1777 }
1778
1779 /**
1780 * Receives intents from other applications to change the wallpaper.
1781 */
1782 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1783 private final Application mApplication;
1784 private WeakReference<Launcher> mLauncher;
1785
1786 WallpaperIntentReceiver(Application application, Launcher launcher) {
1787 mApplication = application;
1788 setLauncher(launcher);
1789 }
1790
1791 void setLauncher(Launcher launcher) {
1792 mLauncher = new WeakReference<Launcher>(launcher);
1793 }
1794
1795 @Override
1796 public void onReceive(Context context, Intent intent) {
1797 // Load the wallpaper from the ApplicationContext and store it locally
1798 // until the Launcher Activity is ready to use it
1799 final Drawable drawable = mApplication.getWallpaper();
1800 if (drawable instanceof BitmapDrawable) {
1801 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1802 } else {
1803 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1804 }
1805
1806 // If Launcher is alive, notify we have a new wallpaper
1807 if (mLauncher != null) {
1808 final Launcher launcher = mLauncher.get();
1809 if (launcher != null) {
1810 launcher.loadWallpaper();
1811 }
1812 }
1813 }
1814 }
1815
1816 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1817 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1818 private boolean mOpen;
1819
1820 public void onDrawerOpened() {
1821 if (!mOpen) {
1822 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001823
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001824 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001825 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001826
1827 mOpen = true;
1828 }
1829 }
1830
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001831 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1832 view.getDrawingRect(bounds);
1833
1834 while (view != mDragLayer) {
1835 bounds.offset(view.getLeft(), view.getTop());
1836 view = (View) view.getParent();
1837 }
1838 }
1839
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001840 public void onDrawerClosed() {
1841 if (mOpen) {
1842 mHandleIcon.reverseTransition(150);
1843 mWorkspace.mDrawerBounds.setEmpty();
1844 mOpen = false;
1845 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001846
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001847 mAllAppsGrid.setSelection(0);
1848 mAllAppsGrid.clearTextFilter();
1849 }
1850
1851 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001852 if (PROFILE_DRAWER) {
1853 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1854 }
1855
1856 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1857 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001858 }
1859
1860 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001861 if (PROFILE_DRAWER) {
1862 android.os.Debug.stopMethodTracing();
1863 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001864 }
1865 }
1866
1867 private static class DesktopBinder extends Handler {
1868 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001869 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001870 // Number of items to bind in every pass
1871 static final int ITEMS_COUNT = 6;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001872 static final int APPWIDGETS_COUNT = 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001873
1874 private final ArrayList<ItemInfo> mShortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001875 private final ArrayList<LauncherAppWidgetInfo> mAppWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001876 private final WeakReference<Launcher> mLauncher;
1877
1878 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001879 ArrayList<LauncherAppWidgetInfo> appWidgets) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001880
1881 mLauncher = new WeakReference<Launcher>(launcher);
1882 mShortcuts = shortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001883 mAppWidgets = appWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001884 }
1885
1886 public void startBindingItems() {
1887 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
1888 }
1889
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001890 public void startBindingAppWidgets() {
1891 obtainMessage(MESSAGE_BIND_APPWIDGETS, 0, mAppWidgets.size()).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001892 }
1893
1894 @Override
1895 public void handleMessage(Message msg) {
1896 Launcher launcher = mLauncher.get();
1897 if (launcher == null) {
1898 return;
1899 }
1900
1901 switch (msg.what) {
1902 case MESSAGE_BIND_ITEMS: {
1903 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
1904 break;
1905 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001906 case MESSAGE_BIND_APPWIDGETS: {
1907 launcher.bindAppWidgets(this, mAppWidgets, msg.arg1, msg.arg2);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001908 break;
1909 }
1910 }
1911 }
1912 }
1913}