blob: d64669b2acf7425483c44f0a82d5addef09803e8 [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
Dianne Hackbornbd2e54d2009-03-24 21:00:33 -0700415 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
416 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800417
418 try {
419 startActivity(intent);
420 } catch (android.content.ActivityNotFoundException ex) {
421 // Oh well... no one knows how to filter/dial. Life goes on.
422 }
423
424 mDefaultKeySsb.clear();
425 mDefaultKeySsb.clearSpans();
426 Selection.setSelection(mDefaultKeySsb, 0);
427
428 return true;
429 }
430 }
431
432 return handled;
433 }
434
435 /**
436 * Restores the previous state, if it exists.
437 *
438 * @param savedState The previous state.
439 */
440 private void restoreState(Bundle savedState) {
441 if (savedState == null) {
442 return;
443 }
444
445 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
446 if (currentScreen > -1) {
447 mWorkspace.setCurrentScreen(currentScreen);
448 }
449
450 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
451 if (addScreen > -1) {
452 mAddItemCellInfo = new CellLayout.CellInfo();
453 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
454 addItemCellInfo.valid = true;
455 addItemCellInfo.screen = addScreen;
456 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
457 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
458 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
459 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
460 addItemCellInfo.findVacantCellsFromOccupied(
461 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
462 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
463 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
464 mRestoring = true;
465 }
466
467 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
468 if (renameFolder) {
469 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
470 mFolderInfo = sModel.getFolderById(this, id);
471 mRestoring = true;
472 }
473 }
474
475 /**
476 * Finds all the views we need and configure them properly.
477 */
478 private void setupViews() {
479 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
480 final DragLayer dragLayer = mDragLayer;
481
482 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
483 final Workspace workspace = mWorkspace;
484
485 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
486 final SlidingDrawer drawer = mDrawer;
487
488 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
489 final AllAppsGridView grid = mAllAppsGrid;
490
491 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
492
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700493 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
494 mHandleView.setLauncher(this);
495 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800496 mHandleIcon.setCrossFadeEnabled(true);
497
498 drawer.lock();
499 final DrawerManager drawerManager = new DrawerManager();
500 drawer.setOnDrawerOpenListener(drawerManager);
501 drawer.setOnDrawerCloseListener(drawerManager);
502 drawer.setOnDrawerScrollListener(drawerManager);
503
504 grid.setTextFilterEnabled(true);
505 grid.setDragger(dragLayer);
506 grid.setLauncher(this);
507
508 workspace.setOnLongClickListener(this);
509 workspace.setDragger(dragLayer);
510 workspace.setLauncher(this);
511 loadWallpaper();
512
513 deleteZone.setLauncher(this);
514 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700515 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800516
517 dragLayer.setIgnoredDropTarget(grid);
518 dragLayer.setDragScoller(workspace);
519 dragLayer.setDragListener(deleteZone);
520 }
521
522 /**
523 * Creates a view representing a shortcut.
524 *
525 * @param info The data structure describing the shortcut.
526 *
527 * @return A View inflated from R.layout.application.
528 */
529 View createShortcut(ApplicationInfo info) {
530 return createShortcut(R.layout.application,
531 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
532 }
533
534 /**
535 * Creates a view representing a shortcut inflated from the specified resource.
536 *
537 * @param layoutResId The id of the XML layout used to create the shortcut.
538 * @param parent The group the shortcut belongs to.
539 * @param info The data structure describing the shortcut.
540 *
541 * @return A View inflated from layoutResId.
542 */
543 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
544 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
545
546 if (!info.filtered) {
547 info.icon = Utilities.createIconThumbnail(info.icon, this);
548 info.filtered = true;
549 }
550
551 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
552 favorite.setText(info.title);
553 favorite.setTag(info);
554 favorite.setOnClickListener(this);
555
556 return favorite;
557 }
558
559 /**
560 * Add an application shortcut to the workspace.
561 *
562 * @param data The intent describing the application.
563 * @param cellInfo The position on screen where to create the shortcut.
564 */
565 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
566 boolean insertAtFirst) {
567 cellInfo.screen = mWorkspace.getCurrentScreen();
568 if (!findSingleSlot(cellInfo)) return;
569
570 // Find details for this application
571 ComponentName component = data.getComponent();
572 PackageManager packageManager = context.getPackageManager();
573 ActivityInfo activityInfo = null;
574 try {
575 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
576 } catch (NameNotFoundException e) {
577 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
578 }
579
580 if (activityInfo != null) {
581 ApplicationInfo itemInfo = new ApplicationInfo();
582
583 itemInfo.title = activityInfo.loadLabel(packageManager);
584 if (itemInfo.title == null) {
585 itemInfo.title = activityInfo.name;
586 }
587
588 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
589 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
590 itemInfo.icon = activityInfo.loadIcon(packageManager);
591 itemInfo.container = ItemInfo.NO_ID;
592
593 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
594 }
595 }
596
597 /**
598 * Add a shortcut to the workspace.
599 *
600 * @param data The intent describing the shortcut.
601 * @param cellInfo The position on screen where to create the shortcut.
602 * @param insertAtFirst
603 */
604 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
605 boolean insertAtFirst) {
606 cellInfo.screen = mWorkspace.getCurrentScreen();
607 if (!findSingleSlot(cellInfo)) return;
608
609 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
610
611 if (!mRestoring) {
612 sModel.addDesktopItem(info);
613
614 final View view = createShortcut(info);
615 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
616 } else if (sModel.isDesktopLoaded()) {
617 sModel.addDesktopItem(info);
618 }
619 }
620
621
622 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700623 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800624 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700625 * @param data The intent describing the appWidgetId.
626 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700628 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629 boolean insertAtFirst) {
630
631 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700632 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700634 d(LOG_TAG, "dumping extras content="+extras.toString());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700636 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800637
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700638 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800639 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700640 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800641
642 // Try finding open space on Launcher screen
643 final int[] xy = mCellCoordinates;
644 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
645
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700646 // Build Launcher-specific widget info and save to database
647 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800648 launcherInfo.spanX = spans[0];
649 launcherInfo.spanY = spans[1];
650
651 LauncherModel.addItemToDatabase(this, launcherInfo,
652 LauncherSettings.Favorites.CONTAINER_DESKTOP,
653 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
654
655 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700656 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800657
658 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700659 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800660
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700661 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800662 launcherInfo.hostView.setTag(launcherInfo);
663
664 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
665 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
666 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700667 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800668 }
669 }
670
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700671 public LauncherAppWidgetHost getAppWidgetHost() {
672 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800673 }
674
675 static ApplicationInfo addShortcut(Context context, Intent data,
676 CellLayout.CellInfo cellInfo, boolean notify) {
677
678 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
679 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
680 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
681
682 Drawable icon = null;
683 boolean filtered = false;
684 boolean customIcon = false;
685 Intent.ShortcutIconResource iconResource = null;
686
687 if (bitmap != null) {
688 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
689 filtered = true;
690 customIcon = true;
691 } else {
692 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
693 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
694 try {
695 iconResource = (Intent.ShortcutIconResource) extra;
696 final PackageManager packageManager = context.getPackageManager();
697 Resources resources = packageManager.getResourcesForApplication(
698 iconResource.packageName);
699 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
700 icon = resources.getDrawable(id);
701 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700702 w(LOG_TAG, "Could not load shortcut icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800703 }
704 }
705 }
706
707 if (icon == null) {
708 icon = context.getPackageManager().getDefaultActivityIcon();
709 }
710
711 final ApplicationInfo info = new ApplicationInfo();
712 info.icon = icon;
713 info.filtered = filtered;
714 info.title = name;
715 info.intent = intent;
716 info.customIcon = customIcon;
717 info.iconResource = iconResource;
718
719 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
720 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
721 return info;
722 }
723
724 @Override
725 protected void onNewIntent(Intent intent) {
726 super.onNewIntent(intent);
727
728 // Close the menu
729 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
730 getWindow().closeAllPanels();
731
732 try {
733 dismissDialog(DIALOG_CREATE_SHORTCUT);
734 // Unlock the workspace if the dialog was showing
735 mWorkspace.unlock();
736 } catch (Exception e) {
737 // An exception is thrown if the dialog is not visible, which is fine
738 }
739
740 try {
741 dismissDialog(DIALOG_RENAME_FOLDER);
742 // Unlock the workspace if the dialog was showing
743 mWorkspace.unlock();
744 } catch (Exception e) {
745 // An exception is thrown if the dialog is not visible, which is fine
746 }
747
748 // If we are already in front we go back to the default screen,
749 // otherwise we don't
750 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
751 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
752 if (!mWorkspace.isDefaultScreenShowing()) {
753 mWorkspace.moveToDefaultScreen();
754 }
755 closeDrawer();
756 View v = getWindow().peekDecorView();
757 if (v != null && v.getWindowToken() != null) {
758 InputMethodManager imm = (InputMethodManager)getSystemService(
759 INPUT_METHOD_SERVICE);
760 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
761 }
762 } else {
763 closeDrawer(false);
764 }
765 }
766 }
767
768 @Override
769 protected void onRestoreInstanceState(Bundle savedInstanceState) {
770 // Do not call super here
771 mSavedInstanceState = savedInstanceState;
772 }
773
774 @Override
775 protected void onSaveInstanceState(Bundle outState) {
776 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
777
778 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
779 if (folders.size() > 0) {
780 final int count = folders.size();
781 long[] ids = new long[count];
782 for (int i = 0; i < count; i++) {
783 final FolderInfo info = folders.get(i).getInfo();
784 ids[i] = info.id;
785 }
786 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
787 } else {
788 super.onSaveInstanceState(outState);
789 }
790
791 if (mDrawer.isOpened()) {
792 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
793 }
794
795 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
796 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
797 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
798
799 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
800 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
801 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
802 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
803 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
804 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
805 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
806 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
807 layout.getOccupiedCells());
808 }
809
810 if (mFolderInfo != null && mWaitingForResult) {
811 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
812 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
813 }
814 }
815
816 @Override
817 public void onDestroy() {
818 mDestroyed = true;
819
820 super.onDestroy();
821
822 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700823 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800824 } catch (NullPointerException ex) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700825 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800826 }
827
828 TextKeyListener.getInstance().release();
829
830 mAllAppsGrid.clearTextFilter();
831 mAllAppsGrid.setAdapter(null);
832 sModel.unbind();
833 sModel.abortLoaders();
834
835 getContentResolver().unregisterContentObserver(mObserver);
836 unregisterReceiver(mApplicationsReceiver);
837 }
838
839 @Override
840 public void startActivityForResult(Intent intent, int requestCode) {
841 mWaitingForResult = true;
842 super.startActivityForResult(intent, requestCode);
843 }
844
845 @Override
846 public void startSearch(String initialQuery, boolean selectInitialQuery,
847 Bundle appSearchData, boolean globalSearch) {
848 if (appSearchData == null) {
849 appSearchData = new Bundle();
850 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
851 }
852 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
853 }
854
855 @Override
856 public boolean onCreateOptionsMenu(Menu menu) {
857 if (mDesktopLocked) return false;
858
859 super.onCreateOptionsMenu(menu);
860 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
861 .setIcon(android.R.drawable.ic_menu_add)
862 .setAlphabeticShortcut('A');
863 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
864 .setIcon(android.R.drawable.ic_menu_gallery)
865 .setAlphabeticShortcut('W');
866 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
867 .setIcon(android.R.drawable.ic_search_category_default)
868 .setAlphabeticShortcut(SearchManager.MENU_KEY);
869 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
870 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
871 .setAlphabeticShortcut('N');
872
873 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
874 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
875 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
876
877 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
878 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
879 .setIntent(settings);
880
881 return true;
882 }
883
884 @Override
885 public boolean onPrepareOptionsMenu(Menu menu) {
886 super.onPrepareOptionsMenu(menu);
887
888 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
889 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
890
891 return true;
892 }
893
894 @Override
895 public boolean onOptionsItemSelected(MenuItem item) {
896 switch (item.getItemId()) {
897 case MENU_ADD:
898 addItems();
899 return true;
900 case MENU_WALLPAPER_SETTINGS:
901 startWallpaper();
902 return true;
903 case MENU_SEARCH:
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700904 onSearchRequested();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800905 return true;
906 case MENU_NOTIFICATIONS:
907 showNotifications();
908 return true;
909 }
910
911 return super.onOptionsItemSelected(item);
912 }
913
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700914 @Override
915 public boolean onSearchRequested() {
916 if (mWorkspace.snapToSearch()) {
917 closeDrawer(true); // search widget: get drawer out of the way
918 return true;
919 } else {
920 return super.onSearchRequested(); // no search widget: use system search UI
921 }
922 }
923
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800924 private void addItems() {
925 showAddDialog(mMenuAddInfo);
926 }
927
928 private void removeShortcutsForPackage(String packageName) {
929 if (packageName != null && packageName.length() > 0) {
930 mWorkspace.removeShortcutsForPackage(packageName);
931 }
932 }
933
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700934 private void updateShortcutsForPackage(String packageName) {
935 if (packageName != null && packageName.length() > 0) {
936 mWorkspace.updateShortcutsForPackage(packageName);
937 }
938 }
939
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700940 void addAppWidget(Intent data) {
941 // TODO: catch bad widget exception when sent
942 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800943
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700944 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
945 if (SEARCH_WIDGET.equals(customWidget)) {
946 // We don't need this any more, since this isn't a real app widget.
947 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
948 // add the search widget
949 addSearch();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800950 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700951 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
952
953 if (appWidget.configure != null) {
954 // Launch over to configure widget, if needed
955 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
956 intent.setComponent(appWidget.configure);
957 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
958
959 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
960 } else {
961 // Otherwise just add it
962 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
963 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800964 }
965 }
966
967 void addSearch() {
968 final Widget info = Widget.makeSearch();
969 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
970
971 final int[] xy = mCellCoordinates;
972 final int spanX = info.spanX;
973 final int spanY = info.spanY;
974
975 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
976
977 sModel.addDesktopItem(info);
978 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
979 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
980
981 final View view = mInflater.inflate(info.layoutResource, null);
982 view.setTag(info);
983
984 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
985 }
986
987 void addShortcut(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -0700988 // Handle case where user selected "Applications"
989 String applicationName = getResources().getString(R.string.group_applications);
990 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
991
992 if (applicationName != null && applicationName.equals(shortcutName)) {
993 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
994 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
995
996 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
997 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
998 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
999 } else {
1000 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
1001 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001002 }
1003
1004 void addLiveFolder(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001005 // Handle case where user selected "Folder"
1006 String folderName = getResources().getString(R.string.folder_name);
1007 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1008
1009 if (folderName != null && folderName.equals(shortcutName)) {
1010 addFolder(!mDesktopLocked);
1011 } else {
1012 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1013 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001014 }
1015
1016 void addFolder(boolean insertAtFirst) {
1017 UserFolderInfo folderInfo = new UserFolderInfo();
1018 folderInfo.title = getText(R.string.folder_name);
1019
1020 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1021 cellInfo.screen = mWorkspace.getCurrentScreen();
1022 if (!findSingleSlot(cellInfo)) return;
1023
1024 // Update the model
1025 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1026 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1027 sModel.addDesktopItem(folderInfo);
1028 sModel.addFolder(folderInfo);
1029
1030 // Create the view
1031 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1032 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1033 mWorkspace.addInCurrentScreen(newFolder,
1034 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1035 }
1036
1037 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
1038 boolean insertAtFirst) {
1039 cellInfo.screen = mWorkspace.getCurrentScreen();
1040 if (!findSingleSlot(cellInfo)) return;
1041
1042 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1043
1044 if (!mRestoring) {
1045 sModel.addDesktopItem(info);
1046
1047 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1048 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1049 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1050 } else if (sModel.isDesktopLoaded()) {
1051 sModel.addDesktopItem(info);
1052 }
1053 }
1054
1055 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1056 CellLayout.CellInfo cellInfo, boolean notify) {
1057
1058 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1059 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1060
1061 Drawable icon = null;
1062 boolean filtered = false;
1063 Intent.ShortcutIconResource iconResource = null;
1064
1065 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1066 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1067 try {
1068 iconResource = (Intent.ShortcutIconResource) extra;
1069 final PackageManager packageManager = context.getPackageManager();
1070 Resources resources = packageManager.getResourcesForApplication(
1071 iconResource.packageName);
1072 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1073 icon = resources.getDrawable(id);
1074 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001075 w(LOG_TAG, "Could not load live folder icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001076 }
1077 }
1078
1079 if (icon == null) {
1080 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1081 }
1082
1083 final LiveFolderInfo info = new LiveFolderInfo();
1084 info.icon = icon;
1085 info.filtered = filtered;
1086 info.title = name;
1087 info.iconResource = iconResource;
1088 info.uri = data.getData();
1089 info.baseIntent = baseIntent;
1090 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1091 LiveFolders.DISPLAY_MODE_GRID);
1092
1093 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1094 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1095 sModel.addFolder(info);
1096
1097 return info;
1098 }
1099
1100 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1101 final int[] xy = new int[2];
1102 if (findSlot(cellInfo, xy, 1, 1)) {
1103 cellInfo.cellX = xy[0];
1104 cellInfo.cellY = xy[1];
1105 return true;
1106 }
1107 return false;
1108 }
1109
1110 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1111 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1112 boolean[] occupied = mSavedState != null ?
1113 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1114 cellInfo = mWorkspace.findAllVacantCells(occupied);
1115 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1116 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1117 return false;
1118 }
1119 }
1120 return true;
1121 }
1122
1123 private void showNotifications() {
1124 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1125 if (statusBar != null) {
1126 statusBar.expand();
1127 }
1128 }
1129
1130 private void startWallpaper() {
1131 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1132 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1133 }
1134
1135 /**
1136 * Registers various intent receivers. The current implementation registers
1137 * only a wallpaper intent receiver to let other applications change the
1138 * wallpaper.
1139 */
1140 private void registerIntentReceivers() {
1141 if (sWallpaperReceiver == null) {
1142 final Application application = getApplication();
1143
1144 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1145
1146 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1147 application.registerReceiver(sWallpaperReceiver, filter);
1148 } else {
1149 sWallpaperReceiver.setLauncher(this);
1150 }
1151
1152 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1153 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1154 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1155 filter.addDataScheme("package");
1156 registerReceiver(mApplicationsReceiver, filter);
1157 }
1158
1159 /**
1160 * Registers various content observers. The current implementation registers
1161 * only a favorites observer to keep track of the favorites applications.
1162 */
1163 private void registerContentObservers() {
1164 ContentResolver resolver = getContentResolver();
1165 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
1166 }
1167
1168 @Override
1169 public boolean dispatchKeyEvent(KeyEvent event) {
1170 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1171 switch (event.getKeyCode()) {
1172 case KeyEvent.KEYCODE_BACK:
1173 mWorkspace.dispatchKeyEvent(event);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001174 if (mDrawer.isOpened()) {
1175 closeDrawer();
1176 } else {
1177 closeFolder();
1178 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001179 return true;
1180 case KeyEvent.KEYCODE_HOME:
1181 return true;
1182 }
1183 }
1184
1185 return super.dispatchKeyEvent(event);
1186 }
1187
1188 private void closeDrawer() {
1189 closeDrawer(true);
1190 }
1191
1192 private void closeDrawer(boolean animated) {
1193 if (mDrawer.isOpened()) {
1194 if (animated) {
1195 mDrawer.animateClose();
1196 } else {
1197 mDrawer.close();
1198 }
1199 if (mDrawer.hasFocus()) {
1200 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1201 }
1202 }
1203 }
1204
1205 private void closeFolder() {
1206 Folder folder = mWorkspace.getOpenFolder();
1207 if (folder != null) {
1208 closeFolder(folder);
1209 }
1210 }
1211
1212 void closeFolder(Folder folder) {
1213 folder.getInfo().opened = false;
1214 ViewGroup parent = (ViewGroup) folder.getParent();
1215 if (parent != null) {
1216 parent.removeView(folder);
1217 }
1218 folder.onClose();
1219 }
1220
1221 /**
1222 * When the notification that favorites have changed is received, requests
1223 * a favorites list refresh.
1224 */
1225 private void onFavoritesChanged() {
1226 mDesktopLocked = true;
1227 mDrawer.lock();
1228 sModel.loadUserItems(false, this, false, false);
1229 }
1230
1231 void onDesktopItemsLoaded() {
1232 if (mDestroyed) return;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001233 bindDesktopItems();
1234 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001235
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001236 /**
1237 * Refreshes the shortcuts shown on the workspace.
1238 */
1239 private void bindDesktopItems() {
1240 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001241 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001242 final ApplicationsAdapter drawerAdapter = sModel.getApplicationsAdapter();
1243 if (shortcuts == null || appWidgets == null || drawerAdapter == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001244 return;
1245 }
1246
1247 final Workspace workspace = mWorkspace;
1248 int count = workspace.getChildCount();
1249 for (int i = 0; i < count; i++) {
1250 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1251 }
1252
1253 if (DEBUG_USER_INTERFACE) {
1254 android.widget.Button finishButton = new android.widget.Button(this);
1255 finishButton.setText("Finish");
1256 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1257
1258 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1259 public void onClick(View v) {
1260 finish();
1261 }
1262 });
1263 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001264
1265 // Flag any old binder to terminate early
1266 if (mBinder != null) {
1267 mBinder.mTerminate = true;
1268 }
1269
1270 mBinder = new DesktopBinder(this, shortcuts, appWidgets, drawerAdapter);
1271 mBinder.startWhenIdle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001272 }
1273
1274 private void bindItems(Launcher.DesktopBinder binder,
1275 ArrayList<ItemInfo> shortcuts, int start, int count) {
1276
1277 final Workspace workspace = mWorkspace;
1278 final boolean desktopLocked = mDesktopLocked;
1279
1280 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1281 int i = start;
1282
1283 for ( ; i < end; i++) {
1284 final ItemInfo item = shortcuts.get(i);
1285 switch (item.itemType) {
1286 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1287 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1288 final View shortcut = createShortcut((ApplicationInfo) item);
1289 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1290 !desktopLocked);
1291 break;
1292 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1293 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1294 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1295 (UserFolderInfo) item);
1296 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1297 !desktopLocked);
1298 break;
1299 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1300 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1301 R.layout.live_folder_icon, this,
1302 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1303 (LiveFolderInfo) item);
1304 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1305 !desktopLocked);
1306 break;
1307 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1308 final int screen = workspace.getCurrentScreen();
1309 final View view = mInflater.inflate(R.layout.widget_search,
1310 (ViewGroup) workspace.getChildAt(screen), false);
1311
1312 final Widget widget = (Widget) item;
1313 view.setTag(widget);
1314
1315 workspace.addWidget(view, widget, !desktopLocked);
1316 break;
1317 }
1318 }
1319
1320 workspace.requestLayout();
1321
1322 if (end >= count) {
1323 finishBindDesktopItems();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001324 binder.startBindingDrawer();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001325 } else {
1326 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1327 }
1328 }
1329
1330 private void finishBindDesktopItems() {
1331 if (mSavedState != null) {
1332 if (!mWorkspace.hasFocus()) {
1333 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1334 }
1335
1336 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1337 if (userFolders != null) {
1338 for (long folderId : userFolders) {
1339 final FolderInfo info = sModel.findFolderById(folderId);
1340 if (info != null) {
1341 openFolder(info);
1342 }
1343 }
1344 final Folder openFolder = mWorkspace.getOpenFolder();
1345 if (openFolder != null) {
1346 openFolder.requestFocus();
1347 }
1348 }
1349
1350 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1351 if (allApps) {
1352 mDrawer.open();
1353 }
1354
1355 mSavedState = null;
1356 }
1357
1358 if (mSavedInstanceState != null) {
1359 super.onRestoreInstanceState(mSavedInstanceState);
1360 mSavedInstanceState = null;
1361 }
1362
1363 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1364 mDrawer.requestFocus();
1365 }
1366
1367 mDesktopLocked = false;
1368 mDrawer.unlock();
1369 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001370
1371 private void bindDrawer(Launcher.DesktopBinder binder,
1372 ApplicationsAdapter drawerAdapter) {
1373 mAllAppsGrid.setAdapter(drawerAdapter);
1374 binder.startBindingAppWidgets();
1375 }
1376
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001377 private void bindAppWidgets(Launcher.DesktopBinder binder,
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001378 LinkedList<LauncherAppWidgetInfo> appWidgets) {
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001379
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001380 final Workspace workspace = mWorkspace;
1381 final boolean desktopLocked = mDesktopLocked;
1382
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001383 if (!appWidgets.isEmpty()) {
1384 final LauncherAppWidgetInfo item = appWidgets.removeFirst();
1385
1386 final int appWidgetId = item.appWidgetId;
1387 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
1388 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1389
1390 if (LOGD) d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s", appWidgetId, appWidgetInfo));
1391
1392 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1393 item.hostView.setTag(item);
1394
1395 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1396 item.cellY, item.spanX, item.spanY, !desktopLocked);
1397
1398 workspace.requestLayout();
1399 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001400
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001401 if (appWidgets.isEmpty()) {
1402 if (PROFILE_ROTATE) {
1403 android.os.Debug.stopMethodTracing();
1404 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001405 } else {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001406 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001407 }
1408 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001409
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001410 DragController getDragController() {
1411 return mDragLayer;
1412 }
1413
1414 /**
1415 * Launches the intent referred by the clicked shortcut.
1416 *
1417 * @param v The view representing the clicked shortcut.
1418 */
1419 public void onClick(View v) {
1420 Object tag = v.getTag();
1421 if (tag instanceof ApplicationInfo) {
1422 // Open shortcut
1423 final Intent intent = ((ApplicationInfo) tag).intent;
1424 startActivitySafely(intent);
1425 } else if (tag instanceof FolderInfo) {
1426 handleFolderClick((FolderInfo) tag);
1427 }
1428 }
1429
1430 void startActivitySafely(Intent intent) {
1431 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1432 try {
1433 startActivity(intent);
1434 } catch (ActivityNotFoundException e) {
1435 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1436 } catch (SecurityException e) {
1437 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1438 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1439 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1440 "or use the exported attribute for this activity.", e);
1441 }
1442 }
1443
1444 private void handleFolderClick(FolderInfo folderInfo) {
1445 if (!folderInfo.opened) {
1446 // Close any open folder
1447 closeFolder();
1448 // Open the requested folder
1449 openFolder(folderInfo);
1450 } else {
1451 // Find the open folder...
1452 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1453 int folderScreen;
1454 if (openFolder != null) {
1455 folderScreen = mWorkspace.getScreenForView(openFolder);
1456 // .. and close it
1457 closeFolder(openFolder);
1458 if (folderScreen != mWorkspace.getCurrentScreen()) {
1459 // Close any folder open on the current screen
1460 closeFolder();
1461 // Pull the folder onto this screen
1462 openFolder(folderInfo);
1463 }
1464 }
1465 }
1466 }
1467
1468 private void loadWallpaper() {
1469 // The first time the application is started, we load the wallpaper from
1470 // the ApplicationContext
1471 if (sWallpaper == null) {
1472 final Drawable drawable = getWallpaper();
1473 if (drawable instanceof BitmapDrawable) {
1474 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1475 } else {
1476 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1477 }
1478 }
1479 mWorkspace.loadWallpaper(sWallpaper);
1480 }
1481
1482 /**
1483 * Opens the user fodler described by the specified tag. The opening of the folder
1484 * is animated relative to the specified View. If the View is null, no animation
1485 * is played.
1486 *
1487 * @param folderInfo The FolderInfo describing the folder to open.
1488 */
1489 private void openFolder(FolderInfo folderInfo) {
1490 Folder openFolder;
1491
1492 if (folderInfo instanceof UserFolderInfo) {
1493 openFolder = UserFolder.fromXml(this);
1494 } else if (folderInfo instanceof LiveFolderInfo) {
1495 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1496 } else {
1497 return;
1498 }
1499
1500 openFolder.setDragger(mDragLayer);
1501 openFolder.setLauncher(this);
1502
1503 openFolder.bind(folderInfo);
1504 folderInfo.opened = true;
1505
1506 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1507 openFolder.onOpen();
1508 }
1509
1510 /**
1511 * Returns true if the workspace is being loaded. When the workspace is loading,
1512 * no user interaction should be allowed to avoid any conflict.
1513 *
1514 * @return True if the workspace is locked, false otherwise.
1515 */
1516 boolean isWorkspaceLocked() {
1517 return mDesktopLocked;
1518 }
1519
1520 public boolean onLongClick(View v) {
1521 if (mDesktopLocked) {
1522 return false;
1523 }
1524
1525 if (!(v instanceof CellLayout)) {
1526 v = (View) v.getParent();
1527 }
1528
1529 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1530
1531 // This happens when long clicking an item with the dpad/trackball
1532 if (cellInfo == null) {
1533 return true;
1534 }
1535
1536 if (mWorkspace.allowLongPress()) {
1537 if (cellInfo.cell == null) {
1538 if (cellInfo.valid) {
1539 // User long pressed on empty space
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001540 mWorkspace.setAllowLongPress(false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001541 showAddDialog(cellInfo);
1542 }
1543 } else {
1544 if (!(cellInfo.cell instanceof Folder)) {
1545 // User long pressed on an item
1546 mWorkspace.startDrag(cellInfo);
1547 }
1548 }
1549 }
1550 return true;
1551 }
1552
1553 static LauncherModel getModel() {
1554 return sModel;
1555 }
1556
1557 void closeAllApplications() {
1558 mDrawer.close();
1559 }
1560
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001561 View getDrawerHandle() {
1562 return mHandleView;
1563 }
1564
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001565 boolean isDrawerDown() {
1566 return !mDrawer.isMoving() && !mDrawer.isOpened();
1567 }
1568
1569 boolean isDrawerUp() {
1570 return mDrawer.isOpened() && !mDrawer.isMoving();
1571 }
1572
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001573 boolean isDrawerMoving() {
1574 return mDrawer.isMoving();
1575 }
1576
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001577 Workspace getWorkspace() {
1578 return mWorkspace;
1579 }
1580
1581 GridView getApplicationsGrid() {
1582 return mAllAppsGrid;
1583 }
1584
1585 @Override
1586 protected Dialog onCreateDialog(int id) {
1587 switch (id) {
1588 case DIALOG_CREATE_SHORTCUT:
1589 return new CreateShortcut().createDialog();
1590 case DIALOG_RENAME_FOLDER:
1591 return new RenameFolder().createDialog();
1592 }
1593
1594 return super.onCreateDialog(id);
1595 }
1596
1597 @Override
1598 protected void onPrepareDialog(int id, Dialog dialog) {
1599 switch (id) {
1600 case DIALOG_CREATE_SHORTCUT:
1601 mWorkspace.lock();
1602 break;
1603 case DIALOG_RENAME_FOLDER:
1604 mWorkspace.lock();
1605 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1606 final CharSequence text = mFolderInfo.title;
1607 input.setText(text);
1608 input.setSelection(0, text.length());
1609 break;
1610 }
1611 }
1612
1613 void showRenameDialog(FolderInfo info) {
1614 mFolderInfo = info;
1615 mWaitingForResult = true;
1616 showDialog(DIALOG_RENAME_FOLDER);
1617 }
1618
1619 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1620 mAddItemCellInfo = cellInfo;
1621 mWaitingForResult = true;
1622 showDialog(DIALOG_CREATE_SHORTCUT);
1623 }
1624
1625 private class RenameFolder {
1626 private EditText mInput;
1627
1628 Dialog createDialog() {
1629 mWaitingForResult = true;
1630 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1631 mInput = (EditText) layout.findViewById(R.id.folder_name);
1632
1633 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1634 builder.setIcon(0);
1635 builder.setTitle(getString(R.string.rename_folder_title));
1636 builder.setCancelable(true);
1637 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1638 public void onCancel(DialogInterface dialog) {
1639 cleanup();
1640 }
1641 });
1642 builder.setNegativeButton(getString(R.string.cancel_action),
1643 new Dialog.OnClickListener() {
1644 public void onClick(DialogInterface dialog, int which) {
1645 cleanup();
1646 }
1647 }
1648 );
1649 builder.setPositiveButton(getString(R.string.rename_action),
1650 new Dialog.OnClickListener() {
1651 public void onClick(DialogInterface dialog, int which) {
1652 changeFolderName();
1653 }
1654 }
1655 );
1656 builder.setView(layout);
1657 return builder.create();
1658 }
1659
1660 private void changeFolderName() {
1661 final String name = mInput.getText().toString();
1662 if (!TextUtils.isEmpty(name)) {
1663 // Make sure we have the right folder info
1664 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1665 mFolderInfo.title = name;
1666 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1667
1668 if (mDesktopLocked) {
1669 mDrawer.lock();
1670 sModel.loadUserItems(false, Launcher.this, false, false);
1671 } else {
1672 final FolderIcon folderIcon = (FolderIcon)
1673 mWorkspace.getViewForTag(mFolderInfo);
1674 if (folderIcon != null) {
1675 folderIcon.setText(name);
1676 getWorkspace().requestLayout();
1677 } else {
1678 mDesktopLocked = true;
1679 mDrawer.lock();
1680 sModel.loadUserItems(false, Launcher.this, false, false);
1681 }
1682 }
1683 }
1684 cleanup();
1685 }
1686
1687 private void cleanup() {
1688 mWorkspace.unlock();
1689 dismissDialog(DIALOG_RENAME_FOLDER);
1690 mWaitingForResult = false;
1691 mFolderInfo = null;
1692 }
1693 }
1694
1695 /**
1696 * Displays the shortcut creation dialog and launches, if necessary, the
1697 * appropriate activity.
1698 */
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001699 private class CreateShortcut implements DialogInterface.OnClickListener,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001700 DialogInterface.OnCancelListener {
1701 private AddAdapter mAdapter;
1702 private ListView mList;
1703
1704 Dialog createDialog() {
1705 mWaitingForResult = true;
1706
1707 mAdapter = new AddAdapter(Launcher.this);
1708
1709 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1710 builder.setTitle(getString(R.string.menu_item_add_item));
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001711 builder.setAdapter(mAdapter, this);
1712
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001713 builder.setView(mList);
1714 builder.setInverseBackgroundForced(true);
1715
1716 AlertDialog dialog = builder.create();
1717 dialog.setOnCancelListener(this);
1718
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001719 return dialog;
1720 }
1721
1722 public void onCancel(DialogInterface dialog) {
1723 mWaitingForResult = false;
1724 cleanup();
1725 }
1726
1727 private void cleanup() {
1728 mWorkspace.unlock();
1729 dismissDialog(DIALOG_CREATE_SHORTCUT);
1730 }
1731
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001732 /**
1733 * Handle the action clicked in the "Add to home" dialog.
1734 */
1735 public void onClick(DialogInterface dialog, int which) {
1736 Resources res = getResources();
1737 cleanup();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001738
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001739 switch (which) {
1740 case AddAdapter.ITEM_SHORTCUT: {
1741 // Insert extra item to handle picking application
1742 Bundle bundle = new Bundle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001743
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001744 ArrayList<String> shortcutNames = new ArrayList<String>();
1745 shortcutNames.add(res.getString(R.string.group_applications));
1746 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001747
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001748 ArrayList<ShortcutIconResource> shortcutIcons =
1749 new ArrayList<ShortcutIconResource>();
1750 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1751 R.drawable.ic_launcher_application));
1752 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001753
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001754 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1755 pickIntent.putExtra(Intent.EXTRA_INTENT,
1756 new Intent(Intent.ACTION_CREATE_SHORTCUT));
1757 pickIntent.putExtra(Intent.EXTRA_TITLE,
1758 getText(R.string.title_select_shortcut));
1759 pickIntent.putExtras(bundle);
1760
1761 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1762 break;
1763 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001764
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001765 case AddAdapter.ITEM_APPWIDGET: {
1766 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
1767
1768 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1769 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1770 // add the search widget
1771 ArrayList<AppWidgetProviderInfo> customInfo =
1772 new ArrayList<AppWidgetProviderInfo>();
1773 AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1774 info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1775 info.label = getString(R.string.group_search);
1776 info.icon = R.drawable.ic_search_widget;
1777 customInfo.add(info);
1778 pickIntent.putParcelableArrayListExtra(
1779 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1780 ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1781 Bundle b = new Bundle();
1782 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1783 customExtras.add(b);
1784 pickIntent.putParcelableArrayListExtra(
1785 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1786 // start the pick activity
1787 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
1788 break;
1789 }
1790
1791 case AddAdapter.ITEM_LIVE_FOLDER: {
1792 // Insert extra item to handle inserting folder
1793 Bundle bundle = new Bundle();
1794
1795 ArrayList<String> shortcutNames = new ArrayList<String>();
1796 shortcutNames.add(res.getString(R.string.group_folder));
1797 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1798
1799 ArrayList<ShortcutIconResource> shortcutIcons =
1800 new ArrayList<ShortcutIconResource>();
1801 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1802 R.drawable.ic_launcher_folder));
1803 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1804
1805 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1806 pickIntent.putExtra(Intent.EXTRA_INTENT,
1807 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
1808 pickIntent.putExtra(Intent.EXTRA_TITLE,
1809 getText(R.string.title_select_live_folder));
1810 pickIntent.putExtras(bundle);
1811
1812 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1813 break;
1814 }
1815
1816 case AddAdapter.ITEM_WALLPAPER: {
1817 startWallpaper();
1818 break;
1819 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001820 }
1821 }
1822 }
1823
1824 /**
1825 * Receives notifications when applications are added/removed.
1826 */
1827 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1828 @Override
1829 public void onReceive(Context context, Intent intent) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001830 final String action = intent.getAction();
1831 final String packageName = intent.getData().getSchemeSpecificPart();
1832 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1833
1834 if (LauncherModel.DEBUG_LOADERS) {
1835 d(LauncherModel.LOG_TAG, "application intent received: " + action +
1836 ", replacing=" + replacing);
1837 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001838 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001839
1840 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1841 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1842 if (!replacing) {
1843 removeShortcutsForPackage(packageName);
1844 if (LauncherModel.DEBUG_LOADERS) {
1845 d(LauncherModel.LOG_TAG, " --> remove package");
1846 }
1847 sModel.removePackage(Launcher.this, packageName);
1848 }
1849 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1850 // later, we will update the package at this time
1851 } else {
1852 if (!replacing) {
1853 if (LauncherModel.DEBUG_LOADERS) {
1854 d(LauncherModel.LOG_TAG, " --> add package");
1855 }
1856 sModel.addPackage(Launcher.this, packageName);
1857 } else {
1858 if (LauncherModel.DEBUG_LOADERS) {
1859 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
1860 }
1861 sModel.updatePackage(Launcher.this, packageName);
1862 updateShortcutsForPackage(packageName);
1863 }
1864 }
1865 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001866 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001867 if (LauncherModel.DEBUG_LOADERS) {
1868 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
1869 }
1870 sModel.syncPackage(Launcher.this, packageName);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001871 }
1872 }
1873 }
1874
1875 /**
1876 * Receives notifications whenever the user favorites have changed.
1877 */
1878 private class FavoritesChangeObserver extends ContentObserver {
1879 public FavoritesChangeObserver() {
1880 super(new Handler());
1881 }
1882
1883 @Override
1884 public void onChange(boolean selfChange) {
1885 onFavoritesChanged();
1886 }
1887 }
1888
1889 /**
1890 * Receives intents from other applications to change the wallpaper.
1891 */
1892 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1893 private final Application mApplication;
1894 private WeakReference<Launcher> mLauncher;
1895
1896 WallpaperIntentReceiver(Application application, Launcher launcher) {
1897 mApplication = application;
1898 setLauncher(launcher);
1899 }
1900
1901 void setLauncher(Launcher launcher) {
1902 mLauncher = new WeakReference<Launcher>(launcher);
1903 }
1904
1905 @Override
1906 public void onReceive(Context context, Intent intent) {
1907 // Load the wallpaper from the ApplicationContext and store it locally
1908 // until the Launcher Activity is ready to use it
1909 final Drawable drawable = mApplication.getWallpaper();
1910 if (drawable instanceof BitmapDrawable) {
1911 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1912 } else {
1913 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1914 }
1915
1916 // If Launcher is alive, notify we have a new wallpaper
1917 if (mLauncher != null) {
1918 final Launcher launcher = mLauncher.get();
1919 if (launcher != null) {
1920 launcher.loadWallpaper();
1921 }
1922 }
1923 }
1924 }
1925
1926 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1927 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1928 private boolean mOpen;
1929
1930 public void onDrawerOpened() {
1931 if (!mOpen) {
1932 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001933
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001934 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001935 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001936
1937 mOpen = true;
1938 }
1939 }
1940
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001941 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1942 view.getDrawingRect(bounds);
1943
1944 while (view != mDragLayer) {
1945 bounds.offset(view.getLeft(), view.getTop());
1946 view = (View) view.getParent();
1947 }
1948 }
1949
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001950 public void onDrawerClosed() {
1951 if (mOpen) {
1952 mHandleIcon.reverseTransition(150);
1953 mWorkspace.mDrawerBounds.setEmpty();
1954 mOpen = false;
1955 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001956
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001957 mAllAppsGrid.setSelection(0);
1958 mAllAppsGrid.clearTextFilter();
1959 }
1960
1961 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001962 if (PROFILE_DRAWER) {
1963 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1964 }
1965
1966 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1967 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001968 }
1969
1970 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001971 if (PROFILE_DRAWER) {
1972 android.os.Debug.stopMethodTracing();
1973 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001974 }
1975 }
1976
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001977 private static class DesktopBinder extends Handler implements MessageQueue.IdleHandler {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001978 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001979 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001980 static final int MESSAGE_BIND_DRAWER = 0x3;
1981
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001982 // Number of items to bind in every pass
1983 static final int ITEMS_COUNT = 6;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001984
1985 private final ArrayList<ItemInfo> mShortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001986 private final LinkedList<LauncherAppWidgetInfo> mAppWidgets;
1987 private final ApplicationsAdapter mDrawerAdapter;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001988 private final WeakReference<Launcher> mLauncher;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001989
1990 public boolean mTerminate = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001991
1992 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001993 ArrayList<LauncherAppWidgetInfo> appWidgets,
1994 ApplicationsAdapter drawerAdapter) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001995
1996 mLauncher = new WeakReference<Launcher>(launcher);
1997 mShortcuts = shortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001998 mDrawerAdapter = drawerAdapter;
1999
2000 // Sort widgets so active workspace is bound first
2001 final int currentScreen = launcher.mWorkspace.getCurrentScreen();
2002 final int size = appWidgets.size();
2003 mAppWidgets = new LinkedList<LauncherAppWidgetInfo>();
2004
2005 for (int i = 0; i < size; i++) {
2006 LauncherAppWidgetInfo appWidgetInfo = appWidgets.get(i);
2007 if (appWidgetInfo.screen == currentScreen) {
2008 mAppWidgets.addFirst(appWidgetInfo);
2009 } else {
2010 mAppWidgets.addLast(appWidgetInfo);
2011 }
2012 }
2013 }
2014
2015 public void startWhenIdle() {
2016 // Ask for notification when message queue becomes idle
2017 final MessageQueue messageQueue = Looper.myQueue();
2018 messageQueue.addIdleHandler(this);
2019 }
2020
2021 public boolean queueIdle() {
2022 // Queue is idle, so start binding items
2023 startBindingItems();
2024 return false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002025 }
2026
2027 public void startBindingItems() {
2028 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
2029 }
2030
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002031 public void startBindingDrawer() {
2032 obtainMessage(MESSAGE_BIND_DRAWER).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002033 }
2034
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002035 public void startBindingAppWidgets() {
2036 obtainMessage(MESSAGE_BIND_APPWIDGETS).sendToTarget();
2037 }
2038
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002039 @Override
2040 public void handleMessage(Message msg) {
2041 Launcher launcher = mLauncher.get();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002042 if (launcher == null || mTerminate) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002043 return;
2044 }
2045
2046 switch (msg.what) {
2047 case MESSAGE_BIND_ITEMS: {
2048 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
2049 break;
2050 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002051 case MESSAGE_BIND_DRAWER: {
2052 launcher.bindDrawer(this, mDrawerAdapter);
2053 break;
2054 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07002055 case MESSAGE_BIND_APPWIDGETS: {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002056 launcher.bindAppWidgets(this, mAppWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002057 break;
2058 }
2059 }
2060 }
2061 }
2062}