blob: 17f16a7a3d8a631f294740fddc5018a758ba3406 [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() {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700276 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
277 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
278
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800279 mRestoring = false;
280 }
281
282 private void setWallpaperDimension() {
283 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
284 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
285
286 Display display = getWindowManager().getDefaultDisplay();
287 boolean isPortrait = display.getWidth() < display.getHeight();
288
289 final int width = isPortrait ? display.getWidth() : display.getHeight();
290 final int height = isPortrait ? display.getHeight() : display.getWidth();
291 try {
292 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
293 } catch (RemoteException e) {
294 // System is dead!
295 }
296 }
297
298 @Override
299 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
300 // The pattern used here is that a user PICKs a specific application,
301 // which, depending on the target, might need to CREATE the actual target.
302
303 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
304 // launch over to the Music app to actually CREATE_SHORTCUT.
305
306 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
307 switch (requestCode) {
308 case REQUEST_PICK_APPLICATION:
309 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
310 break;
311 case REQUEST_PICK_SHORTCUT:
312 addShortcut(data);
313 break;
314 case REQUEST_CREATE_SHORTCUT:
315 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
316 break;
317 case REQUEST_PICK_LIVE_FOLDER:
318 addLiveFolder(data);
319 break;
320 case REQUEST_CREATE_LIVE_FOLDER:
321 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
322 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700323 case REQUEST_PICK_APPWIDGET:
324 addAppWidget(data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800325 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700326 case REQUEST_CREATE_APPWIDGET:
327 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800328 break;
329 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700330 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800331 resultCode == RESULT_CANCELED && data != null) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700332 // Clean up the appWidgetId if we canceled
333 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
334 if (appWidgetId != -1) {
335 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336 }
337 }
338 mWaitingForResult = false;
339 }
340
341 @Override
342 protected void onResume() {
343 super.onResume();
344
345 if (mRestoring) {
346 startLoaders();
347 }
348 }
349
350 @Override
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700351 protected void onPause() {
352 super.onPause();
353 closeDrawer(false);
354 }
355
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800356 private boolean acceptFilter() {
357 final InputMethodManager inputManager = (InputMethodManager)
358 getSystemService(Context.INPUT_METHOD_SERVICE);
359 return !inputManager.isFullscreenMode();
360 }
361
362 @Override
363 public boolean onKeyDown(int keyCode, KeyEvent event) {
364 boolean handled = super.onKeyDown(keyCode, event);
365 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
366 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
367 keyCode, event);
368 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
369 // something usable has been typed - dispatch it now.
370 final String str = mDefaultKeySsb.toString();
371
372 boolean isDialable = true;
373 final int count = str.length();
374 for (int i = 0; i < count; i++) {
375 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
376 isDialable = false;
377 break;
378 }
379 }
380 Intent intent;
381 if (isDialable) {
382 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
383 } else {
384 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
385 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
386 }
387
388 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
389
390 try {
391 startActivity(intent);
392 } catch (android.content.ActivityNotFoundException ex) {
393 // Oh well... no one knows how to filter/dial. Life goes on.
394 }
395
396 mDefaultKeySsb.clear();
397 mDefaultKeySsb.clearSpans();
398 Selection.setSelection(mDefaultKeySsb, 0);
399
400 return true;
401 }
402 }
403
404 return handled;
405 }
406
407 /**
408 * Restores the previous state, if it exists.
409 *
410 * @param savedState The previous state.
411 */
412 private void restoreState(Bundle savedState) {
413 if (savedState == null) {
414 return;
415 }
416
417 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
418 if (currentScreen > -1) {
419 mWorkspace.setCurrentScreen(currentScreen);
420 }
421
422 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
423 if (addScreen > -1) {
424 mAddItemCellInfo = new CellLayout.CellInfo();
425 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
426 addItemCellInfo.valid = true;
427 addItemCellInfo.screen = addScreen;
428 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
429 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
430 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
431 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
432 addItemCellInfo.findVacantCellsFromOccupied(
433 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
434 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
435 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
436 mRestoring = true;
437 }
438
439 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
440 if (renameFolder) {
441 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
442 mFolderInfo = sModel.getFolderById(this, id);
443 mRestoring = true;
444 }
445 }
446
447 /**
448 * Finds all the views we need and configure them properly.
449 */
450 private void setupViews() {
451 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
452 final DragLayer dragLayer = mDragLayer;
453
454 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
455 final Workspace workspace = mWorkspace;
456
457 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
458 final SlidingDrawer drawer = mDrawer;
459
460 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
461 final AllAppsGridView grid = mAllAppsGrid;
462
463 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
464
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700465 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
466 mHandleView.setLauncher(this);
467 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800468 mHandleIcon.setCrossFadeEnabled(true);
469
470 drawer.lock();
471 final DrawerManager drawerManager = new DrawerManager();
472 drawer.setOnDrawerOpenListener(drawerManager);
473 drawer.setOnDrawerCloseListener(drawerManager);
474 drawer.setOnDrawerScrollListener(drawerManager);
475
476 grid.setTextFilterEnabled(true);
477 grid.setDragger(dragLayer);
478 grid.setLauncher(this);
479
480 workspace.setOnLongClickListener(this);
481 workspace.setDragger(dragLayer);
482 workspace.setLauncher(this);
483 loadWallpaper();
484
485 deleteZone.setLauncher(this);
486 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700487 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800488
489 dragLayer.setIgnoredDropTarget(grid);
490 dragLayer.setDragScoller(workspace);
491 dragLayer.setDragListener(deleteZone);
492 }
493
494 /**
495 * Creates a view representing a shortcut.
496 *
497 * @param info The data structure describing the shortcut.
498 *
499 * @return A View inflated from R.layout.application.
500 */
501 View createShortcut(ApplicationInfo info) {
502 return createShortcut(R.layout.application,
503 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
504 }
505
506 /**
507 * Creates a view representing a shortcut inflated from the specified resource.
508 *
509 * @param layoutResId The id of the XML layout used to create the shortcut.
510 * @param parent The group the shortcut belongs to.
511 * @param info The data structure describing the shortcut.
512 *
513 * @return A View inflated from layoutResId.
514 */
515 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
516 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
517
518 if (!info.filtered) {
519 info.icon = Utilities.createIconThumbnail(info.icon, this);
520 info.filtered = true;
521 }
522
523 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
524 favorite.setText(info.title);
525 favorite.setTag(info);
526 favorite.setOnClickListener(this);
527
528 return favorite;
529 }
530
531 /**
532 * Add an application shortcut to the workspace.
533 *
534 * @param data The intent describing the application.
535 * @param cellInfo The position on screen where to create the shortcut.
536 */
537 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
538 boolean insertAtFirst) {
539 cellInfo.screen = mWorkspace.getCurrentScreen();
540 if (!findSingleSlot(cellInfo)) return;
541
542 // Find details for this application
543 ComponentName component = data.getComponent();
544 PackageManager packageManager = context.getPackageManager();
545 ActivityInfo activityInfo = null;
546 try {
547 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
548 } catch (NameNotFoundException e) {
549 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
550 }
551
552 if (activityInfo != null) {
553 ApplicationInfo itemInfo = new ApplicationInfo();
554
555 itemInfo.title = activityInfo.loadLabel(packageManager);
556 if (itemInfo.title == null) {
557 itemInfo.title = activityInfo.name;
558 }
559
560 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
561 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
562 itemInfo.icon = activityInfo.loadIcon(packageManager);
563 itemInfo.container = ItemInfo.NO_ID;
564
565 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
566 }
567 }
568
569 /**
570 * Add a shortcut to the workspace.
571 *
572 * @param data The intent describing the shortcut.
573 * @param cellInfo The position on screen where to create the shortcut.
574 * @param insertAtFirst
575 */
576 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
577 boolean insertAtFirst) {
578 cellInfo.screen = mWorkspace.getCurrentScreen();
579 if (!findSingleSlot(cellInfo)) return;
580
581 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
582
583 if (!mRestoring) {
584 sModel.addDesktopItem(info);
585
586 final View view = createShortcut(info);
587 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
588 } else if (sModel.isDesktopLoaded()) {
589 sModel.addDesktopItem(info);
590 }
591 }
592
593
594 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700595 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800596 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700597 * @param data The intent describing the appWidgetId.
598 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800599 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700600 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800601 boolean insertAtFirst) {
602
603 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700604 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800605
606 Log.d(LOG_TAG, "dumping extras content="+extras.toString());
607
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700608 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800609
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700610 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800611 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700612 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800613
614 // Try finding open space on Launcher screen
615 final int[] xy = mCellCoordinates;
616 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
617
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700618 // Build Launcher-specific widget info and save to database
619 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800620 launcherInfo.spanX = spans[0];
621 launcherInfo.spanY = spans[1];
622
623 LauncherModel.addItemToDatabase(this, launcherInfo,
624 LauncherSettings.Favorites.CONTAINER_DESKTOP,
625 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
626
627 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700628 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629
630 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700631 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700633 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634 launcherInfo.hostView.setTag(launcherInfo);
635
636 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
637 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
638 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700639 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640 }
641 }
642
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700643 public LauncherAppWidgetHost getAppWidgetHost() {
644 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800645 }
646
647 static ApplicationInfo addShortcut(Context context, Intent data,
648 CellLayout.CellInfo cellInfo, boolean notify) {
649
650 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
651 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
652 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
653
654 Drawable icon = null;
655 boolean filtered = false;
656 boolean customIcon = false;
657 Intent.ShortcutIconResource iconResource = null;
658
659 if (bitmap != null) {
660 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
661 filtered = true;
662 customIcon = true;
663 } else {
664 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
665 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
666 try {
667 iconResource = (Intent.ShortcutIconResource) extra;
668 final PackageManager packageManager = context.getPackageManager();
669 Resources resources = packageManager.getResourcesForApplication(
670 iconResource.packageName);
671 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
672 icon = resources.getDrawable(id);
673 } catch (Exception e) {
674 Log.w(LOG_TAG, "Could not load shortcut icon: " + extra);
675 }
676 }
677 }
678
679 if (icon == null) {
680 icon = context.getPackageManager().getDefaultActivityIcon();
681 }
682
683 final ApplicationInfo info = new ApplicationInfo();
684 info.icon = icon;
685 info.filtered = filtered;
686 info.title = name;
687 info.intent = intent;
688 info.customIcon = customIcon;
689 info.iconResource = iconResource;
690
691 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
692 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
693 return info;
694 }
695
696 @Override
697 protected void onNewIntent(Intent intent) {
698 super.onNewIntent(intent);
699
700 // Close the menu
701 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
702 getWindow().closeAllPanels();
703
704 try {
705 dismissDialog(DIALOG_CREATE_SHORTCUT);
706 // Unlock the workspace if the dialog was showing
707 mWorkspace.unlock();
708 } catch (Exception e) {
709 // An exception is thrown if the dialog is not visible, which is fine
710 }
711
712 try {
713 dismissDialog(DIALOG_RENAME_FOLDER);
714 // Unlock the workspace if the dialog was showing
715 mWorkspace.unlock();
716 } catch (Exception e) {
717 // An exception is thrown if the dialog is not visible, which is fine
718 }
719
720 // If we are already in front we go back to the default screen,
721 // otherwise we don't
722 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
723 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
724 if (!mWorkspace.isDefaultScreenShowing()) {
725 mWorkspace.moveToDefaultScreen();
726 }
727 closeDrawer();
728 View v = getWindow().peekDecorView();
729 if (v != null && v.getWindowToken() != null) {
730 InputMethodManager imm = (InputMethodManager)getSystemService(
731 INPUT_METHOD_SERVICE);
732 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
733 }
734 } else {
735 closeDrawer(false);
736 }
737 }
738 }
739
740 @Override
741 protected void onRestoreInstanceState(Bundle savedInstanceState) {
742 // Do not call super here
743 mSavedInstanceState = savedInstanceState;
744 }
745
746 @Override
747 protected void onSaveInstanceState(Bundle outState) {
748 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
749
750 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
751 if (folders.size() > 0) {
752 final int count = folders.size();
753 long[] ids = new long[count];
754 for (int i = 0; i < count; i++) {
755 final FolderInfo info = folders.get(i).getInfo();
756 ids[i] = info.id;
757 }
758 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
759 } else {
760 super.onSaveInstanceState(outState);
761 }
762
763 if (mDrawer.isOpened()) {
764 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
765 }
766
767 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
768 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
769 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
770
771 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
772 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
773 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
774 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
775 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
776 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
777 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
778 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
779 layout.getOccupiedCells());
780 }
781
782 if (mFolderInfo != null && mWaitingForResult) {
783 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
784 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
785 }
786 }
787
788 @Override
789 public void onDestroy() {
790 mDestroyed = true;
791
792 super.onDestroy();
793
794 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700795 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800796 } catch (NullPointerException ex) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700797 Log.w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800798 }
799
800 TextKeyListener.getInstance().release();
801
802 mAllAppsGrid.clearTextFilter();
803 mAllAppsGrid.setAdapter(null);
804 sModel.unbind();
805 sModel.abortLoaders();
806
807 getContentResolver().unregisterContentObserver(mObserver);
808 unregisterReceiver(mApplicationsReceiver);
809 }
810
811 @Override
812 public void startActivityForResult(Intent intent, int requestCode) {
813 mWaitingForResult = true;
814 super.startActivityForResult(intent, requestCode);
815 }
816
817 @Override
818 public void startSearch(String initialQuery, boolean selectInitialQuery,
819 Bundle appSearchData, boolean globalSearch) {
820 if (appSearchData == null) {
821 appSearchData = new Bundle();
822 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
823 }
824 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
825 }
826
827 @Override
828 public boolean onCreateOptionsMenu(Menu menu) {
829 if (mDesktopLocked) return false;
830
831 super.onCreateOptionsMenu(menu);
832 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
833 .setIcon(android.R.drawable.ic_menu_add)
834 .setAlphabeticShortcut('A');
835 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
836 .setIcon(android.R.drawable.ic_menu_gallery)
837 .setAlphabeticShortcut('W');
838 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
839 .setIcon(android.R.drawable.ic_search_category_default)
840 .setAlphabeticShortcut(SearchManager.MENU_KEY);
841 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
842 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
843 .setAlphabeticShortcut('N');
844
845 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
846 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
847 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
848
849 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
850 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
851 .setIntent(settings);
852
853 return true;
854 }
855
856 @Override
857 public boolean onPrepareOptionsMenu(Menu menu) {
858 super.onPrepareOptionsMenu(menu);
859
860 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
861 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
862
863 return true;
864 }
865
866 @Override
867 public boolean onOptionsItemSelected(MenuItem item) {
868 switch (item.getItemId()) {
869 case MENU_ADD:
870 addItems();
871 return true;
872 case MENU_WALLPAPER_SETTINGS:
873 startWallpaper();
874 return true;
875 case MENU_SEARCH:
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700876 onSearchRequested();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800877 return true;
878 case MENU_NOTIFICATIONS:
879 showNotifications();
880 return true;
881 }
882
883 return super.onOptionsItemSelected(item);
884 }
885
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700886 @Override
887 public boolean onSearchRequested() {
888 if (mWorkspace.snapToSearch()) {
889 closeDrawer(true); // search widget: get drawer out of the way
890 return true;
891 } else {
892 return super.onSearchRequested(); // no search widget: use system search UI
893 }
894 }
895
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800896 private void addItems() {
897 showAddDialog(mMenuAddInfo);
898 }
899
900 private void removeShortcutsForPackage(String packageName) {
901 if (packageName != null && packageName.length() > 0) {
902 mWorkspace.removeShortcutsForPackage(packageName);
903 }
904 }
905
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700906 void addAppWidget(Intent data) {
907 // TODO: catch bad widget exception when sent
908 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
909 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800910
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700911 if (appWidget.configure != null) {
912 // Launch over to configure widget, if needed
913 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
914 intent.setComponent(appWidget.configure);
915 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800916
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700917 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800918 } else {
919 // Otherwise just add it
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700920 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800921 }
922 }
923
924 void addSearch() {
925 final Widget info = Widget.makeSearch();
926 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
927
928 final int[] xy = mCellCoordinates;
929 final int spanX = info.spanX;
930 final int spanY = info.spanY;
931
932 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
933
934 sModel.addDesktopItem(info);
935 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
936 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
937
938 final View view = mInflater.inflate(info.layoutResource, null);
939 view.setTag(info);
940
941 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
942 }
943
944 void addShortcut(Intent intent) {
945 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
946 }
947
948 void addLiveFolder(Intent intent) {
949 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
950 }
951
952 void addFolder(boolean insertAtFirst) {
953 UserFolderInfo folderInfo = new UserFolderInfo();
954 folderInfo.title = getText(R.string.folder_name);
955
956 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
957 cellInfo.screen = mWorkspace.getCurrentScreen();
958 if (!findSingleSlot(cellInfo)) return;
959
960 // Update the model
961 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
962 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
963 sModel.addDesktopItem(folderInfo);
964 sModel.addFolder(folderInfo);
965
966 // Create the view
967 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
968 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
969 mWorkspace.addInCurrentScreen(newFolder,
970 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
971 }
972
973 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
974 boolean insertAtFirst) {
975 cellInfo.screen = mWorkspace.getCurrentScreen();
976 if (!findSingleSlot(cellInfo)) return;
977
978 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
979
980 if (!mRestoring) {
981 sModel.addDesktopItem(info);
982
983 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
984 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
985 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
986 } else if (sModel.isDesktopLoaded()) {
987 sModel.addDesktopItem(info);
988 }
989 }
990
991 static LiveFolderInfo addLiveFolder(Context context, Intent data,
992 CellLayout.CellInfo cellInfo, boolean notify) {
993
994 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
995 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
996
997 Drawable icon = null;
998 boolean filtered = false;
999 Intent.ShortcutIconResource iconResource = null;
1000
1001 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1002 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1003 try {
1004 iconResource = (Intent.ShortcutIconResource) extra;
1005 final PackageManager packageManager = context.getPackageManager();
1006 Resources resources = packageManager.getResourcesForApplication(
1007 iconResource.packageName);
1008 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1009 icon = resources.getDrawable(id);
1010 } catch (Exception e) {
1011 Log.w(LOG_TAG, "Could not load live folder icon: " + extra);
1012 }
1013 }
1014
1015 if (icon == null) {
1016 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1017 }
1018
1019 final LiveFolderInfo info = new LiveFolderInfo();
1020 info.icon = icon;
1021 info.filtered = filtered;
1022 info.title = name;
1023 info.iconResource = iconResource;
1024 info.uri = data.getData();
1025 info.baseIntent = baseIntent;
1026 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1027 LiveFolders.DISPLAY_MODE_GRID);
1028
1029 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1030 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1031 sModel.addFolder(info);
1032
1033 return info;
1034 }
1035
1036 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1037 final int[] xy = new int[2];
1038 if (findSlot(cellInfo, xy, 1, 1)) {
1039 cellInfo.cellX = xy[0];
1040 cellInfo.cellY = xy[1];
1041 return true;
1042 }
1043 return false;
1044 }
1045
1046 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1047 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1048 boolean[] occupied = mSavedState != null ?
1049 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1050 cellInfo = mWorkspace.findAllVacantCells(occupied);
1051 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1052 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1053 return false;
1054 }
1055 }
1056 return true;
1057 }
1058
1059 private void showNotifications() {
1060 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1061 if (statusBar != null) {
1062 statusBar.expand();
1063 }
1064 }
1065
1066 private void startWallpaper() {
1067 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1068 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1069 }
1070
1071 /**
1072 * Registers various intent receivers. The current implementation registers
1073 * only a wallpaper intent receiver to let other applications change the
1074 * wallpaper.
1075 */
1076 private void registerIntentReceivers() {
1077 if (sWallpaperReceiver == null) {
1078 final Application application = getApplication();
1079
1080 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1081
1082 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1083 application.registerReceiver(sWallpaperReceiver, filter);
1084 } else {
1085 sWallpaperReceiver.setLauncher(this);
1086 }
1087
1088 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1089 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1090 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1091 filter.addDataScheme("package");
1092 registerReceiver(mApplicationsReceiver, filter);
1093 }
1094
1095 /**
1096 * Registers various content observers. The current implementation registers
1097 * only a favorites observer to keep track of the favorites applications.
1098 */
1099 private void registerContentObservers() {
1100 ContentResolver resolver = getContentResolver();
1101 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1102 }
1103
1104 @Override
1105 public boolean dispatchKeyEvent(KeyEvent event) {
1106 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1107 switch (event.getKeyCode()) {
1108 case KeyEvent.KEYCODE_BACK:
1109 mWorkspace.dispatchKeyEvent(event);
1110 closeFolder();
1111 closeDrawer();
1112 return true;
1113 case KeyEvent.KEYCODE_HOME:
1114 return true;
1115 }
1116 }
1117
1118 return super.dispatchKeyEvent(event);
1119 }
1120
1121 private void closeDrawer() {
1122 closeDrawer(true);
1123 }
1124
1125 private void closeDrawer(boolean animated) {
1126 if (mDrawer.isOpened()) {
1127 if (animated) {
1128 mDrawer.animateClose();
1129 } else {
1130 mDrawer.close();
1131 }
1132 if (mDrawer.hasFocus()) {
1133 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1134 }
1135 }
1136 }
1137
1138 private void closeFolder() {
1139 Folder folder = mWorkspace.getOpenFolder();
1140 if (folder != null) {
1141 closeFolder(folder);
1142 }
1143 }
1144
1145 void closeFolder(Folder folder) {
1146 folder.getInfo().opened = false;
1147 ViewGroup parent = (ViewGroup) folder.getParent();
1148 if (parent != null) {
1149 parent.removeView(folder);
1150 }
1151 folder.onClose();
1152 }
1153
1154 /**
1155 * When the notification that favorites have changed is received, requests
1156 * a favorites list refresh.
1157 */
1158 private void onFavoritesChanged() {
1159 mDesktopLocked = true;
1160 mDrawer.lock();
1161 sModel.loadUserItems(false, this, false, false);
1162 }
1163
1164 void onDesktopItemsLoaded() {
1165 if (mDestroyed) return;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001166android.util.Log.d("Home", "setting grid adapter");
1167 mAllAppsGrid.setAdapter(sModel.getApplicationsAdapter());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001168 bindDesktopItems();
1169 }
1170
1171 /**
1172 * Refreshes the shortcuts shown on the workspace.
1173 */
1174 private void bindDesktopItems() {
1175 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001176 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
1177 if (shortcuts == null || appWidgets == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001178 return;
1179 }
1180
1181 final Workspace workspace = mWorkspace;
1182 int count = workspace.getChildCount();
1183 for (int i = 0; i < count; i++) {
1184 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1185 }
1186
1187 if (DEBUG_USER_INTERFACE) {
1188 android.widget.Button finishButton = new android.widget.Button(this);
1189 finishButton.setText("Finish");
1190 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1191
1192 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1193 public void onClick(View v) {
1194 finish();
1195 }
1196 });
1197 }
1198
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001199 final DesktopBinder binder = new DesktopBinder(this, shortcuts, appWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001200 binder.startBindingItems();
1201 }
1202
1203 private void bindItems(Launcher.DesktopBinder binder,
1204 ArrayList<ItemInfo> shortcuts, int start, int count) {
1205
1206 final Workspace workspace = mWorkspace;
1207 final boolean desktopLocked = mDesktopLocked;
1208
1209 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1210 int i = start;
1211
1212 for ( ; i < end; i++) {
1213 final ItemInfo item = shortcuts.get(i);
1214 switch (item.itemType) {
1215 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1216 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1217 final View shortcut = createShortcut((ApplicationInfo) item);
1218 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1219 !desktopLocked);
1220 break;
1221 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1222 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1223 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1224 (UserFolderInfo) item);
1225 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1226 !desktopLocked);
1227 break;
1228 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1229 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1230 R.layout.live_folder_icon, this,
1231 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1232 (LiveFolderInfo) item);
1233 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1234 !desktopLocked);
1235 break;
1236 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1237 final int screen = workspace.getCurrentScreen();
1238 final View view = mInflater.inflate(R.layout.widget_search,
1239 (ViewGroup) workspace.getChildAt(screen), false);
1240
1241 final Widget widget = (Widget) item;
1242 view.setTag(widget);
1243
1244 workspace.addWidget(view, widget, !desktopLocked);
1245 break;
1246 }
1247 }
1248
1249 workspace.requestLayout();
1250
1251 if (end >= count) {
1252 finishBindDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001253 binder.startBindingAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001254 } else {
1255 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1256 }
1257 }
1258
1259 private void finishBindDesktopItems() {
1260 if (mSavedState != null) {
1261 if (!mWorkspace.hasFocus()) {
1262 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1263 }
1264
1265 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1266 if (userFolders != null) {
1267 for (long folderId : userFolders) {
1268 final FolderInfo info = sModel.findFolderById(folderId);
1269 if (info != null) {
1270 openFolder(info);
1271 }
1272 }
1273 final Folder openFolder = mWorkspace.getOpenFolder();
1274 if (openFolder != null) {
1275 openFolder.requestFocus();
1276 }
1277 }
1278
1279 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1280 if (allApps) {
1281 mDrawer.open();
1282 }
1283
1284 mSavedState = null;
1285 }
1286
1287 if (mSavedInstanceState != null) {
1288 super.onRestoreInstanceState(mSavedInstanceState);
1289 mSavedInstanceState = null;
1290 }
1291
1292 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1293 mDrawer.requestFocus();
1294 }
1295
1296 mDesktopLocked = false;
1297 mDrawer.unlock();
1298 }
1299
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001300 private void bindAppWidgets(Launcher.DesktopBinder binder,
1301 ArrayList<LauncherAppWidgetInfo> appWidgets, int start, int count) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001302
1303 final Workspace workspace = mWorkspace;
1304 final boolean desktopLocked = mDesktopLocked;
1305
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001306 final int end = Math.min(start + DesktopBinder.APPWIDGETS_COUNT, count);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001307 int i = start;
1308
1309 for ( ; i < end; i++) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001310 final LauncherAppWidgetInfo item = appWidgets.get(i);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001311
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001312 final int appWidgetId = item.appWidgetId;
1313 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1314 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001315
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001316 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 -08001317
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001318 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001319 item.hostView.setTag(item);
1320
1321 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1322 item.cellY, item.spanX, item.spanY, !desktopLocked);
1323 }
1324
1325 workspace.requestLayout();
1326
1327 if (end >= count) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001328 finishBindDesktopAppWidgets();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001329 } else {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001330 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS, i, count).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001331 }
1332 }
1333
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001334 private void finishBindDesktopAppWidgets() {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001335 }
1336
1337 DragController getDragController() {
1338 return mDragLayer;
1339 }
1340
1341 /**
1342 * Launches the intent referred by the clicked shortcut.
1343 *
1344 * @param v The view representing the clicked shortcut.
1345 */
1346 public void onClick(View v) {
1347 Object tag = v.getTag();
1348 if (tag instanceof ApplicationInfo) {
1349 // Open shortcut
1350 final Intent intent = ((ApplicationInfo) tag).intent;
1351 startActivitySafely(intent);
1352 } else if (tag instanceof FolderInfo) {
1353 handleFolderClick((FolderInfo) tag);
1354 }
1355 }
1356
1357 void startActivitySafely(Intent intent) {
1358 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1359 try {
1360 startActivity(intent);
1361 } catch (ActivityNotFoundException e) {
1362 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1363 } catch (SecurityException e) {
1364 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1365 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1366 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1367 "or use the exported attribute for this activity.", e);
1368 }
1369 }
1370
1371 private void handleFolderClick(FolderInfo folderInfo) {
1372 if (!folderInfo.opened) {
1373 // Close any open folder
1374 closeFolder();
1375 // Open the requested folder
1376 openFolder(folderInfo);
1377 } else {
1378 // Find the open folder...
1379 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1380 int folderScreen;
1381 if (openFolder != null) {
1382 folderScreen = mWorkspace.getScreenForView(openFolder);
1383 // .. and close it
1384 closeFolder(openFolder);
1385 if (folderScreen != mWorkspace.getCurrentScreen()) {
1386 // Close any folder open on the current screen
1387 closeFolder();
1388 // Pull the folder onto this screen
1389 openFolder(folderInfo);
1390 }
1391 }
1392 }
1393 }
1394
1395 private void loadWallpaper() {
1396 // The first time the application is started, we load the wallpaper from
1397 // the ApplicationContext
1398 if (sWallpaper == null) {
1399 final Drawable drawable = getWallpaper();
1400 if (drawable instanceof BitmapDrawable) {
1401 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1402 } else {
1403 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1404 }
1405 }
1406 mWorkspace.loadWallpaper(sWallpaper);
1407 }
1408
1409 /**
1410 * Opens the user fodler described by the specified tag. The opening of the folder
1411 * is animated relative to the specified View. If the View is null, no animation
1412 * is played.
1413 *
1414 * @param folderInfo The FolderInfo describing the folder to open.
1415 */
1416 private void openFolder(FolderInfo folderInfo) {
1417 Folder openFolder;
1418
1419 if (folderInfo instanceof UserFolderInfo) {
1420 openFolder = UserFolder.fromXml(this);
1421 } else if (folderInfo instanceof LiveFolderInfo) {
1422 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1423 } else {
1424 return;
1425 }
1426
1427 openFolder.setDragger(mDragLayer);
1428 openFolder.setLauncher(this);
1429
1430 openFolder.bind(folderInfo);
1431 folderInfo.opened = true;
1432
1433 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1434 openFolder.onOpen();
1435 }
1436
1437 /**
1438 * Returns true if the workspace is being loaded. When the workspace is loading,
1439 * no user interaction should be allowed to avoid any conflict.
1440 *
1441 * @return True if the workspace is locked, false otherwise.
1442 */
1443 boolean isWorkspaceLocked() {
1444 return mDesktopLocked;
1445 }
1446
1447 public boolean onLongClick(View v) {
1448 if (mDesktopLocked) {
1449 return false;
1450 }
1451
1452 if (!(v instanceof CellLayout)) {
1453 v = (View) v.getParent();
1454 }
1455
1456 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1457
1458 // This happens when long clicking an item with the dpad/trackball
1459 if (cellInfo == null) {
1460 return true;
1461 }
1462
1463 if (mWorkspace.allowLongPress()) {
1464 if (cellInfo.cell == null) {
1465 if (cellInfo.valid) {
1466 // User long pressed on empty space
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001467 mWorkspace.setAllowLongPress(false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001468 showAddDialog(cellInfo);
1469 }
1470 } else {
1471 if (!(cellInfo.cell instanceof Folder)) {
1472 // User long pressed on an item
1473 mWorkspace.startDrag(cellInfo);
1474 }
1475 }
1476 }
1477 return true;
1478 }
1479
1480 static LauncherModel getModel() {
1481 return sModel;
1482 }
1483
1484 void closeAllApplications() {
1485 mDrawer.close();
1486 }
1487
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001488 View getDrawerHandle() {
1489 return mHandleView;
1490 }
1491
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001492 boolean isDrawerDown() {
1493 return !mDrawer.isMoving() && !mDrawer.isOpened();
1494 }
1495
1496 boolean isDrawerUp() {
1497 return mDrawer.isOpened() && !mDrawer.isMoving();
1498 }
1499
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001500 boolean isDrawerMoving() {
1501 return mDrawer.isMoving();
1502 }
1503
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001504 Workspace getWorkspace() {
1505 return mWorkspace;
1506 }
1507
1508 GridView getApplicationsGrid() {
1509 return mAllAppsGrid;
1510 }
1511
1512 @Override
1513 protected Dialog onCreateDialog(int id) {
1514 switch (id) {
1515 case DIALOG_CREATE_SHORTCUT:
1516 return new CreateShortcut().createDialog();
1517 case DIALOG_RENAME_FOLDER:
1518 return new RenameFolder().createDialog();
1519 }
1520
1521 return super.onCreateDialog(id);
1522 }
1523
1524 @Override
1525 protected void onPrepareDialog(int id, Dialog dialog) {
1526 switch (id) {
1527 case DIALOG_CREATE_SHORTCUT:
1528 mWorkspace.lock();
1529 break;
1530 case DIALOG_RENAME_FOLDER:
1531 mWorkspace.lock();
1532 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1533 final CharSequence text = mFolderInfo.title;
1534 input.setText(text);
1535 input.setSelection(0, text.length());
1536 break;
1537 }
1538 }
1539
1540 void showRenameDialog(FolderInfo info) {
1541 mFolderInfo = info;
1542 mWaitingForResult = true;
1543 showDialog(DIALOG_RENAME_FOLDER);
1544 }
1545
1546 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1547 mAddItemCellInfo = cellInfo;
1548 mWaitingForResult = true;
1549 showDialog(DIALOG_CREATE_SHORTCUT);
1550 }
1551
1552 private class RenameFolder {
1553 private EditText mInput;
1554
1555 Dialog createDialog() {
1556 mWaitingForResult = true;
1557 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1558 mInput = (EditText) layout.findViewById(R.id.folder_name);
1559
1560 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1561 builder.setIcon(0);
1562 builder.setTitle(getString(R.string.rename_folder_title));
1563 builder.setCancelable(true);
1564 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1565 public void onCancel(DialogInterface dialog) {
1566 cleanup();
1567 }
1568 });
1569 builder.setNegativeButton(getString(R.string.cancel_action),
1570 new Dialog.OnClickListener() {
1571 public void onClick(DialogInterface dialog, int which) {
1572 cleanup();
1573 }
1574 }
1575 );
1576 builder.setPositiveButton(getString(R.string.rename_action),
1577 new Dialog.OnClickListener() {
1578 public void onClick(DialogInterface dialog, int which) {
1579 changeFolderName();
1580 }
1581 }
1582 );
1583 builder.setView(layout);
1584 return builder.create();
1585 }
1586
1587 private void changeFolderName() {
1588 final String name = mInput.getText().toString();
1589 if (!TextUtils.isEmpty(name)) {
1590 // Make sure we have the right folder info
1591 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1592 mFolderInfo.title = name;
1593 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1594
1595 if (mDesktopLocked) {
1596 mDrawer.lock();
1597 sModel.loadUserItems(false, Launcher.this, false, false);
1598 } else {
1599 final FolderIcon folderIcon = (FolderIcon)
1600 mWorkspace.getViewForTag(mFolderInfo);
1601 if (folderIcon != null) {
1602 folderIcon.setText(name);
1603 getWorkspace().requestLayout();
1604 } else {
1605 mDesktopLocked = true;
1606 mDrawer.lock();
1607 sModel.loadUserItems(false, Launcher.this, false, false);
1608 }
1609 }
1610 }
1611 cleanup();
1612 }
1613
1614 private void cleanup() {
1615 mWorkspace.unlock();
1616 dismissDialog(DIALOG_RENAME_FOLDER);
1617 mWaitingForResult = false;
1618 mFolderInfo = null;
1619 }
1620 }
1621
1622 /**
1623 * Displays the shortcut creation dialog and launches, if necessary, the
1624 * appropriate activity.
1625 */
1626 private class CreateShortcut implements AdapterView.OnItemClickListener,
1627 DialogInterface.OnCancelListener {
1628 private AddAdapter mAdapter;
1629 private ListView mList;
1630
1631 Dialog createDialog() {
1632 mWaitingForResult = true;
1633
1634 mAdapter = new AddAdapter(Launcher.this);
1635
1636 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1637 builder.setTitle(getString(R.string.menu_item_add_item));
1638 builder.setIcon(0);
1639
1640 mList = (ListView)
1641 View.inflate(Launcher.this, R.layout.create_shortcut_list, null);
1642 mList.setAdapter(mAdapter);
1643 mList.setOnItemClickListener(this);
1644 builder.setView(mList);
1645 builder.setInverseBackgroundForced(true);
1646
1647 AlertDialog dialog = builder.create();
1648 dialog.setOnCancelListener(this);
1649
1650 WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
1651 attributes.gravity = Gravity.TOP;
1652 dialog.onWindowAttributesChanged(attributes);
1653
1654 return dialog;
1655 }
1656
1657 public void onCancel(DialogInterface dialog) {
1658 mWaitingForResult = false;
1659 cleanup();
1660 }
1661
1662 private void cleanup() {
1663 mWorkspace.unlock();
1664 dismissDialog(DIALOG_CREATE_SHORTCUT);
1665 }
1666
1667 public void onItemClick(AdapterView parent, View view, int position, long id) {
1668 // handle which item was clicked based on position
1669 // this will launch off pick intent
1670
1671 Object tag = view.getTag();
1672 if (tag instanceof AddAdapter.ListItem) {
1673 AddAdapter.ListItem item = (AddAdapter.ListItem) tag;
1674 cleanup();
1675 switch (item.actionTag) {
1676 case AddAdapter.ITEM_APPLICATION: {
1677 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
1678 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
1679
1680 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1681 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
1682 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
1683 break;
1684 }
1685
1686 case AddAdapter.ITEM_SHORTCUT: {
1687 Intent shortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
1688
1689 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1690 pickIntent.putExtra(Intent.EXTRA_INTENT, shortcutIntent);
1691 pickIntent.putExtra(Intent.EXTRA_TITLE,
1692 getText(R.string.title_select_shortcut));
1693 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1694 break;
1695 }
1696
1697 case AddAdapter.ITEM_SEARCH: {
1698 addSearch();
1699 break;
1700 }
1701
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001702 case AddAdapter.ITEM_APPWIDGET: {
1703 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001704
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001705 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1706 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1707 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001708 break;
1709 }
1710
1711 case AddAdapter.ITEM_LIVE_FOLDER: {
1712 Intent liveFolderIntent = new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER);
1713
1714 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1715 pickIntent.putExtra(Intent.EXTRA_INTENT, liveFolderIntent);
1716 pickIntent.putExtra(Intent.EXTRA_TITLE,
1717 getText(R.string.title_select_live_folder));
1718 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1719 break;
1720 }
1721
1722 case AddAdapter.ITEM_FOLDER: {
1723 addFolder(!mDesktopLocked);
1724 dismissDialog(DIALOG_CREATE_SHORTCUT);
1725 break;
1726 }
1727
1728 case AddAdapter.ITEM_WALLPAPER: {
1729 startWallpaper();
1730 break;
1731 }
1732
1733 }
1734
1735 }
1736 }
1737 }
1738
1739 /**
1740 * Receives notifications when applications are added/removed.
1741 */
1742 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1743 @Override
1744 public void onReceive(Context context, Intent intent) {
1745 boolean reloadWorkspace = false;
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001746android.util.Log.d("Home", "application intent received: " + intent.getAction());
1747android.util.Log.d("Home", " --> " + intent.getData());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001748 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 Project31dd5032009-03-03 19:32:27 -08001756 if (!reloadWorkspace) {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001757android.util.Log.d("Home", " --> loading apps");
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001758 sModel.loadApplications(false, Launcher.this, false);
1759 } else {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001760android.util.Log.d("Home", " --> loading workspace");
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001761 sModel.loadUserItems(false, Launcher.this, false, true);
1762 }
1763 }
1764 }
1765
1766 /**
1767 * Receives notifications whenever the user favorites have changed.
1768 */
1769 private class FavoritesChangeObserver extends ContentObserver {
1770 public FavoritesChangeObserver() {
1771 super(new Handler());
1772 }
1773
1774 @Override
1775 public void onChange(boolean selfChange) {
1776 onFavoritesChanged();
1777 }
1778 }
1779
1780 /**
1781 * Receives intents from other applications to change the wallpaper.
1782 */
1783 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1784 private final Application mApplication;
1785 private WeakReference<Launcher> mLauncher;
1786
1787 WallpaperIntentReceiver(Application application, Launcher launcher) {
1788 mApplication = application;
1789 setLauncher(launcher);
1790 }
1791
1792 void setLauncher(Launcher launcher) {
1793 mLauncher = new WeakReference<Launcher>(launcher);
1794 }
1795
1796 @Override
1797 public void onReceive(Context context, Intent intent) {
1798 // Load the wallpaper from the ApplicationContext and store it locally
1799 // until the Launcher Activity is ready to use it
1800 final Drawable drawable = mApplication.getWallpaper();
1801 if (drawable instanceof BitmapDrawable) {
1802 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1803 } else {
1804 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1805 }
1806
1807 // If Launcher is alive, notify we have a new wallpaper
1808 if (mLauncher != null) {
1809 final Launcher launcher = mLauncher.get();
1810 if (launcher != null) {
1811 launcher.loadWallpaper();
1812 }
1813 }
1814 }
1815 }
1816
1817 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1818 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1819 private boolean mOpen;
1820
1821 public void onDrawerOpened() {
1822 if (!mOpen) {
1823 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001824
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001825 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001826 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001827
1828 mOpen = true;
1829 }
1830 }
1831
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001832 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1833 view.getDrawingRect(bounds);
1834
1835 while (view != mDragLayer) {
1836 bounds.offset(view.getLeft(), view.getTop());
1837 view = (View) view.getParent();
1838 }
1839 }
1840
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001841 public void onDrawerClosed() {
1842 if (mOpen) {
1843 mHandleIcon.reverseTransition(150);
1844 mWorkspace.mDrawerBounds.setEmpty();
1845 mOpen = false;
1846 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001847
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001848 mAllAppsGrid.setSelection(0);
1849 mAllAppsGrid.clearTextFilter();
1850 }
1851
1852 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001853 if (PROFILE_DRAWER) {
1854 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1855 }
1856
1857 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1858 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001859 }
1860
1861 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001862 if (PROFILE_DRAWER) {
1863 android.os.Debug.stopMethodTracing();
1864 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001865 }
1866 }
1867
1868 private static class DesktopBinder extends Handler {
1869 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001870 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001871 // Number of items to bind in every pass
1872 static final int ITEMS_COUNT = 6;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001873 static final int APPWIDGETS_COUNT = 1;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001874
1875 private final ArrayList<ItemInfo> mShortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001876 private final ArrayList<LauncherAppWidgetInfo> mAppWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001877 private final WeakReference<Launcher> mLauncher;
1878
1879 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001880 ArrayList<LauncherAppWidgetInfo> appWidgets) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001881
1882 mLauncher = new WeakReference<Launcher>(launcher);
1883 mShortcuts = shortcuts;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001884 mAppWidgets = appWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001885 }
1886
1887 public void startBindingItems() {
1888 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
1889 }
1890
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001891 public void startBindingAppWidgets() {
1892 obtainMessage(MESSAGE_BIND_APPWIDGETS, 0, mAppWidgets.size()).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001893 }
1894
1895 @Override
1896 public void handleMessage(Message msg) {
1897 Launcher launcher = mLauncher.get();
1898 if (launcher == null) {
1899 return;
1900 }
1901
1902 switch (msg.what) {
1903 case MESSAGE_BIND_ITEMS: {
1904 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
1905 break;
1906 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001907 case MESSAGE_BIND_APPWIDGETS: {
1908 launcher.bindAppWidgets(this, mAppWidgets, msg.arg1, msg.arg2);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001909 break;
1910 }
1911 }
1912 }
1913 }
1914}