blob: d84e67da744828eeb18f5160f46b742c5e1a01fa [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;
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -070034import android.content.Intent.ShortcutIconResource;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080035import android.content.pm.ActivityInfo;
36import android.content.pm.PackageManager;
37import android.content.pm.PackageManager.NameNotFoundException;
38import android.content.res.Resources;
39import android.content.res.Configuration;
40import android.database.ContentObserver;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080041import android.graphics.Bitmap;
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -070042import android.graphics.BitmapFactory;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080043import android.graphics.Rect;
44import android.graphics.drawable.BitmapDrawable;
45import android.graphics.drawable.Drawable;
46import android.graphics.drawable.TransitionDrawable;
47import android.net.Uri;
48import android.os.Bundle;
49import android.os.Handler;
50import android.os.IBinder;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -070051import android.os.Looper;
52import android.os.MessageQueue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080053import android.os.Parcelable;
54import android.os.RemoteException;
55import android.os.ServiceManager;
56import android.os.Message;
57import android.provider.*;
58import android.telephony.PhoneNumberUtils;
59import android.text.Selection;
60import android.text.SpannableStringBuilder;
61import android.text.TextUtils;
62import android.text.method.TextKeyListener;
63import android.util.Log;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070064import static android.util.Log.*;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065import android.view.Display;
66import android.view.Gravity;
67import android.view.KeyEvent;
68import android.view.LayoutInflater;
69import android.view.Menu;
70import android.view.MenuItem;
71import android.view.View;
72import android.view.ViewGroup;
73import android.view.WindowManager;
74import android.view.View.OnLongClickListener;
75import android.view.inputmethod.InputMethodManager;
76import android.widget.AdapterView;
77import android.widget.EditText;
78import android.widget.ListView;
79import android.widget.TextView;
80import android.widget.Toast;
81import android.widget.GridView;
82import android.widget.SlidingDrawer;
83import android.app.IWallpaperService;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070084import android.appwidget.AppWidgetManager;
85import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080086
87import java.lang.ref.WeakReference;
88import java.util.ArrayList;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -070089import java.util.LinkedList;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080090
91/**
92 * Default launcher application.
93 */
94public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
95 static final String LOG_TAG = "Launcher";
96 static final boolean LOGD = false;
97
98 private static final boolean PROFILE_STARTUP = false;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070099 private static final boolean PROFILE_DRAWER = false;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -0700100 private static final boolean PROFILE_ROTATE = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800101 private static final boolean DEBUG_USER_INTERFACE = false;
102
103 private static final int WALLPAPER_SCREENS_SPAN = 2;
104
105 private static final int MENU_GROUP_ADD = 1;
106 private static final int MENU_ADD = Menu.FIRST + 1;
107 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
108 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
109 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
110 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
111
112 private static final int REQUEST_CREATE_SHORTCUT = 1;
113 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700114 private static final int REQUEST_CREATE_APPWIDGET = 5;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800115 private static final int REQUEST_PICK_APPLICATION = 6;
116 private static final int REQUEST_PICK_SHORTCUT = 7;
117 private static final int REQUEST_PICK_LIVE_FOLDER = 8;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700118 private static final int REQUEST_PICK_APPWIDGET = 9;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800119
120 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
121
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700122 static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
123 static final String SEARCH_WIDGET = "search_widget";
124
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800125 static final int SCREEN_COUNT = 3;
126 static final int DEFAULT_SCREN = 1;
127 static final int NUMBER_CELLS_X = 4;
128 static final int NUMBER_CELLS_Y = 4;
129
130 private static final int DIALOG_CREATE_SHORTCUT = 1;
131 static final int DIALOG_RENAME_FOLDER = 2;
132
133 private static final String PREFERENCES = "launcher";
134 private static final String KEY_LOCALE = "locale";
135 private static final String KEY_MCC = "mcc";
136 private static final String KEY_MNC = "mnc";
137
138 // Type: int
139 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
140 // Type: boolean
141 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
142 // Type: long
143 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
144 // Type: int
145 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
146 // Type: int
147 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
148 // Type: int
149 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
150 // Type: int
151 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
152 // Type: int
153 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
154 // Type: int
155 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
156 // Type: int
157 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
158 // Type: int[]
159 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
160 // Type: boolean
161 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
162 // Type: long
163 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
164
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700165 private static final LauncherModel sModel = new LauncherModel();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800166
167 private static Bitmap sWallpaper;
168
169 private static final Object sLock = new Object();
170 private static int sScreen = DEFAULT_SCREN;
171
172 private static WallpaperIntentReceiver sWallpaperReceiver;
173
174 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
175 private final ContentObserver mObserver = new FavoritesChangeObserver();
176
177 private LayoutInflater mInflater;
178
179 private DragLayer mDragLayer;
180 private Workspace mWorkspace;
181
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700182 private AppWidgetManager mAppWidgetManager;
183 private LauncherAppWidgetHost mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800184
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700185 static final int APPWIDGET_HOST_ID = 1024;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800186
187 private CellLayout.CellInfo mAddItemCellInfo;
188 private CellLayout.CellInfo mMenuAddInfo;
189 private final int[] mCellCoordinates = new int[2];
190 private FolderInfo mFolderInfo;
191
192 private SlidingDrawer mDrawer;
193 private TransitionDrawable mHandleIcon;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700194 private HandleView mHandleView;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800195 private AllAppsGridView mAllAppsGrid;
196
197 private boolean mDesktopLocked = true;
198 private Bundle mSavedState;
199
200 private SpannableStringBuilder mDefaultKeySsb = null;
201
202 private boolean mDestroyed;
203
204 private boolean mRestoring;
205 private boolean mWaitingForResult;
206 private boolean mLocaleChanged;
207
208 private Bundle mSavedInstanceState;
209
Jeffrey Sharkey99c87582009-03-24 17:59:43 -0700210 private DesktopBinder mBinder;
211
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800212 @Override
213 protected void onCreate(Bundle savedInstanceState) {
214 super.onCreate(savedInstanceState);
215 mInflater = getLayoutInflater();
216
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700217 mAppWidgetManager = AppWidgetManager.getInstance(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800218
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700219 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
220 mAppWidgetHost.startListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800221
222 if (PROFILE_STARTUP) {
223 android.os.Debug.startMethodTracing("/sdcard/launcher");
224 }
225
226 checkForLocaleChange();
227 setWallpaperDimension();
228
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800229 setContentView(R.layout.launcher);
230 setupViews();
231
232 registerIntentReceivers();
233 registerContentObservers();
234
235 mSavedState = savedInstanceState;
236 restoreState(mSavedState);
237
238 if (PROFILE_STARTUP) {
239 android.os.Debug.stopMethodTracing();
240 }
241
242 if (!mRestoring) {
243 startLoaders();
244 }
245
246 // For handling default keys
247 mDefaultKeySsb = new SpannableStringBuilder();
248 Selection.setSelection(mDefaultKeySsb, 0);
249 }
250
251 private void checkForLocaleChange() {
252 final SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
253 final Configuration configuration = getResources().getConfiguration();
254
255 final String previousLocale = preferences.getString(KEY_LOCALE, null);
256 final String locale = configuration.locale.toString();
257
258 final int previousMcc = preferences.getInt(KEY_MCC, -1);
259 final int mcc = configuration.mcc;
260
261 final int previousMnc = preferences.getInt(KEY_MNC, -1);
262 final int mnc = configuration.mnc;
263
264 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
265
266 if (mLocaleChanged) {
267 final SharedPreferences.Editor editor = preferences.edit();
268 editor.putString(KEY_LOCALE, locale);
269 editor.putInt(KEY_MCC, mcc);
270 editor.putInt(KEY_MNC, mnc);
271 editor.commit();
272 }
273 }
274
275 static int getScreen() {
276 synchronized (sLock) {
277 return sScreen;
278 }
279 }
280
281 static void setScreen(int screen) {
282 synchronized (sLock) {
283 sScreen = screen;
284 }
285 }
286
287 private void startLoaders() {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700288 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
289 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
290
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800291 mRestoring = false;
292 }
293
294 private void setWallpaperDimension() {
295 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
296 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
297
298 Display display = getWindowManager().getDefaultDisplay();
299 boolean isPortrait = display.getWidth() < display.getHeight();
300
301 final int width = isPortrait ? display.getWidth() : display.getHeight();
302 final int height = isPortrait ? display.getHeight() : display.getWidth();
303 try {
304 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
305 } catch (RemoteException e) {
306 // System is dead!
307 }
308 }
309
310 @Override
311 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
312 // The pattern used here is that a user PICKs a specific application,
313 // which, depending on the target, might need to CREATE the actual target.
314
315 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
316 // launch over to the Music app to actually CREATE_SHORTCUT.
317
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -0700318 Resources res = getResources();
319
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800320 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
321 switch (requestCode) {
322 case REQUEST_PICK_APPLICATION:
323 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
324 break;
325 case REQUEST_PICK_SHORTCUT:
326 addShortcut(data);
327 break;
328 case REQUEST_CREATE_SHORTCUT:
329 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
330 break;
331 case REQUEST_PICK_LIVE_FOLDER:
332 addLiveFolder(data);
333 break;
334 case REQUEST_CREATE_LIVE_FOLDER:
335 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
336 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700337 case REQUEST_PICK_APPWIDGET:
338 addAppWidget(data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700340 case REQUEST_CREATE_APPWIDGET:
341 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800342 break;
343 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700344 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800345 resultCode == RESULT_CANCELED && data != null) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700346 // Clean up the appWidgetId if we canceled
347 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
348 if (appWidgetId != -1) {
349 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800350 }
351 }
352 mWaitingForResult = false;
353 }
354
355 @Override
356 protected void onResume() {
357 super.onResume();
358
359 if (mRestoring) {
360 startLoaders();
361 }
362 }
363
364 @Override
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700365 protected void onPause() {
366 super.onPause();
367 closeDrawer(false);
368 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -0700369
370 @Override
371 public Object onRetainNonConfigurationInstance() {
372 // Flag any binder to stop early before switching
373 if (mBinder != null) {
374 mBinder.mTerminate = true;
375 }
376
377 if (PROFILE_ROTATE) {
378 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
379 }
380 return null;
381 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700382
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800383 private boolean acceptFilter() {
384 final InputMethodManager inputManager = (InputMethodManager)
385 getSystemService(Context.INPUT_METHOD_SERVICE);
386 return !inputManager.isFullscreenMode();
387 }
388
389 @Override
390 public boolean onKeyDown(int keyCode, KeyEvent event) {
391 boolean handled = super.onKeyDown(keyCode, event);
392 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
393 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
394 keyCode, event);
395 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
396 // something usable has been typed - dispatch it now.
397 final String str = mDefaultKeySsb.toString();
398
399 boolean isDialable = true;
400 final int count = str.length();
401 for (int i = 0; i < count; i++) {
402 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
403 isDialable = false;
404 break;
405 }
406 }
407 Intent intent;
408 if (isDialable) {
409 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
410 } else {
411 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
412 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
413 }
414
415 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
416
417 try {
418 startActivity(intent);
419 } catch (android.content.ActivityNotFoundException ex) {
420 // Oh well... no one knows how to filter/dial. Life goes on.
421 }
422
423 mDefaultKeySsb.clear();
424 mDefaultKeySsb.clearSpans();
425 Selection.setSelection(mDefaultKeySsb, 0);
426
427 return true;
428 }
429 }
430
431 return handled;
432 }
433
434 /**
435 * Restores the previous state, if it exists.
436 *
437 * @param savedState The previous state.
438 */
439 private void restoreState(Bundle savedState) {
440 if (savedState == null) {
441 return;
442 }
443
444 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
445 if (currentScreen > -1) {
446 mWorkspace.setCurrentScreen(currentScreen);
447 }
448
449 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
450 if (addScreen > -1) {
451 mAddItemCellInfo = new CellLayout.CellInfo();
452 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
453 addItemCellInfo.valid = true;
454 addItemCellInfo.screen = addScreen;
455 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
456 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
457 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
458 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
459 addItemCellInfo.findVacantCellsFromOccupied(
460 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
461 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
462 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
463 mRestoring = true;
464 }
465
466 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
467 if (renameFolder) {
468 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
469 mFolderInfo = sModel.getFolderById(this, id);
470 mRestoring = true;
471 }
472 }
473
474 /**
475 * Finds all the views we need and configure them properly.
476 */
477 private void setupViews() {
478 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
479 final DragLayer dragLayer = mDragLayer;
480
481 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
482 final Workspace workspace = mWorkspace;
483
484 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
485 final SlidingDrawer drawer = mDrawer;
486
487 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
488 final AllAppsGridView grid = mAllAppsGrid;
489
490 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
491
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700492 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
493 mHandleView.setLauncher(this);
494 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800495 mHandleIcon.setCrossFadeEnabled(true);
496
497 drawer.lock();
498 final DrawerManager drawerManager = new DrawerManager();
499 drawer.setOnDrawerOpenListener(drawerManager);
500 drawer.setOnDrawerCloseListener(drawerManager);
501 drawer.setOnDrawerScrollListener(drawerManager);
502
503 grid.setTextFilterEnabled(true);
504 grid.setDragger(dragLayer);
505 grid.setLauncher(this);
506
507 workspace.setOnLongClickListener(this);
508 workspace.setDragger(dragLayer);
509 workspace.setLauncher(this);
510 loadWallpaper();
511
512 deleteZone.setLauncher(this);
513 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700514 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800515
516 dragLayer.setIgnoredDropTarget(grid);
517 dragLayer.setDragScoller(workspace);
518 dragLayer.setDragListener(deleteZone);
519 }
520
521 /**
522 * Creates a view representing a shortcut.
523 *
524 * @param info The data structure describing the shortcut.
525 *
526 * @return A View inflated from R.layout.application.
527 */
528 View createShortcut(ApplicationInfo info) {
529 return createShortcut(R.layout.application,
530 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
531 }
532
533 /**
534 * Creates a view representing a shortcut inflated from the specified resource.
535 *
536 * @param layoutResId The id of the XML layout used to create the shortcut.
537 * @param parent The group the shortcut belongs to.
538 * @param info The data structure describing the shortcut.
539 *
540 * @return A View inflated from layoutResId.
541 */
542 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
543 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
544
545 if (!info.filtered) {
546 info.icon = Utilities.createIconThumbnail(info.icon, this);
547 info.filtered = true;
548 }
549
550 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
551 favorite.setText(info.title);
552 favorite.setTag(info);
553 favorite.setOnClickListener(this);
554
555 return favorite;
556 }
557
558 /**
559 * Add an application shortcut to the workspace.
560 *
561 * @param data The intent describing the application.
562 * @param cellInfo The position on screen where to create the shortcut.
563 */
564 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
565 boolean insertAtFirst) {
566 cellInfo.screen = mWorkspace.getCurrentScreen();
567 if (!findSingleSlot(cellInfo)) return;
568
569 // Find details for this application
570 ComponentName component = data.getComponent();
571 PackageManager packageManager = context.getPackageManager();
572 ActivityInfo activityInfo = null;
573 try {
574 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
575 } catch (NameNotFoundException e) {
576 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
577 }
578
579 if (activityInfo != null) {
580 ApplicationInfo itemInfo = new ApplicationInfo();
581
582 itemInfo.title = activityInfo.loadLabel(packageManager);
583 if (itemInfo.title == null) {
584 itemInfo.title = activityInfo.name;
585 }
586
587 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
588 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
589 itemInfo.icon = activityInfo.loadIcon(packageManager);
590 itemInfo.container = ItemInfo.NO_ID;
591
592 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
593 }
594 }
595
596 /**
597 * Add a shortcut to the workspace.
598 *
599 * @param data The intent describing the shortcut.
600 * @param cellInfo The position on screen where to create the shortcut.
601 * @param insertAtFirst
602 */
603 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
604 boolean insertAtFirst) {
605 cellInfo.screen = mWorkspace.getCurrentScreen();
606 if (!findSingleSlot(cellInfo)) return;
607
608 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
609
610 if (!mRestoring) {
611 sModel.addDesktopItem(info);
612
613 final View view = createShortcut(info);
614 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
615 } else if (sModel.isDesktopLoaded()) {
616 sModel.addDesktopItem(info);
617 }
618 }
619
620
621 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700622 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700624 * @param data The intent describing the appWidgetId.
625 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800626 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700627 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800628 boolean insertAtFirst) {
629
630 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700631 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800632
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700633 d(LOG_TAG, "dumping extras content="+extras.toString());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800634
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700635 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800636
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700637 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800638 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700639 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800640
641 // Try finding open space on Launcher screen
642 final int[] xy = mCellCoordinates;
643 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
644
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700645 // Build Launcher-specific widget info and save to database
646 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800647 launcherInfo.spanX = spans[0];
648 launcherInfo.spanY = spans[1];
649
650 LauncherModel.addItemToDatabase(this, launcherInfo,
651 LauncherSettings.Favorites.CONTAINER_DESKTOP,
652 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
653
654 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700655 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800656
657 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700658 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800659
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700660 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800661 launcherInfo.hostView.setTag(launcherInfo);
662
663 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
664 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
665 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700666 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 }
668 }
669
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700670 public LauncherAppWidgetHost getAppWidgetHost() {
671 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800672 }
673
674 static ApplicationInfo addShortcut(Context context, Intent data,
675 CellLayout.CellInfo cellInfo, boolean notify) {
676
677 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
678 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
679 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
680
681 Drawable icon = null;
682 boolean filtered = false;
683 boolean customIcon = false;
684 Intent.ShortcutIconResource iconResource = null;
685
686 if (bitmap != null) {
687 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
688 filtered = true;
689 customIcon = true;
690 } else {
691 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
692 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
693 try {
694 iconResource = (Intent.ShortcutIconResource) extra;
695 final PackageManager packageManager = context.getPackageManager();
696 Resources resources = packageManager.getResourcesForApplication(
697 iconResource.packageName);
698 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
699 icon = resources.getDrawable(id);
700 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700701 w(LOG_TAG, "Could not load shortcut icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800702 }
703 }
704 }
705
706 if (icon == null) {
707 icon = context.getPackageManager().getDefaultActivityIcon();
708 }
709
710 final ApplicationInfo info = new ApplicationInfo();
711 info.icon = icon;
712 info.filtered = filtered;
713 info.title = name;
714 info.intent = intent;
715 info.customIcon = customIcon;
716 info.iconResource = iconResource;
717
718 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
719 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
720 return info;
721 }
722
723 @Override
724 protected void onNewIntent(Intent intent) {
725 super.onNewIntent(intent);
726
727 // Close the menu
728 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
729 getWindow().closeAllPanels();
730
731 try {
732 dismissDialog(DIALOG_CREATE_SHORTCUT);
733 // Unlock the workspace if the dialog was showing
734 mWorkspace.unlock();
735 } catch (Exception e) {
736 // An exception is thrown if the dialog is not visible, which is fine
737 }
738
739 try {
740 dismissDialog(DIALOG_RENAME_FOLDER);
741 // Unlock the workspace if the dialog was showing
742 mWorkspace.unlock();
743 } catch (Exception e) {
744 // An exception is thrown if the dialog is not visible, which is fine
745 }
746
747 // If we are already in front we go back to the default screen,
748 // otherwise we don't
749 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
750 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
751 if (!mWorkspace.isDefaultScreenShowing()) {
752 mWorkspace.moveToDefaultScreen();
753 }
754 closeDrawer();
755 View v = getWindow().peekDecorView();
756 if (v != null && v.getWindowToken() != null) {
757 InputMethodManager imm = (InputMethodManager)getSystemService(
758 INPUT_METHOD_SERVICE);
759 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
760 }
761 } else {
762 closeDrawer(false);
763 }
764 }
765 }
766
767 @Override
768 protected void onRestoreInstanceState(Bundle savedInstanceState) {
769 // Do not call super here
770 mSavedInstanceState = savedInstanceState;
771 }
772
773 @Override
774 protected void onSaveInstanceState(Bundle outState) {
775 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
776
777 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
778 if (folders.size() > 0) {
779 final int count = folders.size();
780 long[] ids = new long[count];
781 for (int i = 0; i < count; i++) {
782 final FolderInfo info = folders.get(i).getInfo();
783 ids[i] = info.id;
784 }
785 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
786 } else {
787 super.onSaveInstanceState(outState);
788 }
789
790 if (mDrawer.isOpened()) {
791 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
792 }
793
794 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
795 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
796 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
797
798 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
799 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
800 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
801 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
802 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
803 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
804 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
805 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
806 layout.getOccupiedCells());
807 }
808
809 if (mFolderInfo != null && mWaitingForResult) {
810 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
811 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
812 }
813 }
814
815 @Override
816 public void onDestroy() {
817 mDestroyed = true;
818
819 super.onDestroy();
820
821 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700822 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800823 } catch (NullPointerException ex) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700824 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800825 }
826
827 TextKeyListener.getInstance().release();
828
829 mAllAppsGrid.clearTextFilter();
830 mAllAppsGrid.setAdapter(null);
831 sModel.unbind();
832 sModel.abortLoaders();
833
834 getContentResolver().unregisterContentObserver(mObserver);
835 unregisterReceiver(mApplicationsReceiver);
836 }
837
838 @Override
839 public void startActivityForResult(Intent intent, int requestCode) {
840 mWaitingForResult = true;
841 super.startActivityForResult(intent, requestCode);
842 }
843
844 @Override
845 public void startSearch(String initialQuery, boolean selectInitialQuery,
846 Bundle appSearchData, boolean globalSearch) {
847 if (appSearchData == null) {
848 appSearchData = new Bundle();
849 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
850 }
851 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
852 }
853
854 @Override
855 public boolean onCreateOptionsMenu(Menu menu) {
856 if (mDesktopLocked) return false;
857
858 super.onCreateOptionsMenu(menu);
859 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
860 .setIcon(android.R.drawable.ic_menu_add)
861 .setAlphabeticShortcut('A');
862 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
863 .setIcon(android.R.drawable.ic_menu_gallery)
864 .setAlphabeticShortcut('W');
865 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
866 .setIcon(android.R.drawable.ic_search_category_default)
867 .setAlphabeticShortcut(SearchManager.MENU_KEY);
868 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
869 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
870 .setAlphabeticShortcut('N');
871
872 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
873 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
874 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
875
876 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
877 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
878 .setIntent(settings);
879
880 return true;
881 }
882
883 @Override
884 public boolean onPrepareOptionsMenu(Menu menu) {
885 super.onPrepareOptionsMenu(menu);
886
887 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
888 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
889
890 return true;
891 }
892
893 @Override
894 public boolean onOptionsItemSelected(MenuItem item) {
895 switch (item.getItemId()) {
896 case MENU_ADD:
897 addItems();
898 return true;
899 case MENU_WALLPAPER_SETTINGS:
900 startWallpaper();
901 return true;
902 case MENU_SEARCH:
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700903 onSearchRequested();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800904 return true;
905 case MENU_NOTIFICATIONS:
906 showNotifications();
907 return true;
908 }
909
910 return super.onOptionsItemSelected(item);
911 }
912
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700913 @Override
914 public boolean onSearchRequested() {
915 if (mWorkspace.snapToSearch()) {
916 closeDrawer(true); // search widget: get drawer out of the way
917 return true;
918 } else {
919 return super.onSearchRequested(); // no search widget: use system search UI
920 }
921 }
922
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800923 private void addItems() {
924 showAddDialog(mMenuAddInfo);
925 }
926
927 private void removeShortcutsForPackage(String packageName) {
928 if (packageName != null && packageName.length() > 0) {
929 mWorkspace.removeShortcutsForPackage(packageName);
930 }
931 }
932
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700933 private void updateShortcutsForPackage(String packageName) {
934 if (packageName != null && packageName.length() > 0) {
935 mWorkspace.updateShortcutsForPackage(packageName);
936 }
937 }
938
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700939 void addAppWidget(Intent data) {
940 // TODO: catch bad widget exception when sent
941 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800942
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700943 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
944 if (SEARCH_WIDGET.equals(customWidget)) {
945 // We don't need this any more, since this isn't a real app widget.
946 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
947 // add the search widget
948 addSearch();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800949 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700950 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
951
952 if (appWidget.configure != null) {
953 // Launch over to configure widget, if needed
954 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
955 intent.setComponent(appWidget.configure);
956 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
957
958 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
959 } else {
960 // Otherwise just add it
961 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
962 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800963 }
964 }
965
966 void addSearch() {
967 final Widget info = Widget.makeSearch();
968 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
969
970 final int[] xy = mCellCoordinates;
971 final int spanX = info.spanX;
972 final int spanY = info.spanY;
973
974 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
975
976 sModel.addDesktopItem(info);
977 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
978 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
979
980 final View view = mInflater.inflate(info.layoutResource, null);
981 view.setTag(info);
982
983 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
984 }
985
986 void addShortcut(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -0700987 // Handle case where user selected "Applications"
988 String applicationName = getResources().getString(R.string.group_applications);
989 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
990
991 if (applicationName != null && applicationName.equals(shortcutName)) {
992 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
993 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
994
995 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
996 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
997 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
998 } else {
999 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
1000 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001001 }
1002
1003 void addLiveFolder(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001004 // Handle case where user selected "Folder"
1005 String folderName = getResources().getString(R.string.folder_name);
1006 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1007
1008 if (folderName != null && folderName.equals(shortcutName)) {
1009 addFolder(!mDesktopLocked);
1010 } else {
1011 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1012 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001013 }
1014
1015 void addFolder(boolean insertAtFirst) {
1016 UserFolderInfo folderInfo = new UserFolderInfo();
1017 folderInfo.title = getText(R.string.folder_name);
1018
1019 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1020 cellInfo.screen = mWorkspace.getCurrentScreen();
1021 if (!findSingleSlot(cellInfo)) return;
1022
1023 // Update the model
1024 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1025 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1026 sModel.addDesktopItem(folderInfo);
1027 sModel.addFolder(folderInfo);
1028
1029 // Create the view
1030 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1031 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1032 mWorkspace.addInCurrentScreen(newFolder,
1033 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1034 }
1035
1036 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
1037 boolean insertAtFirst) {
1038 cellInfo.screen = mWorkspace.getCurrentScreen();
1039 if (!findSingleSlot(cellInfo)) return;
1040
1041 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1042
1043 if (!mRestoring) {
1044 sModel.addDesktopItem(info);
1045
1046 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1047 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1048 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1049 } else if (sModel.isDesktopLoaded()) {
1050 sModel.addDesktopItem(info);
1051 }
1052 }
1053
1054 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1055 CellLayout.CellInfo cellInfo, boolean notify) {
1056
1057 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1058 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1059
1060 Drawable icon = null;
1061 boolean filtered = false;
1062 Intent.ShortcutIconResource iconResource = null;
1063
1064 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1065 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1066 try {
1067 iconResource = (Intent.ShortcutIconResource) extra;
1068 final PackageManager packageManager = context.getPackageManager();
1069 Resources resources = packageManager.getResourcesForApplication(
1070 iconResource.packageName);
1071 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1072 icon = resources.getDrawable(id);
1073 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001074 w(LOG_TAG, "Could not load live folder icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001075 }
1076 }
1077
1078 if (icon == null) {
1079 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1080 }
1081
1082 final LiveFolderInfo info = new LiveFolderInfo();
1083 info.icon = icon;
1084 info.filtered = filtered;
1085 info.title = name;
1086 info.iconResource = iconResource;
1087 info.uri = data.getData();
1088 info.baseIntent = baseIntent;
1089 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1090 LiveFolders.DISPLAY_MODE_GRID);
1091
1092 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1093 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1094 sModel.addFolder(info);
1095
1096 return info;
1097 }
1098
1099 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1100 final int[] xy = new int[2];
1101 if (findSlot(cellInfo, xy, 1, 1)) {
1102 cellInfo.cellX = xy[0];
1103 cellInfo.cellY = xy[1];
1104 return true;
1105 }
1106 return false;
1107 }
1108
1109 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1110 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1111 boolean[] occupied = mSavedState != null ?
1112 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1113 cellInfo = mWorkspace.findAllVacantCells(occupied);
1114 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1115 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1116 return false;
1117 }
1118 }
1119 return true;
1120 }
1121
1122 private void showNotifications() {
1123 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1124 if (statusBar != null) {
1125 statusBar.expand();
1126 }
1127 }
1128
1129 private void startWallpaper() {
1130 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1131 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1132 }
1133
1134 /**
1135 * Registers various intent receivers. The current implementation registers
1136 * only a wallpaper intent receiver to let other applications change the
1137 * wallpaper.
1138 */
1139 private void registerIntentReceivers() {
1140 if (sWallpaperReceiver == null) {
1141 final Application application = getApplication();
1142
1143 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1144
1145 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1146 application.registerReceiver(sWallpaperReceiver, filter);
1147 } else {
1148 sWallpaperReceiver.setLauncher(this);
1149 }
1150
1151 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1152 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1153 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1154 filter.addDataScheme("package");
1155 registerReceiver(mApplicationsReceiver, filter);
1156 }
1157
1158 /**
1159 * Registers various content observers. The current implementation registers
1160 * only a favorites observer to keep track of the favorites applications.
1161 */
1162 private void registerContentObservers() {
1163 ContentResolver resolver = getContentResolver();
1164 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1165 }
1166
1167 @Override
1168 public boolean dispatchKeyEvent(KeyEvent event) {
1169 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1170 switch (event.getKeyCode()) {
1171 case KeyEvent.KEYCODE_BACK:
1172 mWorkspace.dispatchKeyEvent(event);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001173 if (mDrawer.isOpened()) {
1174 closeDrawer();
1175 } else {
1176 closeFolder();
1177 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001178 return true;
1179 case KeyEvent.KEYCODE_HOME:
1180 return true;
1181 }
1182 }
1183
1184 return super.dispatchKeyEvent(event);
1185 }
1186
1187 private void closeDrawer() {
1188 closeDrawer(true);
1189 }
1190
1191 private void closeDrawer(boolean animated) {
1192 if (mDrawer.isOpened()) {
1193 if (animated) {
1194 mDrawer.animateClose();
1195 } else {
1196 mDrawer.close();
1197 }
1198 if (mDrawer.hasFocus()) {
1199 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1200 }
1201 }
1202 }
1203
1204 private void closeFolder() {
1205 Folder folder = mWorkspace.getOpenFolder();
1206 if (folder != null) {
1207 closeFolder(folder);
1208 }
1209 }
1210
1211 void closeFolder(Folder folder) {
1212 folder.getInfo().opened = false;
1213 ViewGroup parent = (ViewGroup) folder.getParent();
1214 if (parent != null) {
1215 parent.removeView(folder);
1216 }
1217 folder.onClose();
1218 }
1219
1220 /**
1221 * When the notification that favorites have changed is received, requests
1222 * a favorites list refresh.
1223 */
1224 private void onFavoritesChanged() {
1225 mDesktopLocked = true;
1226 mDrawer.lock();
1227 sModel.loadUserItems(false, this, false, false);
1228 }
1229
1230 void onDesktopItemsLoaded() {
1231 if (mDestroyed) return;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001232 bindDesktopItems();
1233 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001234
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001235 /**
1236 * Refreshes the shortcuts shown on the workspace.
1237 */
1238 private void bindDesktopItems() {
1239 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001240 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001241 final ApplicationsAdapter drawerAdapter = sModel.getApplicationsAdapter();
1242 if (shortcuts == null || appWidgets == null || drawerAdapter == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001243 return;
1244 }
1245
1246 final Workspace workspace = mWorkspace;
1247 int count = workspace.getChildCount();
1248 for (int i = 0; i < count; i++) {
1249 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1250 }
1251
1252 if (DEBUG_USER_INTERFACE) {
1253 android.widget.Button finishButton = new android.widget.Button(this);
1254 finishButton.setText("Finish");
1255 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1256
1257 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1258 public void onClick(View v) {
1259 finish();
1260 }
1261 });
1262 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001263
1264 // Flag any old binder to terminate early
1265 if (mBinder != null) {
1266 mBinder.mTerminate = true;
1267 }
1268
1269 mBinder = new DesktopBinder(this, shortcuts, appWidgets, drawerAdapter);
1270 mBinder.startWhenIdle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001271 }
1272
1273 private void bindItems(Launcher.DesktopBinder binder,
1274 ArrayList<ItemInfo> shortcuts, int start, int count) {
1275
1276 final Workspace workspace = mWorkspace;
1277 final boolean desktopLocked = mDesktopLocked;
1278
1279 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1280 int i = start;
1281
1282 for ( ; i < end; i++) {
1283 final ItemInfo item = shortcuts.get(i);
1284 switch (item.itemType) {
1285 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1286 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1287 final View shortcut = createShortcut((ApplicationInfo) item);
1288 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1289 !desktopLocked);
1290 break;
1291 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1292 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1293 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1294 (UserFolderInfo) item);
1295 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1296 !desktopLocked);
1297 break;
1298 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1299 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1300 R.layout.live_folder_icon, this,
1301 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1302 (LiveFolderInfo) item);
1303 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1304 !desktopLocked);
1305 break;
1306 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1307 final int screen = workspace.getCurrentScreen();
1308 final View view = mInflater.inflate(R.layout.widget_search,
1309 (ViewGroup) workspace.getChildAt(screen), false);
1310
1311 final Widget widget = (Widget) item;
1312 view.setTag(widget);
1313
1314 workspace.addWidget(view, widget, !desktopLocked);
1315 break;
1316 }
1317 }
1318
1319 workspace.requestLayout();
1320
1321 if (end >= count) {
1322 finishBindDesktopItems();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001323 binder.startBindingDrawer();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001324 } else {
1325 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1326 }
1327 }
1328
1329 private void finishBindDesktopItems() {
1330 if (mSavedState != null) {
1331 if (!mWorkspace.hasFocus()) {
1332 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1333 }
1334
1335 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1336 if (userFolders != null) {
1337 for (long folderId : userFolders) {
1338 final FolderInfo info = sModel.findFolderById(folderId);
1339 if (info != null) {
1340 openFolder(info);
1341 }
1342 }
1343 final Folder openFolder = mWorkspace.getOpenFolder();
1344 if (openFolder != null) {
1345 openFolder.requestFocus();
1346 }
1347 }
1348
1349 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1350 if (allApps) {
1351 mDrawer.open();
1352 }
1353
1354 mSavedState = null;
1355 }
1356
1357 if (mSavedInstanceState != null) {
1358 super.onRestoreInstanceState(mSavedInstanceState);
1359 mSavedInstanceState = null;
1360 }
1361
1362 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1363 mDrawer.requestFocus();
1364 }
1365
1366 mDesktopLocked = false;
1367 mDrawer.unlock();
1368 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001369
1370 private void bindDrawer(Launcher.DesktopBinder binder,
1371 ApplicationsAdapter drawerAdapter) {
1372 mAllAppsGrid.setAdapter(drawerAdapter);
1373 binder.startBindingAppWidgets();
1374 }
1375
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001376 private void bindAppWidgets(Launcher.DesktopBinder binder,
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001377 LinkedList<LauncherAppWidgetInfo> appWidgets) {
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001378
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001379 final Workspace workspace = mWorkspace;
1380 final boolean desktopLocked = mDesktopLocked;
1381
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001382 if (!appWidgets.isEmpty()) {
1383 final LauncherAppWidgetInfo item = appWidgets.removeFirst();
1384
1385 final int appWidgetId = item.appWidgetId;
1386 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1387 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1388
1389 if (LOGD) d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s", appWidgetId, appWidgetInfo));
1390
1391 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1392 item.hostView.setTag(item);
1393
1394 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1395 item.cellY, item.spanX, item.spanY, !desktopLocked);
1396
1397 workspace.requestLayout();
1398 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001399
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001400 if (appWidgets.isEmpty()) {
1401 if (PROFILE_ROTATE) {
1402 android.os.Debug.stopMethodTracing();
1403 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001404 } else {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001405 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001406 }
1407 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001408
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001409 DragController getDragController() {
1410 return mDragLayer;
1411 }
1412
1413 /**
1414 * Launches the intent referred by the clicked shortcut.
1415 *
1416 * @param v The view representing the clicked shortcut.
1417 */
1418 public void onClick(View v) {
1419 Object tag = v.getTag();
1420 if (tag instanceof ApplicationInfo) {
1421 // Open shortcut
1422 final Intent intent = ((ApplicationInfo) tag).intent;
1423 startActivitySafely(intent);
1424 } else if (tag instanceof FolderInfo) {
1425 handleFolderClick((FolderInfo) tag);
1426 }
1427 }
1428
1429 void startActivitySafely(Intent intent) {
1430 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1431 try {
1432 startActivity(intent);
1433 } catch (ActivityNotFoundException e) {
1434 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1435 } catch (SecurityException e) {
1436 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1437 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1438 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1439 "or use the exported attribute for this activity.", e);
1440 }
1441 }
1442
1443 private void handleFolderClick(FolderInfo folderInfo) {
1444 if (!folderInfo.opened) {
1445 // Close any open folder
1446 closeFolder();
1447 // Open the requested folder
1448 openFolder(folderInfo);
1449 } else {
1450 // Find the open folder...
1451 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1452 int folderScreen;
1453 if (openFolder != null) {
1454 folderScreen = mWorkspace.getScreenForView(openFolder);
1455 // .. and close it
1456 closeFolder(openFolder);
1457 if (folderScreen != mWorkspace.getCurrentScreen()) {
1458 // Close any folder open on the current screen
1459 closeFolder();
1460 // Pull the folder onto this screen
1461 openFolder(folderInfo);
1462 }
1463 }
1464 }
1465 }
1466
1467 private void loadWallpaper() {
1468 // The first time the application is started, we load the wallpaper from
1469 // the ApplicationContext
1470 if (sWallpaper == null) {
1471 final Drawable drawable = getWallpaper();
1472 if (drawable instanceof BitmapDrawable) {
1473 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1474 } else {
1475 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1476 }
1477 }
1478 mWorkspace.loadWallpaper(sWallpaper);
1479 }
1480
1481 /**
1482 * Opens the user fodler described by the specified tag. The opening of the folder
1483 * is animated relative to the specified View. If the View is null, no animation
1484 * is played.
1485 *
1486 * @param folderInfo The FolderInfo describing the folder to open.
1487 */
1488 private void openFolder(FolderInfo folderInfo) {
1489 Folder openFolder;
1490
1491 if (folderInfo instanceof UserFolderInfo) {
1492 openFolder = UserFolder.fromXml(this);
1493 } else if (folderInfo instanceof LiveFolderInfo) {
1494 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1495 } else {
1496 return;
1497 }
1498
1499 openFolder.setDragger(mDragLayer);
1500 openFolder.setLauncher(this);
1501
1502 openFolder.bind(folderInfo);
1503 folderInfo.opened = true;
1504
1505 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1506 openFolder.onOpen();
1507 }
1508
1509 /**
1510 * Returns true if the workspace is being loaded. When the workspace is loading,
1511 * no user interaction should be allowed to avoid any conflict.
1512 *
1513 * @return True if the workspace is locked, false otherwise.
1514 */
1515 boolean isWorkspaceLocked() {
1516 return mDesktopLocked;
1517 }
1518
1519 public boolean onLongClick(View v) {
1520 if (mDesktopLocked) {
1521 return false;
1522 }
1523
1524 if (!(v instanceof CellLayout)) {
1525 v = (View) v.getParent();
1526 }
1527
1528 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1529
1530 // This happens when long clicking an item with the dpad/trackball
1531 if (cellInfo == null) {
1532 return true;
1533 }
1534
1535 if (mWorkspace.allowLongPress()) {
1536 if (cellInfo.cell == null) {
1537 if (cellInfo.valid) {
1538 // User long pressed on empty space
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001539 mWorkspace.setAllowLongPress(false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001540 showAddDialog(cellInfo);
1541 }
1542 } else {
1543 if (!(cellInfo.cell instanceof Folder)) {
1544 // User long pressed on an item
1545 mWorkspace.startDrag(cellInfo);
1546 }
1547 }
1548 }
1549 return true;
1550 }
1551
1552 static LauncherModel getModel() {
1553 return sModel;
1554 }
1555
1556 void closeAllApplications() {
1557 mDrawer.close();
1558 }
1559
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001560 View getDrawerHandle() {
1561 return mHandleView;
1562 }
1563
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001564 boolean isDrawerDown() {
1565 return !mDrawer.isMoving() && !mDrawer.isOpened();
1566 }
1567
1568 boolean isDrawerUp() {
1569 return mDrawer.isOpened() && !mDrawer.isMoving();
1570 }
1571
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001572 boolean isDrawerMoving() {
1573 return mDrawer.isMoving();
1574 }
1575
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001576 Workspace getWorkspace() {
1577 return mWorkspace;
1578 }
1579
1580 GridView getApplicationsGrid() {
1581 return mAllAppsGrid;
1582 }
1583
1584 @Override
1585 protected Dialog onCreateDialog(int id) {
1586 switch (id) {
1587 case DIALOG_CREATE_SHORTCUT:
1588 return new CreateShortcut().createDialog();
1589 case DIALOG_RENAME_FOLDER:
1590 return new RenameFolder().createDialog();
1591 }
1592
1593 return super.onCreateDialog(id);
1594 }
1595
1596 @Override
1597 protected void onPrepareDialog(int id, Dialog dialog) {
1598 switch (id) {
1599 case DIALOG_CREATE_SHORTCUT:
1600 mWorkspace.lock();
1601 break;
1602 case DIALOG_RENAME_FOLDER:
1603 mWorkspace.lock();
1604 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1605 final CharSequence text = mFolderInfo.title;
1606 input.setText(text);
1607 input.setSelection(0, text.length());
1608 break;
1609 }
1610 }
1611
1612 void showRenameDialog(FolderInfo info) {
1613 mFolderInfo = info;
1614 mWaitingForResult = true;
1615 showDialog(DIALOG_RENAME_FOLDER);
1616 }
1617
1618 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1619 mAddItemCellInfo = cellInfo;
1620 mWaitingForResult = true;
1621 showDialog(DIALOG_CREATE_SHORTCUT);
1622 }
1623
1624 private class RenameFolder {
1625 private EditText mInput;
1626
1627 Dialog createDialog() {
1628 mWaitingForResult = true;
1629 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1630 mInput = (EditText) layout.findViewById(R.id.folder_name);
1631
1632 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1633 builder.setIcon(0);
1634 builder.setTitle(getString(R.string.rename_folder_title));
1635 builder.setCancelable(true);
1636 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1637 public void onCancel(DialogInterface dialog) {
1638 cleanup();
1639 }
1640 });
1641 builder.setNegativeButton(getString(R.string.cancel_action),
1642 new Dialog.OnClickListener() {
1643 public void onClick(DialogInterface dialog, int which) {
1644 cleanup();
1645 }
1646 }
1647 );
1648 builder.setPositiveButton(getString(R.string.rename_action),
1649 new Dialog.OnClickListener() {
1650 public void onClick(DialogInterface dialog, int which) {
1651 changeFolderName();
1652 }
1653 }
1654 );
1655 builder.setView(layout);
1656 return builder.create();
1657 }
1658
1659 private void changeFolderName() {
1660 final String name = mInput.getText().toString();
1661 if (!TextUtils.isEmpty(name)) {
1662 // Make sure we have the right folder info
1663 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1664 mFolderInfo.title = name;
1665 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1666
1667 if (mDesktopLocked) {
1668 mDrawer.lock();
1669 sModel.loadUserItems(false, Launcher.this, false, false);
1670 } else {
1671 final FolderIcon folderIcon = (FolderIcon)
1672 mWorkspace.getViewForTag(mFolderInfo);
1673 if (folderIcon != null) {
1674 folderIcon.setText(name);
1675 getWorkspace().requestLayout();
1676 } else {
1677 mDesktopLocked = true;
1678 mDrawer.lock();
1679 sModel.loadUserItems(false, Launcher.this, false, false);
1680 }
1681 }
1682 }
1683 cleanup();
1684 }
1685
1686 private void cleanup() {
1687 mWorkspace.unlock();
1688 dismissDialog(DIALOG_RENAME_FOLDER);
1689 mWaitingForResult = false;
1690 mFolderInfo = null;
1691 }
1692 }
1693
1694 /**
1695 * Displays the shortcut creation dialog and launches, if necessary, the
1696 * appropriate activity.
1697 */
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001698 private class CreateShortcut implements DialogInterface.OnClickListener,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001699 DialogInterface.OnCancelListener {
1700 private AddAdapter mAdapter;
1701 private ListView mList;
1702
1703 Dialog createDialog() {
1704 mWaitingForResult = true;
1705
1706 mAdapter = new AddAdapter(Launcher.this);
1707
1708 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1709 builder.setTitle(getString(R.string.menu_item_add_item));
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001710 builder.setAdapter(mAdapter, this);
1711
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001712 builder.setView(mList);
1713 builder.setInverseBackgroundForced(true);
1714
1715 AlertDialog dialog = builder.create();
1716 dialog.setOnCancelListener(this);
1717
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001718 return dialog;
1719 }
1720
1721 public void onCancel(DialogInterface dialog) {
1722 mWaitingForResult = false;
1723 cleanup();
1724 }
1725
1726 private void cleanup() {
1727 mWorkspace.unlock();
1728 dismissDialog(DIALOG_CREATE_SHORTCUT);
1729 }
1730
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001731 /**
1732 * Handle the action clicked in the "Add to home" dialog.
1733 */
1734 public void onClick(DialogInterface dialog, int which) {
1735 Resources res = getResources();
1736 cleanup();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001737
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001738 switch (which) {
1739 case AddAdapter.ITEM_SHORTCUT: {
1740 // Insert extra item to handle picking application
1741 Bundle bundle = new Bundle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001742
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001743 ArrayList<String> shortcutNames = new ArrayList<String>();
1744 shortcutNames.add(res.getString(R.string.group_applications));
1745 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001746
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001747 ArrayList<ShortcutIconResource> shortcutIcons =
1748 new ArrayList<ShortcutIconResource>();
1749 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1750 R.drawable.ic_launcher_application));
1751 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001752
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001753 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1754 pickIntent.putExtra(Intent.EXTRA_INTENT,
1755 new Intent(Intent.ACTION_CREATE_SHORTCUT));
1756 pickIntent.putExtra(Intent.EXTRA_TITLE,
1757 getText(R.string.title_select_shortcut));
1758 pickIntent.putExtras(bundle);
1759
1760 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1761 break;
1762 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001763
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001764 case AddAdapter.ITEM_APPWIDGET: {
1765 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
1766
1767 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1768 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1769 // add the search widget
1770 ArrayList<AppWidgetProviderInfo> customInfo =
1771 new ArrayList<AppWidgetProviderInfo>();
1772 AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1773 info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1774 info.label = getString(R.string.group_search);
1775 info.icon = R.drawable.ic_search_widget;
1776 customInfo.add(info);
1777 pickIntent.putParcelableArrayListExtra(
1778 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1779 ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1780 Bundle b = new Bundle();
1781 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1782 customExtras.add(b);
1783 pickIntent.putParcelableArrayListExtra(
1784 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1785 // start the pick activity
1786 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
1787 break;
1788 }
1789
1790 case AddAdapter.ITEM_LIVE_FOLDER: {
1791 // Insert extra item to handle inserting folder
1792 Bundle bundle = new Bundle();
1793
1794 ArrayList<String> shortcutNames = new ArrayList<String>();
1795 shortcutNames.add(res.getString(R.string.group_folder));
1796 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1797
1798 ArrayList<ShortcutIconResource> shortcutIcons =
1799 new ArrayList<ShortcutIconResource>();
1800 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1801 R.drawable.ic_launcher_folder));
1802 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1803
1804 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1805 pickIntent.putExtra(Intent.EXTRA_INTENT,
1806 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
1807 pickIntent.putExtra(Intent.EXTRA_TITLE,
1808 getText(R.string.title_select_live_folder));
1809 pickIntent.putExtras(bundle);
1810
1811 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1812 break;
1813 }
1814
1815 case AddAdapter.ITEM_WALLPAPER: {
1816 startWallpaper();
1817 break;
1818 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001819 }
1820 }
1821 }
1822
1823 /**
1824 * Receives notifications when applications are added/removed.
1825 */
1826 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1827 @Override
1828 public void onReceive(Context context, Intent intent) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001829 final String action = intent.getAction();
1830 final String packageName = intent.getData().getSchemeSpecificPart();
1831 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1832
1833 if (LauncherModel.DEBUG_LOADERS) {
1834 d(LauncherModel.LOG_TAG, "application intent received: " + action +
1835 ", replacing=" + replacing);
1836 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001837 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001838
1839 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1840 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1841 if (!replacing) {
1842 removeShortcutsForPackage(packageName);
1843 if (LauncherModel.DEBUG_LOADERS) {
1844 d(LauncherModel.LOG_TAG, " --> remove package");
1845 }
1846 sModel.removePackage(Launcher.this, packageName);
1847 }
1848 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1849 // later, we will update the package at this time
1850 } else {
1851 if (!replacing) {
1852 if (LauncherModel.DEBUG_LOADERS) {
1853 d(LauncherModel.LOG_TAG, " --> add package");
1854 }
1855 sModel.addPackage(Launcher.this, packageName);
1856 } else {
1857 if (LauncherModel.DEBUG_LOADERS) {
1858 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
1859 }
1860 sModel.updatePackage(Launcher.this, packageName);
1861 updateShortcutsForPackage(packageName);
1862 }
1863 }
1864 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001865 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001866 if (LauncherModel.DEBUG_LOADERS) {
1867 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
1868 }
1869 sModel.syncPackage(Launcher.this, packageName);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001870 }
1871 }
1872 }
1873
1874 /**
1875 * Receives notifications whenever the user favorites have changed.
1876 */
1877 private class FavoritesChangeObserver extends ContentObserver {
1878 public FavoritesChangeObserver() {
1879 super(new Handler());
1880 }
1881
1882 @Override
1883 public void onChange(boolean selfChange) {
1884 onFavoritesChanged();
1885 }
1886 }
1887
1888 /**
1889 * Receives intents from other applications to change the wallpaper.
1890 */
1891 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1892 private final Application mApplication;
1893 private WeakReference<Launcher> mLauncher;
1894
1895 WallpaperIntentReceiver(Application application, Launcher launcher) {
1896 mApplication = application;
1897 setLauncher(launcher);
1898 }
1899
1900 void setLauncher(Launcher launcher) {
1901 mLauncher = new WeakReference<Launcher>(launcher);
1902 }
1903
1904 @Override
1905 public void onReceive(Context context, Intent intent) {
1906 // Load the wallpaper from the ApplicationContext and store it locally
1907 // until the Launcher Activity is ready to use it
1908 final Drawable drawable = mApplication.getWallpaper();
1909 if (drawable instanceof BitmapDrawable) {
1910 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1911 } else {
1912 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1913 }
1914
1915 // If Launcher is alive, notify we have a new wallpaper
1916 if (mLauncher != null) {
1917 final Launcher launcher = mLauncher.get();
1918 if (launcher != null) {
1919 launcher.loadWallpaper();
1920 }
1921 }
1922 }
1923 }
1924
1925 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1926 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1927 private boolean mOpen;
1928
1929 public void onDrawerOpened() {
1930 if (!mOpen) {
1931 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001932
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001933 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001934 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001935
1936 mOpen = true;
1937 }
1938 }
1939
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001940 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1941 view.getDrawingRect(bounds);
1942
1943 while (view != mDragLayer) {
1944 bounds.offset(view.getLeft(), view.getTop());
1945 view = (View) view.getParent();
1946 }
1947 }
1948
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001949 public void onDrawerClosed() {
1950 if (mOpen) {
1951 mHandleIcon.reverseTransition(150);
1952 mWorkspace.mDrawerBounds.setEmpty();
1953 mOpen = false;
1954 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001955
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001956 mAllAppsGrid.setSelection(0);
1957 mAllAppsGrid.clearTextFilter();
1958 }
1959
1960 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001961 if (PROFILE_DRAWER) {
1962 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1963 }
1964
1965 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1966 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001967 }
1968
1969 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001970 if (PROFILE_DRAWER) {
1971 android.os.Debug.stopMethodTracing();
1972 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001973 }
1974 }
1975
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001976 private static class DesktopBinder extends Handler implements MessageQueue.IdleHandler {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001977 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001978 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001979 static final int MESSAGE_BIND_DRAWER = 0x3;
1980
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001981 // Number of items to bind in every pass
1982 static final int ITEMS_COUNT = 6;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001983
1984 private final ArrayList<ItemInfo> mShortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001985 private final LinkedList<LauncherAppWidgetInfo> mAppWidgets;
1986 private final ApplicationsAdapter mDrawerAdapter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001987 private final WeakReference<Launcher> mLauncher;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001988
1989 public boolean mTerminate = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001990
1991 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001992 ArrayList<LauncherAppWidgetInfo> appWidgets,
1993 ApplicationsAdapter drawerAdapter) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001994
1995 mLauncher = new WeakReference<Launcher>(launcher);
1996 mShortcuts = shortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001997 mDrawerAdapter = drawerAdapter;
1998
1999 // Sort widgets so active workspace is bound first
2000 final int currentScreen = launcher.mWorkspace.getCurrentScreen();
2001 final int size = appWidgets.size();
2002 mAppWidgets = new LinkedList<LauncherAppWidgetInfo>();
2003
2004 for (int i = 0; i < size; i++) {
2005 LauncherAppWidgetInfo appWidgetInfo = appWidgets.get(i);
2006 if (appWidgetInfo.screen == currentScreen) {
2007 mAppWidgets.addFirst(appWidgetInfo);
2008 } else {
2009 mAppWidgets.addLast(appWidgetInfo);
2010 }
2011 }
2012 }
2013
2014 public void startWhenIdle() {
2015 // Ask for notification when message queue becomes idle
2016 final MessageQueue messageQueue = Looper.myQueue();
2017 messageQueue.addIdleHandler(this);
2018 }
2019
2020 public boolean queueIdle() {
2021 // Queue is idle, so start binding items
2022 startBindingItems();
2023 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002024 }
2025
2026 public void startBindingItems() {
2027 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
2028 }
2029
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002030 public void startBindingDrawer() {
2031 obtainMessage(MESSAGE_BIND_DRAWER).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002032 }
2033
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002034 public void startBindingAppWidgets() {
2035 obtainMessage(MESSAGE_BIND_APPWIDGETS).sendToTarget();
2036 }
2037
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002038 @Override
2039 public void handleMessage(Message msg) {
2040 Launcher launcher = mLauncher.get();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002041 if (launcher == null || mTerminate) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002042 return;
2043 }
2044
2045 switch (msg.what) {
2046 case MESSAGE_BIND_ITEMS: {
2047 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
2048 break;
2049 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002050 case MESSAGE_BIND_DRAWER: {
2051 launcher.bindDrawer(this, mDrawerAdapter);
2052 break;
2053 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07002054 case MESSAGE_BIND_APPWIDGETS: {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002055 launcher.bindAppWidgets(this, mAppWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002056 break;
2057 }
2058 }
2059 }
2060 }
2061}