blob: 7dd341819a09504aa240081a3fceffdd4db1c0e9 [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;
42import android.graphics.Rect;
43import android.graphics.drawable.BitmapDrawable;
44import android.graphics.drawable.Drawable;
45import android.graphics.drawable.TransitionDrawable;
46import android.net.Uri;
47import android.os.Bundle;
48import android.os.Handler;
49import android.os.IBinder;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -070050import android.os.Looper;
51import android.os.MessageQueue;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080052import android.os.Parcelable;
53import android.os.RemoteException;
54import android.os.ServiceManager;
55import android.os.Message;
56import android.provider.*;
57import android.telephony.PhoneNumberUtils;
58import android.text.Selection;
59import android.text.SpannableStringBuilder;
60import android.text.TextUtils;
61import android.text.method.TextKeyListener;
62import android.util.Log;
The Android Open Source Projectf96811c2009-03-18 17:39:48 -070063import static android.util.Log.*;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080064import android.view.Display;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080065import android.view.KeyEvent;
66import android.view.LayoutInflater;
67import android.view.Menu;
68import android.view.MenuItem;
69import android.view.View;
70import android.view.ViewGroup;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080071import android.view.View.OnLongClickListener;
72import android.view.inputmethod.InputMethodManager;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080073import android.widget.EditText;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080074import android.widget.TextView;
75import android.widget.Toast;
76import android.widget.GridView;
77import android.widget.SlidingDrawer;
78import android.app.IWallpaperService;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070079import android.appwidget.AppWidgetManager;
80import android.appwidget.AppWidgetProviderInfo;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080081
82import java.lang.ref.WeakReference;
83import java.util.ArrayList;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -070084import java.util.LinkedList;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080085
86/**
87 * Default launcher application.
88 */
89public final class Launcher extends Activity implements View.OnClickListener, OnLongClickListener {
90 static final String LOG_TAG = "Launcher";
91 static final boolean LOGD = false;
92
93 private static final boolean PROFILE_STARTUP = false;
The Android Open Source Project7376fae2009-03-11 12:11:58 -070094 private static final boolean PROFILE_DRAWER = false;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -070095 private static final boolean PROFILE_ROTATE = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -080096 private static final boolean DEBUG_USER_INTERFACE = false;
97
98 private static final int WALLPAPER_SCREENS_SPAN = 2;
99
100 private static final int MENU_GROUP_ADD = 1;
101 private static final int MENU_ADD = Menu.FIRST + 1;
102 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1;
103 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1;
104 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1;
105 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1;
106
107 private static final int REQUEST_CREATE_SHORTCUT = 1;
108 private static final int REQUEST_CREATE_LIVE_FOLDER = 4;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700109 private static final int REQUEST_CREATE_APPWIDGET = 5;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800110 private static final int REQUEST_PICK_APPLICATION = 6;
111 private static final int REQUEST_PICK_SHORTCUT = 7;
112 private static final int REQUEST_PICK_LIVE_FOLDER = 8;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700113 private static final int REQUEST_PICK_APPWIDGET = 9;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800114
115 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate";
116
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700117 static final String EXTRA_CUSTOM_WIDGET = "custom_widget";
118 static final String SEARCH_WIDGET = "search_widget";
119
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800120 static final int SCREEN_COUNT = 3;
121 static final int DEFAULT_SCREN = 1;
122 static final int NUMBER_CELLS_X = 4;
123 static final int NUMBER_CELLS_Y = 4;
124
125 private static final int DIALOG_CREATE_SHORTCUT = 1;
126 static final int DIALOG_RENAME_FOLDER = 2;
127
128 private static final String PREFERENCES = "launcher";
129 private static final String KEY_LOCALE = "locale";
130 private static final String KEY_MCC = "mcc";
131 private static final String KEY_MNC = "mnc";
132
133 // Type: int
134 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen";
135 // Type: boolean
136 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder";
137 // Type: long
138 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder";
139 // Type: int
140 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen";
141 // Type: int
142 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX";
143 // Type: int
144 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY";
145 // Type: int
146 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX";
147 // Type: int
148 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY";
149 // Type: int
150 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX";
151 // Type: int
152 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY";
153 // Type: int[]
154 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells";
155 // Type: boolean
156 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder";
157 // Type: long
158 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id";
159
The Android Open Source Projectbc219c32009-03-09 11:52:14 -0700160 private static final LauncherModel sModel = new LauncherModel();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800161
162 private static Bitmap sWallpaper;
163
164 private static final Object sLock = new Object();
165 private static int sScreen = DEFAULT_SCREN;
166
167 private static WallpaperIntentReceiver sWallpaperReceiver;
168
169 private final BroadcastReceiver mApplicationsReceiver = new ApplicationsIntentReceiver();
170 private final ContentObserver mObserver = new FavoritesChangeObserver();
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700171 private final ContentObserver mAppWidgetResetObserver = new AppWidgetResetObserver();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800172
173 private LayoutInflater mInflater;
174
175 private DragLayer mDragLayer;
176 private Workspace mWorkspace;
177
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700178 private AppWidgetManager mAppWidgetManager;
179 private LauncherAppWidgetHost mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800180
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700181 static final int APPWIDGET_HOST_ID = 1024;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800182
183 private CellLayout.CellInfo mAddItemCellInfo;
184 private CellLayout.CellInfo mMenuAddInfo;
185 private final int[] mCellCoordinates = new int[2];
186 private FolderInfo mFolderInfo;
187
188 private SlidingDrawer mDrawer;
189 private TransitionDrawable mHandleIcon;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700190 private HandleView mHandleView;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800191 private AllAppsGridView mAllAppsGrid;
192
193 private boolean mDesktopLocked = true;
194 private Bundle mSavedState;
195
196 private SpannableStringBuilder mDefaultKeySsb = null;
197
198 private boolean mDestroyed;
199
200 private boolean mRestoring;
201 private boolean mWaitingForResult;
202 private boolean mLocaleChanged;
203
204 private Bundle mSavedInstanceState;
205
Jeffrey Sharkey99c87582009-03-24 17:59:43 -0700206 private DesktopBinder mBinder;
207
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800208 @Override
209 protected void onCreate(Bundle savedInstanceState) {
210 super.onCreate(savedInstanceState);
211 mInflater = getLayoutInflater();
212
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700213 mAppWidgetManager = AppWidgetManager.getInstance(this);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800214
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700215 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
216 mAppWidgetHost.startListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800217
218 if (PROFILE_STARTUP) {
219 android.os.Debug.startMethodTracing("/sdcard/launcher");
220 }
221
222 checkForLocaleChange();
223 setWallpaperDimension();
224
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800225 setContentView(R.layout.launcher);
226 setupViews();
227
228 registerIntentReceivers();
229 registerContentObservers();
230
231 mSavedState = savedInstanceState;
232 restoreState(mSavedState);
233
234 if (PROFILE_STARTUP) {
235 android.os.Debug.stopMethodTracing();
236 }
237
238 if (!mRestoring) {
239 startLoaders();
240 }
241
242 // For handling default keys
243 mDefaultKeySsb = new SpannableStringBuilder();
244 Selection.setSelection(mDefaultKeySsb, 0);
245 }
246
247 private void checkForLocaleChange() {
248 final SharedPreferences preferences = getSharedPreferences(PREFERENCES, MODE_PRIVATE);
249 final Configuration configuration = getResources().getConfiguration();
250
251 final String previousLocale = preferences.getString(KEY_LOCALE, null);
252 final String locale = configuration.locale.toString();
253
254 final int previousMcc = preferences.getInt(KEY_MCC, -1);
255 final int mcc = configuration.mcc;
256
257 final int previousMnc = preferences.getInt(KEY_MNC, -1);
258 final int mnc = configuration.mnc;
259
260 mLocaleChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc;
261
262 if (mLocaleChanged) {
263 final SharedPreferences.Editor editor = preferences.edit();
264 editor.putString(KEY_LOCALE, locale);
265 editor.putInt(KEY_MCC, mcc);
266 editor.putInt(KEY_MNC, mnc);
267 editor.commit();
268 }
269 }
270
271 static int getScreen() {
272 synchronized (sLock) {
273 return sScreen;
274 }
275 }
276
277 static void setScreen(int screen) {
278 synchronized (sLock) {
279 sScreen = screen;
280 }
281 }
282
283 private void startLoaders() {
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700284 boolean loadApplications = sModel.loadApplications(true, this, mLocaleChanged);
285 sModel.loadUserItems(!mLocaleChanged, this, mLocaleChanged, loadApplications);
286
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800287 mRestoring = false;
288 }
289
290 private void setWallpaperDimension() {
291 IBinder binder = ServiceManager.getService(WALLPAPER_SERVICE);
292 IWallpaperService wallpaperService = IWallpaperService.Stub.asInterface(binder);
293
294 Display display = getWindowManager().getDefaultDisplay();
295 boolean isPortrait = display.getWidth() < display.getHeight();
296
297 final int width = isPortrait ? display.getWidth() : display.getHeight();
298 final int height = isPortrait ? display.getHeight() : display.getWidth();
299 try {
300 wallpaperService.setDimensionHints(width * WALLPAPER_SCREENS_SPAN, height);
301 } catch (RemoteException e) {
302 // System is dead!
303 }
304 }
305
306 @Override
307 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
308 // The pattern used here is that a user PICKs a specific application,
309 // which, depending on the target, might need to CREATE the actual target.
310
311 // For example, the user would PICK_SHORTCUT for "Music playlist", and we
312 // launch over to the Music app to actually CREATE_SHORTCUT.
313
314 if (resultCode == RESULT_OK && mAddItemCellInfo != null) {
315 switch (requestCode) {
316 case REQUEST_PICK_APPLICATION:
317 completeAddApplication(this, data, mAddItemCellInfo, !mDesktopLocked);
318 break;
319 case REQUEST_PICK_SHORTCUT:
320 addShortcut(data);
321 break;
322 case REQUEST_CREATE_SHORTCUT:
323 completeAddShortcut(data, mAddItemCellInfo, !mDesktopLocked);
324 break;
325 case REQUEST_PICK_LIVE_FOLDER:
326 addLiveFolder(data);
327 break;
328 case REQUEST_CREATE_LIVE_FOLDER:
329 completeAddLiveFolder(data, mAddItemCellInfo, !mDesktopLocked);
330 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700331 case REQUEST_PICK_APPWIDGET:
332 addAppWidget(data);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800333 break;
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700334 case REQUEST_CREATE_APPWIDGET:
335 completeAddAppWidget(data, mAddItemCellInfo, !mDesktopLocked);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800336 break;
337 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700338 } else if (requestCode == REQUEST_PICK_APPWIDGET &&
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800339 resultCode == RESULT_CANCELED && data != null) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700340 // Clean up the appWidgetId if we canceled
341 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
342 if (appWidgetId != -1) {
343 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800344 }
345 }
346 mWaitingForResult = false;
347 }
348
349 @Override
350 protected void onResume() {
351 super.onResume();
352
353 if (mRestoring) {
354 startLoaders();
355 }
356 }
357
358 @Override
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700359 protected void onPause() {
360 super.onPause();
361 closeDrawer(false);
362 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -0700363
364 @Override
365 public Object onRetainNonConfigurationInstance() {
366 // Flag any binder to stop early before switching
367 if (mBinder != null) {
368 mBinder.mTerminate = true;
369 }
370
371 if (PROFILE_ROTATE) {
372 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate");
373 }
374 return null;
375 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700376
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800377 private boolean acceptFilter() {
378 final InputMethodManager inputManager = (InputMethodManager)
379 getSystemService(Context.INPUT_METHOD_SERVICE);
380 return !inputManager.isFullscreenMode();
381 }
382
383 @Override
384 public boolean onKeyDown(int keyCode, KeyEvent event) {
385 boolean handled = super.onKeyDown(keyCode, event);
386 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) {
387 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb,
388 keyCode, event);
389 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) {
390 // something usable has been typed - dispatch it now.
391 final String str = mDefaultKeySsb.toString();
392
393 boolean isDialable = true;
394 final int count = str.length();
395 for (int i = 0; i < count; i++) {
396 if (!PhoneNumberUtils.isReallyDialable(str.charAt(i))) {
397 isDialable = false;
398 break;
399 }
400 }
401 Intent intent;
402 if (isDialable) {
403 intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", str, null));
404 } else {
405 intent = new Intent(Contacts.Intents.UI.FILTER_CONTACTS_ACTION);
406 intent.putExtra(Contacts.Intents.UI.FILTER_TEXT_EXTRA_KEY, str);
407 }
408
Dianne Hackbornbd2e54d2009-03-24 21:00:33 -0700409 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
410 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800411
412 try {
413 startActivity(intent);
414 } catch (android.content.ActivityNotFoundException ex) {
415 // Oh well... no one knows how to filter/dial. Life goes on.
416 }
417
418 mDefaultKeySsb.clear();
419 mDefaultKeySsb.clearSpans();
420 Selection.setSelection(mDefaultKeySsb, 0);
421
422 return true;
423 }
424 }
425
426 return handled;
427 }
428
429 /**
430 * Restores the previous state, if it exists.
431 *
432 * @param savedState The previous state.
433 */
434 private void restoreState(Bundle savedState) {
435 if (savedState == null) {
436 return;
437 }
438
439 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1);
440 if (currentScreen > -1) {
441 mWorkspace.setCurrentScreen(currentScreen);
442 }
443
444 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1);
445 if (addScreen > -1) {
446 mAddItemCellInfo = new CellLayout.CellInfo();
447 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
448 addItemCellInfo.valid = true;
449 addItemCellInfo.screen = addScreen;
450 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X);
451 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y);
452 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X);
453 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y);
454 addItemCellInfo.findVacantCellsFromOccupied(
455 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS),
456 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X),
457 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y));
458 mRestoring = true;
459 }
460
461 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false);
462 if (renameFolder) {
463 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID);
464 mFolderInfo = sModel.getFolderById(this, id);
465 mRestoring = true;
466 }
467 }
468
469 /**
470 * Finds all the views we need and configure them properly.
471 */
472 private void setupViews() {
473 mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
474 final DragLayer dragLayer = mDragLayer;
475
476 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace);
477 final Workspace workspace = mWorkspace;
478
479 mDrawer = (SlidingDrawer) dragLayer.findViewById(R.id.drawer);
480 final SlidingDrawer drawer = mDrawer;
481
482 mAllAppsGrid = (AllAppsGridView) drawer.getContent();
483 final AllAppsGridView grid = mAllAppsGrid;
484
485 final DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone);
486
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700487 mHandleView = (HandleView) drawer.findViewById(R.id.all_apps);
488 mHandleView.setLauncher(this);
489 mHandleIcon = (TransitionDrawable) mHandleView.getDrawable();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800490 mHandleIcon.setCrossFadeEnabled(true);
491
492 drawer.lock();
493 final DrawerManager drawerManager = new DrawerManager();
494 drawer.setOnDrawerOpenListener(drawerManager);
495 drawer.setOnDrawerCloseListener(drawerManager);
496 drawer.setOnDrawerScrollListener(drawerManager);
497
498 grid.setTextFilterEnabled(true);
499 grid.setDragger(dragLayer);
500 grid.setLauncher(this);
501
502 workspace.setOnLongClickListener(this);
503 workspace.setDragger(dragLayer);
504 workspace.setLauncher(this);
505 loadWallpaper();
506
507 deleteZone.setLauncher(this);
508 deleteZone.setDragController(dragLayer);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700509 deleteZone.setHandle(mHandleView);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800510
511 dragLayer.setIgnoredDropTarget(grid);
512 dragLayer.setDragScoller(workspace);
513 dragLayer.setDragListener(deleteZone);
514 }
515
516 /**
517 * Creates a view representing a shortcut.
518 *
519 * @param info The data structure describing the shortcut.
520 *
521 * @return A View inflated from R.layout.application.
522 */
523 View createShortcut(ApplicationInfo info) {
524 return createShortcut(R.layout.application,
525 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
526 }
527
528 /**
529 * Creates a view representing a shortcut inflated from the specified resource.
530 *
531 * @param layoutResId The id of the XML layout used to create the shortcut.
532 * @param parent The group the shortcut belongs to.
533 * @param info The data structure describing the shortcut.
534 *
535 * @return A View inflated from layoutResId.
536 */
537 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) {
538 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false);
539
540 if (!info.filtered) {
541 info.icon = Utilities.createIconThumbnail(info.icon, this);
542 info.filtered = true;
543 }
544
545 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null);
546 favorite.setText(info.title);
547 favorite.setTag(info);
548 favorite.setOnClickListener(this);
549
550 return favorite;
551 }
552
553 /**
554 * Add an application shortcut to the workspace.
555 *
556 * @param data The intent describing the application.
557 * @param cellInfo The position on screen where to create the shortcut.
558 */
559 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo,
560 boolean insertAtFirst) {
561 cellInfo.screen = mWorkspace.getCurrentScreen();
562 if (!findSingleSlot(cellInfo)) return;
563
564 // Find details for this application
565 ComponentName component = data.getComponent();
566 PackageManager packageManager = context.getPackageManager();
567 ActivityInfo activityInfo = null;
568 try {
569 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */);
570 } catch (NameNotFoundException e) {
571 Log.e(LOG_TAG, "Couldn't find ActivityInfo for selected application", e);
572 }
573
574 if (activityInfo != null) {
575 ApplicationInfo itemInfo = new ApplicationInfo();
576
577 itemInfo.title = activityInfo.loadLabel(packageManager);
578 if (itemInfo.title == null) {
579 itemInfo.title = activityInfo.name;
580 }
581
582 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK |
583 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
584 itemInfo.icon = activityInfo.loadIcon(packageManager);
585 itemInfo.container = ItemInfo.NO_ID;
586
587 mWorkspace.addApplicationShortcut(itemInfo, cellInfo, insertAtFirst);
588 }
589 }
590
591 /**
592 * Add a shortcut to the workspace.
593 *
594 * @param data The intent describing the shortcut.
595 * @param cellInfo The position on screen where to create the shortcut.
596 * @param insertAtFirst
597 */
598 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo,
599 boolean insertAtFirst) {
600 cellInfo.screen = mWorkspace.getCurrentScreen();
601 if (!findSingleSlot(cellInfo)) return;
602
603 final ApplicationInfo info = addShortcut(this, data, cellInfo, false);
604
605 if (!mRestoring) {
606 sModel.addDesktopItem(info);
607
608 final View view = createShortcut(info);
609 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
610 } else if (sModel.isDesktopLoaded()) {
611 sModel.addDesktopItem(info);
612 }
613 }
614
615
616 /**
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700617 * Add a widget to the workspace.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800618 *
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700619 * @param data The intent describing the appWidgetId.
620 * @param cellInfo The position on screen where to create the widget.
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800621 */
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700622 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo,
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800623 boolean insertAtFirst) {
624
625 Bundle extras = data.getExtras();
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700626 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800627
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700628 d(LOG_TAG, "dumping extras content="+extras.toString());
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800629
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700630 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800631
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700632 // Calculate the grid spans needed to fit this widget
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800633 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen);
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700634 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800635
636 // Try finding open space on Launcher screen
637 final int[] xy = mCellCoordinates;
638 if (!findSlot(cellInfo, xy, spans[0], spans[1])) return;
639
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700640 // Build Launcher-specific widget info and save to database
641 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800642 launcherInfo.spanX = spans[0];
643 launcherInfo.spanY = spans[1];
644
645 LauncherModel.addItemToDatabase(this, launcherInfo,
646 LauncherSettings.Favorites.CONTAINER_DESKTOP,
647 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
648
649 if (!mRestoring) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700650 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800651
652 // Perform actual inflation because we're live
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700653 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800654
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700655 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800656 launcherInfo.hostView.setTag(launcherInfo);
657
658 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1],
659 launcherInfo.spanX, launcherInfo.spanY, insertAtFirst);
660 } else if (sModel.isDesktopLoaded()) {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700661 sModel.addDesktopAppWidget(launcherInfo);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800662 }
663 }
664
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700665 public LauncherAppWidgetHost getAppWidgetHost() {
666 return mAppWidgetHost;
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800667 }
668
669 static ApplicationInfo addShortcut(Context context, Intent data,
670 CellLayout.CellInfo cellInfo, boolean notify) {
671
672 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
673 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
674 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
675
676 Drawable icon = null;
677 boolean filtered = false;
678 boolean customIcon = false;
679 Intent.ShortcutIconResource iconResource = null;
680
681 if (bitmap != null) {
682 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context));
683 filtered = true;
684 customIcon = true;
685 } else {
686 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
687 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
688 try {
689 iconResource = (Intent.ShortcutIconResource) extra;
690 final PackageManager packageManager = context.getPackageManager();
691 Resources resources = packageManager.getResourcesForApplication(
692 iconResource.packageName);
693 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
694 icon = resources.getDrawable(id);
695 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700696 w(LOG_TAG, "Could not load shortcut icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800697 }
698 }
699 }
700
701 if (icon == null) {
702 icon = context.getPackageManager().getDefaultActivityIcon();
703 }
704
705 final ApplicationInfo info = new ApplicationInfo();
706 info.icon = icon;
707 info.filtered = filtered;
708 info.title = name;
709 info.intent = intent;
710 info.customIcon = customIcon;
711 info.iconResource = iconResource;
712
713 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
714 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
715 return info;
716 }
717
718 @Override
719 protected void onNewIntent(Intent intent) {
720 super.onNewIntent(intent);
721
722 // Close the menu
723 if (Intent.ACTION_MAIN.equals(intent.getAction())) {
724 getWindow().closeAllPanels();
725
726 try {
727 dismissDialog(DIALOG_CREATE_SHORTCUT);
728 // Unlock the workspace if the dialog was showing
729 mWorkspace.unlock();
730 } catch (Exception e) {
731 // An exception is thrown if the dialog is not visible, which is fine
732 }
733
734 try {
735 dismissDialog(DIALOG_RENAME_FOLDER);
736 // Unlock the workspace if the dialog was showing
737 mWorkspace.unlock();
738 } catch (Exception e) {
739 // An exception is thrown if the dialog is not visible, which is fine
740 }
741
742 // If we are already in front we go back to the default screen,
743 // otherwise we don't
744 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) !=
745 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) {
746 if (!mWorkspace.isDefaultScreenShowing()) {
747 mWorkspace.moveToDefaultScreen();
748 }
749 closeDrawer();
750 View v = getWindow().peekDecorView();
751 if (v != null && v.getWindowToken() != null) {
752 InputMethodManager imm = (InputMethodManager)getSystemService(
753 INPUT_METHOD_SERVICE);
754 imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
755 }
756 } else {
757 closeDrawer(false);
758 }
759 }
760 }
761
762 @Override
763 protected void onRestoreInstanceState(Bundle savedInstanceState) {
764 // Do not call super here
765 mSavedInstanceState = savedInstanceState;
766 }
767
768 @Override
769 protected void onSaveInstanceState(Bundle outState) {
770 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen());
771
772 final ArrayList<Folder> folders = mWorkspace.getOpenFolders();
773 if (folders.size() > 0) {
774 final int count = folders.size();
775 long[] ids = new long[count];
776 for (int i = 0; i < count; i++) {
777 final FolderInfo info = folders.get(i).getInfo();
778 ids[i] = info.id;
779 }
780 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids);
781 } else {
782 super.onSaveInstanceState(outState);
783 }
784
785 if (mDrawer.isOpened()) {
786 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true);
787 }
788
789 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) {
790 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo;
791 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen);
792
793 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen);
794 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX);
795 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY);
796 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX);
797 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY);
798 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX());
799 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY());
800 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS,
801 layout.getOccupiedCells());
802 }
803
804 if (mFolderInfo != null && mWaitingForResult) {
805 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true);
806 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id);
807 }
808 }
809
810 @Override
811 public void onDestroy() {
812 mDestroyed = true;
813
814 super.onDestroy();
815
816 try {
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700817 mAppWidgetHost.stopListening();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800818 } catch (NullPointerException ex) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700819 w(LOG_TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800820 }
821
822 TextKeyListener.getInstance().release();
823
824 mAllAppsGrid.clearTextFilter();
825 mAllAppsGrid.setAdapter(null);
826 sModel.unbind();
827 sModel.abortLoaders();
828
829 getContentResolver().unregisterContentObserver(mObserver);
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -0700830 getContentResolver().unregisterContentObserver(mAppWidgetResetObserver);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800831 unregisterReceiver(mApplicationsReceiver);
832 }
833
834 @Override
835 public void startActivityForResult(Intent intent, int requestCode) {
836 mWaitingForResult = true;
837 super.startActivityForResult(intent, requestCode);
838 }
839
840 @Override
841 public void startSearch(String initialQuery, boolean selectInitialQuery,
842 Bundle appSearchData, boolean globalSearch) {
843 if (appSearchData == null) {
844 appSearchData = new Bundle();
845 appSearchData.putString(SearchManager.SOURCE, "launcher-search");
846 }
847 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
848 }
849
850 @Override
851 public boolean onCreateOptionsMenu(Menu menu) {
852 if (mDesktopLocked) return false;
853
854 super.onCreateOptionsMenu(menu);
855 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add)
856 .setIcon(android.R.drawable.ic_menu_add)
857 .setAlphabeticShortcut('A');
858 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper)
859 .setIcon(android.R.drawable.ic_menu_gallery)
860 .setAlphabeticShortcut('W');
861 menu.add(0, MENU_SEARCH, 0, R.string.menu_search)
862 .setIcon(android.R.drawable.ic_search_category_default)
863 .setAlphabeticShortcut(SearchManager.MENU_KEY);
864 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications)
865 .setIcon(com.android.internal.R.drawable.ic_menu_notifications)
866 .setAlphabeticShortcut('N');
867
868 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS);
869 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
870 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
871
872 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings)
873 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P')
874 .setIntent(settings);
875
876 return true;
877 }
878
879 @Override
880 public boolean onPrepareOptionsMenu(Menu menu) {
881 super.onPrepareOptionsMenu(menu);
882
883 mMenuAddInfo = mWorkspace.findAllVacantCells(null);
884 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid);
885
886 return true;
887 }
888
889 @Override
890 public boolean onOptionsItemSelected(MenuItem item) {
891 switch (item.getItemId()) {
892 case MENU_ADD:
893 addItems();
894 return true;
895 case MENU_WALLPAPER_SETTINGS:
896 startWallpaper();
897 return true;
898 case MENU_SEARCH:
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700899 onSearchRequested();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800900 return true;
901 case MENU_NOTIFICATIONS:
902 showNotifications();
903 return true;
904 }
905
906 return super.onOptionsItemSelected(item);
907 }
908
The Android Open Source Projectca9475f2009-03-13 13:04:24 -0700909 @Override
910 public boolean onSearchRequested() {
911 if (mWorkspace.snapToSearch()) {
912 closeDrawer(true); // search widget: get drawer out of the way
913 return true;
914 } else {
915 return super.onSearchRequested(); // no search widget: use system search UI
916 }
917 }
918
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800919 private void addItems() {
920 showAddDialog(mMenuAddInfo);
921 }
922
923 private void removeShortcutsForPackage(String packageName) {
924 if (packageName != null && packageName.length() > 0) {
925 mWorkspace.removeShortcutsForPackage(packageName);
926 }
927 }
928
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700929 private void updateShortcutsForPackage(String packageName) {
930 if (packageName != null && packageName.length() > 0) {
931 mWorkspace.updateShortcutsForPackage(packageName);
932 }
933 }
934
The Android Open Source Project7376fae2009-03-11 12:11:58 -0700935 void addAppWidget(Intent data) {
936 // TODO: catch bad widget exception when sent
937 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800938
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700939 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET);
940 if (SEARCH_WIDGET.equals(customWidget)) {
941 // We don't need this any more, since this isn't a real app widget.
942 mAppWidgetHost.deleteAppWidgetId(appWidgetId);
943 // add the search widget
944 addSearch();
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800945 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -0700946 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
947
948 if (appWidget.configure != null) {
949 // Launch over to configure widget, if needed
950 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
951 intent.setComponent(appWidget.configure);
952 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
953
954 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
955 } else {
956 // Otherwise just add it
957 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data);
958 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800959 }
960 }
961
962 void addSearch() {
963 final Widget info = Widget.makeSearch();
964 final CellLayout.CellInfo cellInfo = mAddItemCellInfo;
965
966 final int[] xy = mCellCoordinates;
967 final int spanX = info.spanX;
968 final int spanY = info.spanY;
969
970 if (!findSlot(cellInfo, xy, spanX, spanY)) return;
971
972 sModel.addDesktopItem(info);
973 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
974 mWorkspace.getCurrentScreen(), xy[0], xy[1], false);
975
976 final View view = mInflater.inflate(info.layoutResource, null);
977 view.setTag(info);
978
979 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY);
980 }
981
982 void addShortcut(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -0700983 // Handle case where user selected "Applications"
984 String applicationName = getResources().getString(R.string.group_applications);
985 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
986
987 if (applicationName != null && applicationName.equals(shortcutName)) {
988 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
989 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
990
991 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
992 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
993 startActivityForResult(pickIntent, REQUEST_PICK_APPLICATION);
994 } else {
995 startActivityForResult(intent, REQUEST_CREATE_SHORTCUT);
996 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -0800997 }
998
999 void addLiveFolder(Intent intent) {
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001000 // Handle case where user selected "Folder"
Jeffrey Sharkeyc4bbd0a2009-03-24 22:47:52 -07001001 String folderName = getResources().getString(R.string.group_folder);
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001002 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME);
1003
1004 if (folderName != null && folderName.equals(shortcutName)) {
1005 addFolder(!mDesktopLocked);
1006 } else {
1007 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER);
1008 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001009 }
1010
1011 void addFolder(boolean insertAtFirst) {
1012 UserFolderInfo folderInfo = new UserFolderInfo();
1013 folderInfo.title = getText(R.string.folder_name);
1014
1015 CellLayout.CellInfo cellInfo = mAddItemCellInfo;
1016 cellInfo.screen = mWorkspace.getCurrentScreen();
1017 if (!findSingleSlot(cellInfo)) return;
1018
1019 // Update the model
1020 LauncherModel.addItemToDatabase(this, folderInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1021 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false);
1022 sModel.addDesktopItem(folderInfo);
1023 sModel.addFolder(folderInfo);
1024
1025 // Create the view
1026 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1027 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo);
1028 mWorkspace.addInCurrentScreen(newFolder,
1029 cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1030 }
1031
1032 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo,
1033 boolean insertAtFirst) {
1034 cellInfo.screen = mWorkspace.getCurrentScreen();
1035 if (!findSingleSlot(cellInfo)) return;
1036
1037 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false);
1038
1039 if (!mRestoring) {
1040 sModel.addDesktopItem(info);
1041
1042 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this,
1043 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info);
1044 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, insertAtFirst);
1045 } else if (sModel.isDesktopLoaded()) {
1046 sModel.addDesktopItem(info);
1047 }
1048 }
1049
1050 static LiveFolderInfo addLiveFolder(Context context, Intent data,
1051 CellLayout.CellInfo cellInfo, boolean notify) {
1052
1053 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT);
1054 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME);
1055
1056 Drawable icon = null;
1057 boolean filtered = false;
1058 Intent.ShortcutIconResource iconResource = null;
1059
1060 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON);
1061 if (extra != null && extra instanceof Intent.ShortcutIconResource) {
1062 try {
1063 iconResource = (Intent.ShortcutIconResource) extra;
1064 final PackageManager packageManager = context.getPackageManager();
1065 Resources resources = packageManager.getResourcesForApplication(
1066 iconResource.packageName);
1067 final int id = resources.getIdentifier(iconResource.resourceName, null, null);
1068 icon = resources.getDrawable(id);
1069 } catch (Exception e) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001070 w(LOG_TAG, "Could not load live folder icon: " + extra);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001071 }
1072 }
1073
1074 if (icon == null) {
1075 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder);
1076 }
1077
1078 final LiveFolderInfo info = new LiveFolderInfo();
1079 info.icon = icon;
1080 info.filtered = filtered;
1081 info.title = name;
1082 info.iconResource = iconResource;
1083 info.uri = data.getData();
1084 info.baseIntent = baseIntent;
1085 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE,
1086 LiveFolders.DISPLAY_MODE_GRID);
1087
1088 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP,
1089 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify);
1090 sModel.addFolder(info);
1091
1092 return info;
1093 }
1094
1095 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) {
1096 final int[] xy = new int[2];
1097 if (findSlot(cellInfo, xy, 1, 1)) {
1098 cellInfo.cellX = xy[0];
1099 cellInfo.cellY = xy[1];
1100 return true;
1101 }
1102 return false;
1103 }
1104
1105 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) {
1106 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1107 boolean[] occupied = mSavedState != null ?
1108 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null;
1109 cellInfo = mWorkspace.findAllVacantCells(occupied);
1110 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) {
1111 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show();
1112 return false;
1113 }
1114 }
1115 return true;
1116 }
1117
1118 private void showNotifications() {
1119 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE);
1120 if (statusBar != null) {
1121 statusBar.expand();
1122 }
1123 }
1124
1125 private void startWallpaper() {
1126 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
1127 startActivity(Intent.createChooser(pickWallpaper, getString(R.string.chooser_wallpaper)));
1128 }
1129
1130 /**
1131 * Registers various intent receivers. The current implementation registers
1132 * only a wallpaper intent receiver to let other applications change the
1133 * wallpaper.
1134 */
1135 private void registerIntentReceivers() {
1136 if (sWallpaperReceiver == null) {
1137 final Application application = getApplication();
1138
1139 sWallpaperReceiver = new WallpaperIntentReceiver(application, this);
1140
1141 IntentFilter filter = new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
1142 application.registerReceiver(sWallpaperReceiver, filter);
1143 } else {
1144 sWallpaperReceiver.setLauncher(this);
1145 }
1146
1147 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
1148 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1149 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1150 filter.addDataScheme("package");
1151 registerReceiver(mApplicationsReceiver, filter);
1152 }
1153
1154 /**
1155 * Registers various content observers. The current implementation registers
1156 * only a favorites observer to keep track of the favorites applications.
1157 */
1158 private void registerContentObservers() {
1159 ContentResolver resolver = getContentResolver();
1160 resolver.registerContentObserver(LauncherSettings.Favorites.CONTENT_URI, true, mObserver);
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -07001161 resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI, true, mAppWidgetResetObserver);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001162 }
1163
1164 @Override
1165 public boolean dispatchKeyEvent(KeyEvent event) {
1166 if (event.getAction() == KeyEvent.ACTION_DOWN) {
1167 switch (event.getKeyCode()) {
1168 case KeyEvent.KEYCODE_BACK:
1169 mWorkspace.dispatchKeyEvent(event);
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001170 if (mDrawer.isOpened()) {
1171 closeDrawer();
1172 } else {
1173 closeFolder();
1174 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001175 return true;
1176 case KeyEvent.KEYCODE_HOME:
1177 return true;
1178 }
1179 }
1180
1181 return super.dispatchKeyEvent(event);
1182 }
1183
1184 private void closeDrawer() {
1185 closeDrawer(true);
1186 }
1187
1188 private void closeDrawer(boolean animated) {
1189 if (mDrawer.isOpened()) {
1190 if (animated) {
1191 mDrawer.animateClose();
1192 } else {
1193 mDrawer.close();
1194 }
1195 if (mDrawer.hasFocus()) {
1196 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1197 }
1198 }
1199 }
1200
1201 private void closeFolder() {
1202 Folder folder = mWorkspace.getOpenFolder();
1203 if (folder != null) {
1204 closeFolder(folder);
1205 }
1206 }
1207
1208 void closeFolder(Folder folder) {
1209 folder.getInfo().opened = false;
1210 ViewGroup parent = (ViewGroup) folder.getParent();
1211 if (parent != null) {
1212 parent.removeView(folder);
1213 }
1214 folder.onClose();
1215 }
1216
1217 /**
1218 * When the notification that favorites have changed is received, requests
1219 * a favorites list refresh.
1220 */
1221 private void onFavoritesChanged() {
1222 mDesktopLocked = true;
1223 mDrawer.lock();
1224 sModel.loadUserItems(false, this, false, false);
1225 }
1226
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -07001227 /**
1228 * When reset, we handle by calling {@link AppWidgetHost#startListening()}
1229 * to make sure our callbacks are set correctly.
1230 */
1231 private void onAppWidgetReset() {
1232 if (mAppWidgetHost != null) {
1233 mAppWidgetHost.startListening();
1234 }
1235 }
1236
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001237 void onDesktopItemsLoaded() {
1238 if (mDestroyed) return;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001239 bindDesktopItems();
1240 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001241
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001242 /**
1243 * Refreshes the shortcuts shown on the workspace.
1244 */
1245 private void bindDesktopItems() {
1246 final ArrayList<ItemInfo> shortcuts = sModel.getDesktopItems();
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001247 final ArrayList<LauncherAppWidgetInfo> appWidgets = sModel.getDesktopAppWidgets();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001248 final ApplicationsAdapter drawerAdapter = sModel.getApplicationsAdapter();
1249 if (shortcuts == null || appWidgets == null || drawerAdapter == null) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001250 return;
1251 }
1252
Romain Guy829f56a2009-03-27 16:58:13 -07001253 mAllAppsGrid.setAdapter(drawerAdapter);
1254
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001255 final Workspace workspace = mWorkspace;
1256 int count = workspace.getChildCount();
1257 for (int i = 0; i < count; i++) {
1258 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout();
1259 }
1260
1261 if (DEBUG_USER_INTERFACE) {
1262 android.widget.Button finishButton = new android.widget.Button(this);
1263 finishButton.setText("Finish");
1264 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1);
1265
1266 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() {
1267 public void onClick(View v) {
1268 finish();
1269 }
1270 });
1271 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001272
1273 // Flag any old binder to terminate early
1274 if (mBinder != null) {
1275 mBinder.mTerminate = true;
1276 }
1277
Romain Guy829f56a2009-03-27 16:58:13 -07001278 mBinder = new DesktopBinder(this, shortcuts, appWidgets);
Jeffrey Sharkey2d132af2009-03-24 21:21:09 -07001279 mBinder.startBindingItems();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001280 }
1281
1282 private void bindItems(Launcher.DesktopBinder binder,
1283 ArrayList<ItemInfo> shortcuts, int start, int count) {
1284
1285 final Workspace workspace = mWorkspace;
1286 final boolean desktopLocked = mDesktopLocked;
1287
1288 final int end = Math.min(start + DesktopBinder.ITEMS_COUNT, count);
1289 int i = start;
1290
1291 for ( ; i < end; i++) {
1292 final ItemInfo item = shortcuts.get(i);
1293 switch (item.itemType) {
1294 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION:
1295 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT:
1296 final View shortcut = createShortcut((ApplicationInfo) item);
1297 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1,
1298 !desktopLocked);
1299 break;
1300 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER:
1301 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this,
1302 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1303 (UserFolderInfo) item);
1304 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1,
1305 !desktopLocked);
1306 break;
1307 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER:
1308 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml(
1309 R.layout.live_folder_icon, this,
1310 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()),
1311 (LiveFolderInfo) item);
1312 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1,
1313 !desktopLocked);
1314 break;
1315 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH:
1316 final int screen = workspace.getCurrentScreen();
1317 final View view = mInflater.inflate(R.layout.widget_search,
1318 (ViewGroup) workspace.getChildAt(screen), false);
1319
1320 final Widget widget = (Widget) item;
1321 view.setTag(widget);
1322
1323 workspace.addWidget(view, widget, !desktopLocked);
1324 break;
1325 }
1326 }
1327
1328 workspace.requestLayout();
1329
1330 if (end >= count) {
1331 finishBindDesktopItems();
Romain Guy829f56a2009-03-27 16:58:13 -07001332 binder.startBindingAppWidgetsWhenIdle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001333 } else {
1334 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_ITEMS, i, count).sendToTarget();
1335 }
1336 }
1337
1338 private void finishBindDesktopItems() {
1339 if (mSavedState != null) {
1340 if (!mWorkspace.hasFocus()) {
1341 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus();
1342 }
1343
1344 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS);
1345 if (userFolders != null) {
1346 for (long folderId : userFolders) {
1347 final FolderInfo info = sModel.findFolderById(folderId);
1348 if (info != null) {
1349 openFolder(info);
1350 }
1351 }
1352 final Folder openFolder = mWorkspace.getOpenFolder();
1353 if (openFolder != null) {
1354 openFolder.requestFocus();
1355 }
1356 }
1357
1358 final boolean allApps = mSavedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false);
1359 if (allApps) {
1360 mDrawer.open();
1361 }
1362
1363 mSavedState = null;
1364 }
1365
1366 if (mSavedInstanceState != null) {
1367 super.onRestoreInstanceState(mSavedInstanceState);
1368 mSavedInstanceState = null;
1369 }
1370
1371 if (mDrawer.isOpened() && !mDrawer.hasFocus()) {
1372 mDrawer.requestFocus();
1373 }
1374
1375 mDesktopLocked = false;
1376 mDrawer.unlock();
1377 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001378
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001379 private void bindAppWidgets(Launcher.DesktopBinder binder,
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001380 LinkedList<LauncherAppWidgetInfo> appWidgets) {
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001381
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001382 final Workspace workspace = mWorkspace;
1383 final boolean desktopLocked = mDesktopLocked;
1384
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001385 if (!appWidgets.isEmpty()) {
1386 final LauncherAppWidgetInfo item = appWidgets.removeFirst();
1387
1388 final int appWidgetId = item.appWidgetId;
Romain Guy829f56a2009-03-27 16:58:13 -07001389 final AppWidgetProviderInfo appWidgetInfo =
1390 mAppWidgetManager.getAppWidgetInfo(appWidgetId);
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001391 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo);
1392
Romain Guy829f56a2009-03-27 16:58:13 -07001393 if (LOGD) {
1394 d(LOG_TAG, String.format("about to setAppWidget for id=%d, info=%s",
1395 appWidgetId, appWidgetInfo));
1396 }
Jeffrey Sharkeyd18299f2009-03-24 18:11:49 -07001397
1398 item.hostView.setAppWidget(appWidgetId, appWidgetInfo);
1399 item.hostView.setTag(item);
1400
1401 workspace.addInScreen(item.hostView, item.screen, item.cellX,
1402 item.cellY, item.spanX, item.spanY, !desktopLocked);
1403
1404 workspace.requestLayout();
1405 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001406
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001407 if (appWidgets.isEmpty()) {
1408 if (PROFILE_ROTATE) {
1409 android.os.Debug.stopMethodTracing();
1410 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001411 } else {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001412 binder.obtainMessage(DesktopBinder.MESSAGE_BIND_APPWIDGETS).sendToTarget();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001413 }
1414 }
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001415
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001416 DragController getDragController() {
1417 return mDragLayer;
1418 }
1419
1420 /**
1421 * Launches the intent referred by the clicked shortcut.
1422 *
1423 * @param v The view representing the clicked shortcut.
1424 */
1425 public void onClick(View v) {
1426 Object tag = v.getTag();
1427 if (tag instanceof ApplicationInfo) {
1428 // Open shortcut
1429 final Intent intent = ((ApplicationInfo) tag).intent;
1430 startActivitySafely(intent);
1431 } else if (tag instanceof FolderInfo) {
1432 handleFolderClick((FolderInfo) tag);
1433 }
1434 }
1435
1436 void startActivitySafely(Intent intent) {
1437 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1438 try {
1439 startActivity(intent);
1440 } catch (ActivityNotFoundException e) {
1441 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1442 } catch (SecurityException e) {
1443 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
1444 Log.e(LOG_TAG, "Launcher does not have the permission to launch " + intent +
1445 ". Make sure to create a MAIN intent-filter for the corresponding activity " +
1446 "or use the exported attribute for this activity.", e);
1447 }
1448 }
1449
1450 private void handleFolderClick(FolderInfo folderInfo) {
1451 if (!folderInfo.opened) {
1452 // Close any open folder
1453 closeFolder();
1454 // Open the requested folder
1455 openFolder(folderInfo);
1456 } else {
1457 // Find the open folder...
1458 Folder openFolder = mWorkspace.getFolderForTag(folderInfo);
1459 int folderScreen;
1460 if (openFolder != null) {
1461 folderScreen = mWorkspace.getScreenForView(openFolder);
1462 // .. and close it
1463 closeFolder(openFolder);
1464 if (folderScreen != mWorkspace.getCurrentScreen()) {
1465 // Close any folder open on the current screen
1466 closeFolder();
1467 // Pull the folder onto this screen
1468 openFolder(folderInfo);
1469 }
1470 }
1471 }
1472 }
1473
1474 private void loadWallpaper() {
1475 // The first time the application is started, we load the wallpaper from
1476 // the ApplicationContext
1477 if (sWallpaper == null) {
1478 final Drawable drawable = getWallpaper();
1479 if (drawable instanceof BitmapDrawable) {
1480 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1481 } else {
1482 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1483 }
1484 }
1485 mWorkspace.loadWallpaper(sWallpaper);
1486 }
1487
1488 /**
1489 * Opens the user fodler described by the specified tag. The opening of the folder
1490 * is animated relative to the specified View. If the View is null, no animation
1491 * is played.
1492 *
1493 * @param folderInfo The FolderInfo describing the folder to open.
1494 */
1495 private void openFolder(FolderInfo folderInfo) {
1496 Folder openFolder;
1497
1498 if (folderInfo instanceof UserFolderInfo) {
1499 openFolder = UserFolder.fromXml(this);
1500 } else if (folderInfo instanceof LiveFolderInfo) {
1501 openFolder = com.android.launcher.LiveFolder.fromXml(this, folderInfo);
1502 } else {
1503 return;
1504 }
1505
1506 openFolder.setDragger(mDragLayer);
1507 openFolder.setLauncher(this);
1508
1509 openFolder.bind(folderInfo);
1510 folderInfo.opened = true;
1511
1512 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4);
1513 openFolder.onOpen();
1514 }
1515
1516 /**
1517 * Returns true if the workspace is being loaded. When the workspace is loading,
1518 * no user interaction should be allowed to avoid any conflict.
1519 *
1520 * @return True if the workspace is locked, false otherwise.
1521 */
1522 boolean isWorkspaceLocked() {
1523 return mDesktopLocked;
1524 }
1525
1526 public boolean onLongClick(View v) {
1527 if (mDesktopLocked) {
1528 return false;
1529 }
1530
1531 if (!(v instanceof CellLayout)) {
1532 v = (View) v.getParent();
1533 }
1534
1535 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag();
1536
1537 // This happens when long clicking an item with the dpad/trackball
1538 if (cellInfo == null) {
1539 return true;
1540 }
1541
1542 if (mWorkspace.allowLongPress()) {
1543 if (cellInfo.cell == null) {
1544 if (cellInfo.valid) {
1545 // User long pressed on empty space
The Android Open Source Projectca9475f2009-03-13 13:04:24 -07001546 mWorkspace.setAllowLongPress(false);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001547 showAddDialog(cellInfo);
1548 }
1549 } else {
1550 if (!(cellInfo.cell instanceof Folder)) {
1551 // User long pressed on an item
1552 mWorkspace.startDrag(cellInfo);
1553 }
1554 }
1555 }
1556 return true;
1557 }
1558
1559 static LauncherModel getModel() {
1560 return sModel;
1561 }
1562
1563 void closeAllApplications() {
1564 mDrawer.close();
1565 }
1566
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001567 View getDrawerHandle() {
1568 return mHandleView;
1569 }
1570
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001571 boolean isDrawerDown() {
1572 return !mDrawer.isMoving() && !mDrawer.isOpened();
1573 }
1574
1575 boolean isDrawerUp() {
1576 return mDrawer.isOpened() && !mDrawer.isMoving();
1577 }
1578
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001579 boolean isDrawerMoving() {
1580 return mDrawer.isMoving();
1581 }
1582
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001583 Workspace getWorkspace() {
1584 return mWorkspace;
1585 }
1586
1587 GridView getApplicationsGrid() {
1588 return mAllAppsGrid;
1589 }
1590
1591 @Override
1592 protected Dialog onCreateDialog(int id) {
1593 switch (id) {
1594 case DIALOG_CREATE_SHORTCUT:
1595 return new CreateShortcut().createDialog();
1596 case DIALOG_RENAME_FOLDER:
1597 return new RenameFolder().createDialog();
1598 }
1599
1600 return super.onCreateDialog(id);
1601 }
1602
1603 @Override
1604 protected void onPrepareDialog(int id, Dialog dialog) {
1605 switch (id) {
1606 case DIALOG_CREATE_SHORTCUT:
1607 mWorkspace.lock();
1608 break;
1609 case DIALOG_RENAME_FOLDER:
1610 mWorkspace.lock();
1611 EditText input = (EditText) dialog.findViewById(R.id.folder_name);
1612 final CharSequence text = mFolderInfo.title;
1613 input.setText(text);
1614 input.setSelection(0, text.length());
1615 break;
1616 }
1617 }
1618
1619 void showRenameDialog(FolderInfo info) {
1620 mFolderInfo = info;
1621 mWaitingForResult = true;
1622 showDialog(DIALOG_RENAME_FOLDER);
1623 }
1624
1625 private void showAddDialog(CellLayout.CellInfo cellInfo) {
1626 mAddItemCellInfo = cellInfo;
1627 mWaitingForResult = true;
1628 showDialog(DIALOG_CREATE_SHORTCUT);
1629 }
1630
1631 private class RenameFolder {
1632 private EditText mInput;
1633
1634 Dialog createDialog() {
1635 mWaitingForResult = true;
1636 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null);
1637 mInput = (EditText) layout.findViewById(R.id.folder_name);
1638
1639 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1640 builder.setIcon(0);
1641 builder.setTitle(getString(R.string.rename_folder_title));
1642 builder.setCancelable(true);
1643 builder.setOnCancelListener(new Dialog.OnCancelListener() {
1644 public void onCancel(DialogInterface dialog) {
1645 cleanup();
1646 }
1647 });
1648 builder.setNegativeButton(getString(R.string.cancel_action),
1649 new Dialog.OnClickListener() {
1650 public void onClick(DialogInterface dialog, int which) {
1651 cleanup();
1652 }
1653 }
1654 );
1655 builder.setPositiveButton(getString(R.string.rename_action),
1656 new Dialog.OnClickListener() {
1657 public void onClick(DialogInterface dialog, int which) {
1658 changeFolderName();
1659 }
1660 }
1661 );
1662 builder.setView(layout);
1663 return builder.create();
1664 }
1665
1666 private void changeFolderName() {
1667 final String name = mInput.getText().toString();
1668 if (!TextUtils.isEmpty(name)) {
1669 // Make sure we have the right folder info
1670 mFolderInfo = sModel.findFolderById(mFolderInfo.id);
1671 mFolderInfo.title = name;
1672 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo);
1673
1674 if (mDesktopLocked) {
1675 mDrawer.lock();
1676 sModel.loadUserItems(false, Launcher.this, false, false);
1677 } else {
1678 final FolderIcon folderIcon = (FolderIcon)
1679 mWorkspace.getViewForTag(mFolderInfo);
1680 if (folderIcon != null) {
1681 folderIcon.setText(name);
1682 getWorkspace().requestLayout();
1683 } else {
1684 mDesktopLocked = true;
1685 mDrawer.lock();
1686 sModel.loadUserItems(false, Launcher.this, false, false);
1687 }
1688 }
1689 }
1690 cleanup();
1691 }
1692
1693 private void cleanup() {
1694 mWorkspace.unlock();
1695 dismissDialog(DIALOG_RENAME_FOLDER);
1696 mWaitingForResult = false;
1697 mFolderInfo = null;
1698 }
1699 }
1700
1701 /**
1702 * Displays the shortcut creation dialog and launches, if necessary, the
1703 * appropriate activity.
1704 */
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001705 private class CreateShortcut implements DialogInterface.OnClickListener,
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001706 DialogInterface.OnCancelListener {
1707 private AddAdapter mAdapter;
Romain Guy9ffb5432009-03-24 21:04:15 -07001708
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001709 Dialog createDialog() {
1710 mWaitingForResult = true;
1711
1712 mAdapter = new AddAdapter(Launcher.this);
1713
1714 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this);
1715 builder.setTitle(getString(R.string.menu_item_add_item));
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001716 builder.setAdapter(mAdapter, this);
1717
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001718 builder.setInverseBackgroundForced(true);
1719
1720 AlertDialog dialog = builder.create();
1721 dialog.setOnCancelListener(this);
1722
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001723 return dialog;
1724 }
1725
1726 public void onCancel(DialogInterface dialog) {
1727 mWaitingForResult = false;
1728 cleanup();
1729 }
1730
1731 private void cleanup() {
1732 mWorkspace.unlock();
1733 dismissDialog(DIALOG_CREATE_SHORTCUT);
1734 }
1735
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001736 /**
1737 * Handle the action clicked in the "Add to home" dialog.
1738 */
1739 public void onClick(DialogInterface dialog, int which) {
1740 Resources res = getResources();
1741 cleanup();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001742
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001743 switch (which) {
1744 case AddAdapter.ITEM_SHORTCUT: {
1745 // Insert extra item to handle picking application
1746 Bundle bundle = new Bundle();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001747
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001748 ArrayList<String> shortcutNames = new ArrayList<String>();
1749 shortcutNames.add(res.getString(R.string.group_applications));
1750 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001751
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001752 ArrayList<ShortcutIconResource> shortcutIcons =
1753 new ArrayList<ShortcutIconResource>();
1754 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1755 R.drawable.ic_launcher_application));
1756 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001757
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001758 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1759 pickIntent.putExtra(Intent.EXTRA_INTENT,
1760 new Intent(Intent.ACTION_CREATE_SHORTCUT));
1761 pickIntent.putExtra(Intent.EXTRA_TITLE,
1762 getText(R.string.title_select_shortcut));
1763 pickIntent.putExtras(bundle);
1764
1765 startActivityForResult(pickIntent, REQUEST_PICK_SHORTCUT);
1766 break;
1767 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001768
Jeffrey Sharkeyc7fdae12009-03-24 20:41:22 -07001769 case AddAdapter.ITEM_APPWIDGET: {
1770 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId();
1771
1772 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
1773 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
1774 // add the search widget
1775 ArrayList<AppWidgetProviderInfo> customInfo =
1776 new ArrayList<AppWidgetProviderInfo>();
1777 AppWidgetProviderInfo info = new AppWidgetProviderInfo();
1778 info.provider = new ComponentName(getPackageName(), "XXX.YYY");
1779 info.label = getString(R.string.group_search);
1780 info.icon = R.drawable.ic_search_widget;
1781 customInfo.add(info);
1782 pickIntent.putParcelableArrayListExtra(
1783 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
1784 ArrayList<Bundle> customExtras = new ArrayList<Bundle>();
1785 Bundle b = new Bundle();
1786 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET);
1787 customExtras.add(b);
1788 pickIntent.putParcelableArrayListExtra(
1789 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
1790 // start the pick activity
1791 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
1792 break;
1793 }
1794
1795 case AddAdapter.ITEM_LIVE_FOLDER: {
1796 // Insert extra item to handle inserting folder
1797 Bundle bundle = new Bundle();
1798
1799 ArrayList<String> shortcutNames = new ArrayList<String>();
1800 shortcutNames.add(res.getString(R.string.group_folder));
1801 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames);
1802
1803 ArrayList<ShortcutIconResource> shortcutIcons =
1804 new ArrayList<ShortcutIconResource>();
1805 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this,
1806 R.drawable.ic_launcher_folder));
1807 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons);
1808
1809 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
1810 pickIntent.putExtra(Intent.EXTRA_INTENT,
1811 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER));
1812 pickIntent.putExtra(Intent.EXTRA_TITLE,
1813 getText(R.string.title_select_live_folder));
1814 pickIntent.putExtras(bundle);
1815
1816 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER);
1817 break;
1818 }
1819
1820 case AddAdapter.ITEM_WALLPAPER: {
1821 startWallpaper();
1822 break;
1823 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001824 }
1825 }
1826 }
1827
1828 /**
1829 * Receives notifications when applications are added/removed.
1830 */
1831 private class ApplicationsIntentReceiver extends BroadcastReceiver {
1832 @Override
1833 public void onReceive(Context context, Intent intent) {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001834 final String action = intent.getAction();
1835 final String packageName = intent.getData().getSchemeSpecificPart();
1836 final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1837
1838 if (LauncherModel.DEBUG_LOADERS) {
1839 d(LauncherModel.LOG_TAG, "application intent received: " + action +
1840 ", replacing=" + replacing);
1841 d(LauncherModel.LOG_TAG, " --> " + intent.getData());
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001842 }
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001843
1844 if (!Intent.ACTION_PACKAGE_CHANGED.equals(action)) {
1845 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
1846 if (!replacing) {
1847 removeShortcutsForPackage(packageName);
1848 if (LauncherModel.DEBUG_LOADERS) {
1849 d(LauncherModel.LOG_TAG, " --> remove package");
1850 }
1851 sModel.removePackage(Launcher.this, packageName);
1852 }
1853 // else, we are replacing the package, so a PACKAGE_ADDED will be sent
1854 // later, we will update the package at this time
1855 } else {
1856 if (!replacing) {
1857 if (LauncherModel.DEBUG_LOADERS) {
1858 d(LauncherModel.LOG_TAG, " --> add package");
1859 }
1860 sModel.addPackage(Launcher.this, packageName);
1861 } else {
1862 if (LauncherModel.DEBUG_LOADERS) {
1863 d(LauncherModel.LOG_TAG, " --> update package " + packageName);
1864 }
1865 sModel.updatePackage(Launcher.this, packageName);
1866 updateShortcutsForPackage(packageName);
1867 }
1868 }
1869 removeDialog(DIALOG_CREATE_SHORTCUT);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001870 } else {
The Android Open Source Projectf96811c2009-03-18 17:39:48 -07001871 if (LauncherModel.DEBUG_LOADERS) {
1872 d(LauncherModel.LOG_TAG, " --> sync package " + packageName);
1873 }
1874 sModel.syncPackage(Launcher.this, packageName);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001875 }
1876 }
1877 }
1878
1879 /**
1880 * Receives notifications whenever the user favorites have changed.
1881 */
1882 private class FavoritesChangeObserver extends ContentObserver {
1883 public FavoritesChangeObserver() {
1884 super(new Handler());
1885 }
1886
1887 @Override
1888 public void onChange(boolean selfChange) {
1889 onFavoritesChanged();
1890 }
1891 }
1892
1893 /**
Jeffrey Sharkey2bbcae12009-03-31 14:37:57 -07001894 * Receives notifications when the {@link AppWidgetHost} has been reset,
1895 * usually only when the {@link LauncherProvider} database is first created.
1896 */
1897 private class AppWidgetResetObserver extends ContentObserver {
1898 public AppWidgetResetObserver() {
1899 super(new Handler());
1900 }
1901
1902 @Override
1903 public void onChange(boolean selfChange) {
1904 onAppWidgetReset();
1905 }
1906 }
1907
1908 /**
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001909 * Receives intents from other applications to change the wallpaper.
1910 */
1911 private static class WallpaperIntentReceiver extends BroadcastReceiver {
1912 private final Application mApplication;
1913 private WeakReference<Launcher> mLauncher;
1914
1915 WallpaperIntentReceiver(Application application, Launcher launcher) {
1916 mApplication = application;
1917 setLauncher(launcher);
1918 }
1919
1920 void setLauncher(Launcher launcher) {
1921 mLauncher = new WeakReference<Launcher>(launcher);
1922 }
1923
1924 @Override
1925 public void onReceive(Context context, Intent intent) {
1926 // Load the wallpaper from the ApplicationContext and store it locally
1927 // until the Launcher Activity is ready to use it
1928 final Drawable drawable = mApplication.getWallpaper();
1929 if (drawable instanceof BitmapDrawable) {
1930 sWallpaper = ((BitmapDrawable) drawable).getBitmap();
1931 } else {
1932 throw new IllegalStateException("The wallpaper must be a BitmapDrawable.");
1933 }
1934
1935 // If Launcher is alive, notify we have a new wallpaper
1936 if (mLauncher != null) {
1937 final Launcher launcher = mLauncher.get();
1938 if (launcher != null) {
1939 launcher.loadWallpaper();
1940 }
1941 }
1942 }
1943 }
1944
1945 private class DrawerManager implements SlidingDrawer.OnDrawerOpenListener,
1946 SlidingDrawer.OnDrawerCloseListener, SlidingDrawer.OnDrawerScrollListener {
1947 private boolean mOpen;
1948
1949 public void onDrawerOpened() {
1950 if (!mOpen) {
1951 mHandleIcon.reverseTransition(150);
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001952
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001953 final Rect bounds = mWorkspace.mDrawerBounds;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001954 offsetBoundsToDragLayer(bounds, mAllAppsGrid);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001955
1956 mOpen = true;
1957 }
1958 }
1959
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001960 private void offsetBoundsToDragLayer(Rect bounds, View view) {
1961 view.getDrawingRect(bounds);
1962
1963 while (view != mDragLayer) {
1964 bounds.offset(view.getLeft(), view.getTop());
1965 view = (View) view.getParent();
1966 }
1967 }
1968
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001969 public void onDrawerClosed() {
1970 if (mOpen) {
1971 mHandleIcon.reverseTransition(150);
1972 mWorkspace.mDrawerBounds.setEmpty();
1973 mOpen = false;
1974 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001975
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001976 mAllAppsGrid.setSelection(0);
1977 mAllAppsGrid.clearTextFilter();
1978 }
1979
1980 public void onScrollStarted() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001981 if (PROFILE_DRAWER) {
1982 android.os.Debug.startMethodTracing("/sdcard/launcher-drawer");
1983 }
1984
1985 mWorkspace.mDrawerContentWidth = mAllAppsGrid.getWidth();
1986 mWorkspace.mDrawerContentHeight = mAllAppsGrid.getHeight();
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001987 }
1988
1989 public void onScrollEnded() {
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001990 if (PROFILE_DRAWER) {
1991 android.os.Debug.stopMethodTracing();
1992 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001993 }
1994 }
1995
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001996 private static class DesktopBinder extends Handler implements MessageQueue.IdleHandler {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08001997 static final int MESSAGE_BIND_ITEMS = 0x1;
The Android Open Source Project7376fae2009-03-11 12:11:58 -07001998 static final int MESSAGE_BIND_APPWIDGETS = 0x2;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07001999
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002000 // Number of items to bind in every pass
2001 static final int ITEMS_COUNT = 6;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002002
2003 private final ArrayList<ItemInfo> mShortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002004 private final LinkedList<LauncherAppWidgetInfo> mAppWidgets;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002005 private final WeakReference<Launcher> mLauncher;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002006
Romain Guy829f56a2009-03-27 16:58:13 -07002007 public volatile boolean mTerminate = false;
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002008
2009 DesktopBinder(Launcher launcher, ArrayList<ItemInfo> shortcuts,
Romain Guy829f56a2009-03-27 16:58:13 -07002010 ArrayList<LauncherAppWidgetInfo> appWidgets) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002011
2012 mLauncher = new WeakReference<Launcher>(launcher);
2013 mShortcuts = shortcuts;
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002014
2015 // Sort widgets so active workspace is bound first
2016 final int currentScreen = launcher.mWorkspace.getCurrentScreen();
2017 final int size = appWidgets.size();
2018 mAppWidgets = new LinkedList<LauncherAppWidgetInfo>();
2019
2020 for (int i = 0; i < size; i++) {
2021 LauncherAppWidgetInfo appWidgetInfo = appWidgets.get(i);
2022 if (appWidgetInfo.screen == currentScreen) {
2023 mAppWidgets.addFirst(appWidgetInfo);
2024 } else {
2025 mAppWidgets.addLast(appWidgetInfo);
2026 }
2027 }
2028 }
2029
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002030 public void startBindingItems() {
2031 obtainMessage(MESSAGE_BIND_ITEMS, 0, mShortcuts.size()).sendToTarget();
2032 }
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002033
Jeffrey Sharkey2d132af2009-03-24 21:21:09 -07002034 public void startBindingAppWidgetsWhenIdle() {
2035 // Ask for notification when message queue becomes idle
2036 final MessageQueue messageQueue = Looper.myQueue();
2037 messageQueue.addIdleHandler(this);
2038 }
2039
2040 public boolean queueIdle() {
2041 // Queue is idle, so start binding items
2042 startBindingAppWidgets();
2043 return false;
2044 }
2045
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002046 public void startBindingAppWidgets() {
2047 obtainMessage(MESSAGE_BIND_APPWIDGETS).sendToTarget();
2048 }
2049
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002050 @Override
2051 public void handleMessage(Message msg) {
2052 Launcher launcher = mLauncher.get();
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002053 if (launcher == null || mTerminate) {
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002054 return;
2055 }
2056
2057 switch (msg.what) {
2058 case MESSAGE_BIND_ITEMS: {
2059 launcher.bindItems(this, mShortcuts, msg.arg1, msg.arg2);
2060 break;
2061 }
The Android Open Source Project7376fae2009-03-11 12:11:58 -07002062 case MESSAGE_BIND_APPWIDGETS: {
Jeffrey Sharkey99c87582009-03-24 17:59:43 -07002063 launcher.bindAppWidgets(this, mAppWidgets);
The Android Open Source Project31dd5032009-03-03 19:32:27 -08002064 break;
2065 }
2066 }
2067 }
2068 }
2069}