Launcher.java revision 14f122bf847e50a3e7730ccbe57abc25d086a01b
1/* 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.launcher2; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.Dialog; 22import android.app.ISearchManager; 23import android.app.SearchManager; 24import android.app.StatusBarManager; 25import android.app.WallpaperManager; 26import android.content.ActivityNotFoundException; 27import android.content.BroadcastReceiver; 28import android.content.ComponentName; 29import android.content.ContentResolver; 30import android.content.Context; 31import android.content.DialogInterface; 32import android.content.Intent; 33import android.content.Intent.ShortcutIconResource; 34import android.content.IntentFilter; 35import android.content.pm.ActivityInfo; 36import android.content.pm.PackageManager; 37import android.content.pm.PackageManager.NameNotFoundException; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.database.ContentObserver; 41import android.graphics.Bitmap; 42import android.graphics.Rect; 43import android.graphics.Canvas; 44import android.graphics.drawable.Drawable; 45import android.graphics.drawable.ColorDrawable; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.Parcelable; 49import android.os.RemoteException; 50import android.os.ServiceManager; 51import android.os.SystemProperties; 52import android.provider.LiveFolders; 53import android.text.Selection; 54import android.text.SpannableStringBuilder; 55import android.text.TextUtils; 56import android.text.method.TextKeyListener; 57import android.util.Log; 58import android.view.Display; 59import android.view.HapticFeedbackConstants; 60import android.view.KeyEvent; 61import android.view.LayoutInflater; 62import android.view.Menu; 63import android.view.MenuItem; 64import android.view.View; 65import android.view.ViewGroup; 66import android.view.View.OnLongClickListener; 67import android.view.inputmethod.InputMethodManager; 68import android.widget.EditText; 69import android.widget.TextView; 70import android.widget.Toast; 71import android.widget.ImageView; 72import android.widget.PopupWindow; 73import android.widget.LinearLayout; 74import android.appwidget.AppWidgetManager; 75import android.appwidget.AppWidgetProviderInfo; 76 77import java.util.ArrayList; 78import java.util.HashMap; 79import java.io.DataOutputStream; 80import java.io.FileNotFoundException; 81import java.io.IOException; 82import java.io.DataInputStream; 83 84/** 85 * Default launcher application. 86 */ 87public final class Launcher extends Activity 88 implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks { 89 static final String TAG = "Launcher"; 90 static final boolean LOGD = false; 91 92 static final boolean PROFILE_STARTUP = false; 93 static final boolean PROFILE_ROTATE = false; 94 static final boolean DEBUG_USER_INTERFACE = false; 95 96 private static final int WALLPAPER_SCREENS_SPAN = 2; 97 98 private static final int MENU_GROUP_ADD = 1; 99 private static final int MENU_ADD = Menu.FIRST + 1; 100 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1; 101 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1; 102 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1; 103 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1; 104 105 private static final int REQUEST_CREATE_SHORTCUT = 1; 106 private static final int REQUEST_CREATE_LIVE_FOLDER = 4; 107 private static final int REQUEST_CREATE_APPWIDGET = 5; 108 private static final int REQUEST_PICK_APPLICATION = 6; 109 private static final int REQUEST_PICK_SHORTCUT = 7; 110 private static final int REQUEST_PICK_LIVE_FOLDER = 8; 111 private static final int REQUEST_PICK_APPWIDGET = 9; 112 private static final int REQUEST_PICK_WALLPAPER = 10; 113 114 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; 115 116 static final String EXTRA_CUSTOM_WIDGET = "custom_widget"; 117 static final String SEARCH_WIDGET = "search_widget"; 118 119 static final int SCREEN_COUNT = 5; 120 static final int DEFAULT_SCREEN = 2; 121 static final int NUMBER_CELLS_X = 4; 122 static final int NUMBER_CELLS_Y = 4; 123 124 static final int DIALOG_CREATE_SHORTCUT = 1; 125 static final int DIALOG_RENAME_FOLDER = 2; 126 127 private static final String PREFERENCES = "launcher.preferences"; 128 129 // Type: int 130 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; 131 // Type: boolean 132 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder"; 133 // Type: long 134 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder"; 135 // Type: int 136 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; 137 // Type: int 138 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX"; 139 // Type: int 140 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY"; 141 // Type: int 142 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX"; 143 // Type: int 144 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY"; 145 // Type: int 146 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX"; 147 // Type: int 148 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY"; 149 // Type: int[] 150 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells"; 151 // Type: boolean 152 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; 153 // Type: long 154 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; 155 156 static final int APPWIDGET_HOST_ID = 1024; 157 158 private static final Object sLock = new Object(); 159 private static int sScreen = DEFAULT_SCREEN; 160 161 private final BroadcastReceiver mCloseSystemDialogsReceiver 162 = new CloseSystemDialogsIntentReceiver(); 163 private final ContentObserver mWidgetObserver = new AppWidgetResetObserver(); 164 165 private LayoutInflater mInflater; 166 167 private DragController mDragController; 168 private Workspace mWorkspace; 169 170 private AppWidgetManager mAppWidgetManager; 171 private LauncherAppWidgetHost mAppWidgetHost; 172 173 private CellLayout.CellInfo mAddItemCellInfo; 174 private CellLayout.CellInfo mMenuAddInfo; 175 private final int[] mCellCoordinates = new int[2]; 176 private FolderInfo mFolderInfo; 177 178 private DeleteZone mDeleteZone; 179 private HandleView mHandleView; 180 private AllAppsView mAllAppsGrid; 181 182 private Bundle mSavedState; 183 184 private SpannableStringBuilder mDefaultKeySsb = null; 185 186 private boolean mIsNewIntent; 187 188 private boolean mWorkspaceLoading = true; 189 190 private boolean mRestoring; 191 private boolean mWaitingForResult; 192 193 private Bundle mSavedInstanceState; 194 195 private LauncherModel mModel; 196 197 private ArrayList<ItemInfo> mDesktopItems = new ArrayList<ItemInfo>(); 198 private static HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); 199 200 private ImageView mPreviousView; 201 private ImageView mNextView; 202 203 @Override 204 protected void onCreate(Bundle savedInstanceState) { 205 super.onCreate(savedInstanceState); 206 207 mModel = ((LauncherApplication)getApplication()).setLauncher(this); 208 mDragController = new DragController(this); 209 mInflater = getLayoutInflater(); 210 211 IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 212 registerReceiver(mCloseSystemDialogsReceiver, filter); 213 214 mAppWidgetManager = AppWidgetManager.getInstance(this); 215 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); 216 mAppWidgetHost.startListening(); 217 218 if (PROFILE_STARTUP) { 219 android.os.Debug.startMethodTracing("/sdcard/launcher"); 220 } 221 222 checkForLocaleChange(); 223 setWallpaperDimension(); 224 225 setContentView(R.layout.launcher); 226 setupViews(); 227 228 registerContentObservers(); 229 230 lockAllApps(); 231 232 mSavedState = savedInstanceState; 233 restoreState(mSavedState); 234 235 if (PROFILE_STARTUP) { 236 android.os.Debug.stopMethodTracing(); 237 } 238 239 // We have a new AllAppsView, we need to re-bind everything, and it could have 240 // changed in our absence. 241 mModel.setAllAppsDirty(); 242 mModel.setWorkspaceDirty(); 243 244 if (!mRestoring) { 245 mModel.startLoader(this, true); 246 } 247 248 // For handling default keys 249 mDefaultKeySsb = new SpannableStringBuilder(); 250 Selection.setSelection(mDefaultKeySsb, 0); 251 } 252 253 private void checkForLocaleChange() { 254 final LocaleConfiguration localeConfiguration = new LocaleConfiguration(); 255 readConfiguration(this, localeConfiguration); 256 257 final Configuration configuration = getResources().getConfiguration(); 258 259 final String previousLocale = localeConfiguration.locale; 260 final String locale = configuration.locale.toString(); 261 262 final int previousMcc = localeConfiguration.mcc; 263 final int mcc = configuration.mcc; 264 265 final int previousMnc = localeConfiguration.mnc; 266 final int mnc = configuration.mnc; 267 268 boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; 269 270 if (localeChanged) { 271 localeConfiguration.locale = locale; 272 localeConfiguration.mcc = mcc; 273 localeConfiguration.mnc = mnc; 274 275 writeConfiguration(this, localeConfiguration); 276 AppInfoCache.flush(); 277 } 278 } 279 280 private static class LocaleConfiguration { 281 public String locale; 282 public int mcc = -1; 283 public int mnc = -1; 284 } 285 286 private static void readConfiguration(Context context, LocaleConfiguration configuration) { 287 DataInputStream in = null; 288 try { 289 in = new DataInputStream(context.openFileInput(PREFERENCES)); 290 configuration.locale = in.readUTF(); 291 configuration.mcc = in.readInt(); 292 configuration.mnc = in.readInt(); 293 } catch (FileNotFoundException e) { 294 // Ignore 295 } catch (IOException e) { 296 // Ignore 297 } finally { 298 if (in != null) { 299 try { 300 in.close(); 301 } catch (IOException e) { 302 // Ignore 303 } 304 } 305 } 306 } 307 308 private static void writeConfiguration(Context context, LocaleConfiguration configuration) { 309 DataOutputStream out = null; 310 try { 311 out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); 312 out.writeUTF(configuration.locale); 313 out.writeInt(configuration.mcc); 314 out.writeInt(configuration.mnc); 315 out.flush(); 316 } catch (FileNotFoundException e) { 317 // Ignore 318 } catch (IOException e) { 319 //noinspection ResultOfMethodCallIgnored 320 context.getFileStreamPath(PREFERENCES).delete(); 321 } finally { 322 if (out != null) { 323 try { 324 out.close(); 325 } catch (IOException e) { 326 // Ignore 327 } 328 } 329 } 330 } 331 332 static int getScreen() { 333 synchronized (sLock) { 334 return sScreen; 335 } 336 } 337 338 static void setScreen(int screen) { 339 synchronized (sLock) { 340 sScreen = screen; 341 } 342 } 343 344 private void setWallpaperDimension() { 345 WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE); 346 347 Display display = getWindowManager().getDefaultDisplay(); 348 boolean isPortrait = display.getWidth() < display.getHeight(); 349 350 final int width = isPortrait ? display.getWidth() : display.getHeight(); 351 final int height = isPortrait ? display.getHeight() : display.getWidth(); 352 wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height); 353 } 354 355 @Override 356 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 357 mWaitingForResult = false; 358 359 // The pattern used here is that a user PICKs a specific application, 360 // which, depending on the target, might need to CREATE the actual target. 361 362 // For example, the user would PICK_SHORTCUT for "Music playlist", and we 363 // launch over to the Music app to actually CREATE_SHORTCUT. 364 365 if (resultCode == RESULT_OK && mAddItemCellInfo != null) { 366 switch (requestCode) { 367 case REQUEST_PICK_APPLICATION: 368 completeAddApplication(this, data, mAddItemCellInfo); 369 break; 370 case REQUEST_PICK_SHORTCUT: 371 processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT); 372 break; 373 case REQUEST_CREATE_SHORTCUT: 374 completeAddShortcut(data, mAddItemCellInfo); 375 break; 376 case REQUEST_PICK_LIVE_FOLDER: 377 addLiveFolder(data); 378 break; 379 case REQUEST_CREATE_LIVE_FOLDER: 380 completeAddLiveFolder(data, mAddItemCellInfo); 381 break; 382 case REQUEST_PICK_APPWIDGET: 383 addAppWidget(data); 384 break; 385 case REQUEST_CREATE_APPWIDGET: 386 completeAddAppWidget(data, mAddItemCellInfo); 387 break; 388 case REQUEST_PICK_WALLPAPER: 389 // We just wanted the activity result here so we can clear mWaitingForResult 390 break; 391 } 392 } else if ((requestCode == REQUEST_PICK_APPWIDGET || 393 requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED && 394 data != null) { 395 // Clean up the appWidgetId if we canceled 396 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 397 if (appWidgetId != -1) { 398 mAppWidgetHost.deleteAppWidgetId(appWidgetId); 399 } 400 } 401 } 402 403 @Override 404 protected void onResume() { 405 super.onResume(); 406 407 if (mRestoring) { 408 mWorkspaceLoading = true; 409 mModel.startLoader(this, true); 410 mRestoring = false; 411 } 412 413 // If this was a new intent (i.e., the mIsNewIntent flag got set to true by 414 // onNewIntent), then close the search dialog if needed, because it probably 415 // came from the user pressing 'home' (rather than, for example, pressing 'back'). 416 if (mIsNewIntent) { 417 // Post to a handler so that this happens after the search dialog tries to open 418 // itself again. 419 mWorkspace.post(new Runnable() { 420 public void run() { 421 ISearchManager searchManagerService = ISearchManager.Stub.asInterface( 422 ServiceManager.getService(Context.SEARCH_SERVICE)); 423 try { 424 searchManagerService.stopSearch(); 425 } catch (RemoteException e) { 426 Log.e(TAG, "error stopping search", e); 427 } 428 } 429 }); 430 } 431 432 mIsNewIntent = false; 433 } 434 435 @Override 436 protected void onPause() { 437 super.onPause(); 438 dismissPreview(mPreviousView); 439 dismissPreview(mNextView); 440 mDragController.cancelDrag(); 441 } 442 443 @Override 444 public Object onRetainNonConfigurationInstance() { 445 // Flag the loader to stop early before switching 446 mModel.stopLoader(); 447 448 if (PROFILE_ROTATE) { 449 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate"); 450 } 451 return null; 452 } 453 454 private boolean acceptFilter() { 455 final InputMethodManager inputManager = (InputMethodManager) 456 getSystemService(Context.INPUT_METHOD_SERVICE); 457 return !inputManager.isFullscreenMode(); 458 } 459 460 @Override 461 public boolean onKeyDown(int keyCode, KeyEvent event) { 462 boolean handled = super.onKeyDown(keyCode, event); 463 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) { 464 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, 465 keyCode, event); 466 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { 467 // something usable has been typed - start a search 468 // the typed text will be retrieved and cleared by 469 // showSearchDialog() 470 // If there are multiple keystrokes before the search dialog takes focus, 471 // onSearchRequested() will be called for every keystroke, 472 // but it is idempotent, so it's fine. 473 return onSearchRequested(); 474 } 475 } 476 477 return handled; 478 } 479 480 private String getTypedText() { 481 return mDefaultKeySsb.toString(); 482 } 483 484 private void clearTypedText() { 485 mDefaultKeySsb.clear(); 486 mDefaultKeySsb.clearSpans(); 487 Selection.setSelection(mDefaultKeySsb, 0); 488 } 489 490 /** 491 * Restores the previous state, if it exists. 492 * 493 * @param savedState The previous state. 494 */ 495 private void restoreState(Bundle savedState) { 496 if (savedState == null) { 497 return; 498 } 499 500 final boolean allApps = savedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false); 501 if (allApps) { 502 showAllApps(false); 503 } 504 505 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); 506 if (currentScreen > -1) { 507 mWorkspace.setCurrentScreen(currentScreen); 508 } 509 510 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); 511 if (addScreen > -1) { 512 mAddItemCellInfo = new CellLayout.CellInfo(); 513 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo; 514 addItemCellInfo.valid = true; 515 addItemCellInfo.screen = addScreen; 516 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); 517 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); 518 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X); 519 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y); 520 addItemCellInfo.findVacantCellsFromOccupied( 521 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS), 522 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X), 523 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y)); 524 mRestoring = true; 525 } 526 527 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); 528 if (renameFolder) { 529 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); 530 mFolderInfo = mModel.getFolderById(this, mFolders, id); 531 mRestoring = true; 532 } 533 } 534 535 /** 536 * Finds all the views we need and configure them properly. 537 */ 538 private void setupViews() { 539 DragController dragController = mDragController; 540 541 DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer); 542 dragLayer.setDragController(dragController); 543 544 mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view); 545 mAllAppsGrid.setLauncher(this); 546 mAllAppsGrid.setDragController(dragController); 547 mAllAppsGrid.setWillNotDraw(false); // We don't want a hole punched in our window. 548 // Manage focusability manually since this thing is always visible 549 mAllAppsGrid.setFocusable(false); 550 551 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace); 552 final Workspace workspace = mWorkspace; 553 554 DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone); 555 mDeleteZone = deleteZone; 556 557 mHandleView = (HandleView) findViewById(R.id.all_apps_button); 558 mHandleView.setLauncher(this); 559 mHandleView.setOnClickListener(this); 560 561 mPreviousView = (ImageView) dragLayer.findViewById(R.id.previous_screen); 562 mNextView = (ImageView) dragLayer.findViewById(R.id.next_screen); 563 564 Drawable previous = mPreviousView.getDrawable(); 565 Drawable next = mNextView.getDrawable(); 566 mWorkspace.setIndicators(previous, next); 567 568 mPreviousView.setHapticFeedbackEnabled(false); 569 mPreviousView.setOnLongClickListener(this); 570 mNextView.setHapticFeedbackEnabled(false); 571 mNextView.setOnLongClickListener(this); 572 573 workspace.setOnLongClickListener(this); 574 workspace.setDragController(dragController); 575 workspace.setLauncher(this); 576 577 deleteZone.setLauncher(this); 578 deleteZone.setDragController(dragController); 579 deleteZone.setHandle(mHandleView); 580 581 dragController.setDragScoller(workspace); 582 dragController.setDragListener(deleteZone); 583 dragController.setScrollView(dragLayer); 584 585 // The order here is bottom to top. 586 dragController.addDropTarget(workspace); 587 dragController.addDropTarget(deleteZone); 588 } 589 590 @SuppressWarnings({"UnusedDeclaration"}) 591 public void previousScreen(View v) { 592 if (!isAllAppsVisible()) { 593 mWorkspace.scrollLeft(); 594 } 595 } 596 597 @SuppressWarnings({"UnusedDeclaration"}) 598 public void nextScreen(View v) { 599 if (!isAllAppsVisible()) { 600 mWorkspace.scrollRight(); 601 } 602 } 603 604 /** 605 * Creates a view representing a shortcut. 606 * 607 * @param info The data structure describing the shortcut. 608 * 609 * @return A View inflated from R.layout.application. 610 */ 611 View createShortcut(ApplicationInfo info) { 612 return createShortcut(R.layout.application, 613 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info); 614 } 615 616 /** 617 * Creates a view representing a shortcut inflated from the specified resource. 618 * 619 * @param layoutResId The id of the XML layout used to create the shortcut. 620 * @param parent The group the shortcut belongs to. 621 * @param info The data structure describing the shortcut. 622 * 623 * @return A View inflated from layoutResId. 624 */ 625 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) { 626 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false); 627 628 if (info.icon == null) { 629 info.icon = AppInfoCache.getIconDrawable(getPackageManager(), info); 630 } 631 if (!info.filtered) { 632 info.icon = Utilities.createIconThumbnail(info.icon, this); 633 info.filtered = true; 634 } 635 636 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null); 637 favorite.setText(info.title); 638 favorite.setTag(info); 639 favorite.setOnClickListener(this); 640 641 return favorite; 642 } 643 644 /** 645 * Add an application shortcut to the workspace. 646 * 647 * @param data The intent describing the application. 648 * @param cellInfo The position on screen where to create the shortcut. 649 */ 650 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) { 651 cellInfo.screen = mWorkspace.getCurrentScreen(); 652 if (!findSingleSlot(cellInfo)) return; 653 654 final ApplicationInfo info = infoFromApplicationIntent(context, data); 655 if (info != null) { 656 mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked()); 657 } 658 } 659 660 private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) { 661 ComponentName component = data.getComponent(); 662 PackageManager packageManager = context.getPackageManager(); 663 ActivityInfo activityInfo = null; 664 try { 665 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */); 666 } catch (NameNotFoundException e) { 667 Log.e(TAG, "Couldn't find ActivityInfo for selected application", e); 668 } 669 670 if (activityInfo != null) { 671 ApplicationInfo itemInfo = new ApplicationInfo(); 672 673 itemInfo.title = activityInfo.loadLabel(packageManager); 674 if (itemInfo.title == null) { 675 itemInfo.title = activityInfo.name; 676 } 677 678 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK | 679 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 680 itemInfo.icon = activityInfo.loadIcon(packageManager); 681 itemInfo.container = ItemInfo.NO_ID; 682 683 return itemInfo; 684 } 685 686 return null; 687 } 688 689 /** 690 * Add a shortcut to the workspace. 691 * 692 * @param data The intent describing the shortcut. 693 * @param cellInfo The position on screen where to create the shortcut. 694 */ 695 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) { 696 cellInfo.screen = mWorkspace.getCurrentScreen(); 697 if (!findSingleSlot(cellInfo)) return; 698 699 final ApplicationInfo info = addShortcut(this, data, cellInfo, false); 700 701 if (!mRestoring) { 702 final View view = createShortcut(info); 703 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, 704 isWorkspaceLocked()); 705 } 706 } 707 708 709 /** 710 * Add a widget to the workspace. 711 * 712 * @param data The intent describing the appWidgetId. 713 * @param cellInfo The position on screen where to create the widget. 714 */ 715 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) { 716 Bundle extras = data.getExtras(); 717 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 718 719 if (LOGD) Log.d(TAG, "dumping extras content=" + extras.toString()); 720 721 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 722 723 // Calculate the grid spans needed to fit this widget 724 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen); 725 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight); 726 727 // Try finding open space on Launcher screen 728 final int[] xy = mCellCoordinates; 729 if (!findSlot(cellInfo, xy, spans[0], spans[1])) { 730 if (appWidgetId != -1) mAppWidgetHost.deleteAppWidgetId(appWidgetId); 731 return; 732 } 733 734 // Build Launcher-specific widget info and save to database 735 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId); 736 launcherInfo.spanX = spans[0]; 737 launcherInfo.spanY = spans[1]; 738 739 LauncherModel.addItemToDatabase(this, launcherInfo, 740 LauncherSettings.Favorites.CONTAINER_DESKTOP, 741 mWorkspace.getCurrentScreen(), xy[0], xy[1], false); 742 743 if (!mRestoring) { 744 mDesktopItems.add(launcherInfo); 745 746 // Perform actual inflation because we're live 747 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 748 749 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); 750 launcherInfo.hostView.setTag(launcherInfo); 751 752 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1], 753 launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); 754 } 755 } 756 757 public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { 758 mDesktopItems.remove(launcherInfo); 759 launcherInfo.hostView = null; 760 } 761 762 public LauncherAppWidgetHost getAppWidgetHost() { 763 return mAppWidgetHost; 764 } 765 766 static ApplicationInfo addShortcut(Context context, Intent data, 767 CellLayout.CellInfo cellInfo, boolean notify) { 768 769 final ApplicationInfo info = infoFromShortcutIntent(context, data); 770 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, 771 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); 772 773 return info; 774 } 775 776 private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) { 777 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); 778 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 779 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); 780 781 Drawable icon = null; 782 boolean filtered = false; 783 boolean customIcon = false; 784 ShortcutIconResource iconResource = null; 785 786 if (bitmap != null) { 787 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context)); 788 filtered = true; 789 customIcon = true; 790 } else { 791 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); 792 if (extra != null && extra instanceof ShortcutIconResource) { 793 try { 794 iconResource = (ShortcutIconResource) extra; 795 final PackageManager packageManager = context.getPackageManager(); 796 Resources resources = packageManager.getResourcesForApplication( 797 iconResource.packageName); 798 final int id = resources.getIdentifier(iconResource.resourceName, null, null); 799 icon = resources.getDrawable(id); 800 } catch (Exception e) { 801 Log.w(TAG, "Could not load shortcut icon: " + extra); 802 } 803 } 804 } 805 806 if (icon == null) { 807 icon = context.getPackageManager().getDefaultActivityIcon(); 808 } 809 810 final ApplicationInfo info = new ApplicationInfo(); 811 info.icon = icon; 812 info.filtered = filtered; 813 info.title = name; 814 info.intent = intent; 815 info.customIcon = customIcon; 816 info.iconResource = iconResource; 817 818 return info; 819 } 820 821 void closeSystemDialogs() { 822 closeAllApps(true); 823 getWindow().closeAllPanels(); 824 825 try { 826 dismissDialog(DIALOG_CREATE_SHORTCUT); 827 // Unlock the workspace if the dialog was showing 828 } catch (Exception e) { 829 // An exception is thrown if the dialog is not visible, which is fine 830 } 831 832 try { 833 dismissDialog(DIALOG_RENAME_FOLDER); 834 // Unlock the workspace if the dialog was showing 835 } catch (Exception e) { 836 // An exception is thrown if the dialog is not visible, which is fine 837 } 838 839 // Whatever we were doing is hereby canceled. 840 mWaitingForResult = false; 841 } 842 843 @Override 844 protected void onNewIntent(Intent intent) { 845 super.onNewIntent(intent); 846 847 // Close the menu 848 if (Intent.ACTION_MAIN.equals(intent.getAction())) { 849 // also will cancel mWaitingForResult. 850 closeSystemDialogs(); 851 852 // Set this flag so that onResume knows to close the search dialog if it's open, 853 // because this was a new intent (thus a press of 'home' or some such) rather than 854 // for example onResume being called when the user pressed the 'back' button. 855 mIsNewIntent = true; 856 857 boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) 858 != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 859 boolean allAppsVisible = isAllAppsVisible(); 860 if (!mWorkspace.isDefaultScreenShowing()) { 861 mWorkspace.moveToDefaultScreen(alreadyOnHome && !allAppsVisible); 862 } 863 closeAllApps(alreadyOnHome && allAppsVisible); 864 865 final View v = getWindow().peekDecorView(); 866 if (v != null && v.getWindowToken() != null) { 867 InputMethodManager imm = (InputMethodManager)getSystemService( 868 INPUT_METHOD_SERVICE); 869 imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 870 } 871 } 872 } 873 874 @Override 875 protected void onRestoreInstanceState(Bundle savedInstanceState) { 876 // Do not call super here 877 mSavedInstanceState = savedInstanceState; 878 } 879 880 @Override 881 protected void onSaveInstanceState(Bundle outState) { 882 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentScreen()); 883 884 final ArrayList<Folder> folders = mWorkspace.getOpenFolders(); 885 if (folders.size() > 0) { 886 final int count = folders.size(); 887 long[] ids = new long[count]; 888 for (int i = 0; i < count; i++) { 889 final FolderInfo info = folders.get(i).getInfo(); 890 ids[i] = info.id; 891 } 892 outState.putLongArray(RUNTIME_STATE_USER_FOLDERS, ids); 893 } else { 894 super.onSaveInstanceState(outState); 895 } 896 897 // TODO should not do this if the drawer is currently closing. 898 if (isAllAppsVisible()) { 899 outState.putBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, true); 900 } 901 902 if (mAddItemCellInfo != null && mAddItemCellInfo.valid && mWaitingForResult) { 903 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo; 904 final CellLayout layout = (CellLayout) mWorkspace.getChildAt(addItemCellInfo.screen); 905 906 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, addItemCellInfo.screen); 907 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, addItemCellInfo.cellX); 908 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, addItemCellInfo.cellY); 909 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_X, addItemCellInfo.spanX); 910 outState.putInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y, addItemCellInfo.spanY); 911 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_X, layout.getCountX()); 912 outState.putInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y, layout.getCountY()); 913 outState.putBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS, 914 layout.getOccupiedCells()); 915 } 916 917 if (mFolderInfo != null && mWaitingForResult) { 918 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true); 919 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id); 920 } 921 } 922 923 @Override 924 public void onDestroy() { 925 super.onDestroy(); 926 927 try { 928 mAppWidgetHost.stopListening(); 929 } catch (NullPointerException ex) { 930 Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex); 931 } 932 933 TextKeyListener.getInstance().release(); 934 935 mModel.stopLoader(); 936 937 unbindDesktopItems(); 938 AppInfoCache.unbindDrawables(); 939 940 getContentResolver().unregisterContentObserver(mWidgetObserver); 941 942 dismissPreview(mPreviousView); 943 dismissPreview(mNextView); 944 945 unregisterReceiver(mCloseSystemDialogsReceiver); 946 } 947 948 @Override 949 public void startActivityForResult(Intent intent, int requestCode) { 950 if (requestCode >= 0) mWaitingForResult = true; 951 super.startActivityForResult(intent, requestCode); 952 } 953 954 @Override 955 public void startSearch(String initialQuery, boolean selectInitialQuery, 956 Bundle appSearchData, boolean globalSearch) { 957 958 closeAllApps(true); 959 960 // Slide the search widget to the top, if it's on the current screen, 961 // otherwise show the search dialog immediately. 962 Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); 963 if (searchWidget == null) { 964 showSearchDialog(initialQuery, selectInitialQuery, appSearchData, globalSearch); 965 } else { 966 searchWidget.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); 967 // show the currently typed text in the search widget while sliding 968 searchWidget.setQuery(getTypedText()); 969 } 970 } 971 972 /** 973 * Show the search dialog immediately, without changing the search widget. 974 * 975 * @see Activity#startSearch(String, boolean, android.os.Bundle, boolean) 976 */ 977 void showSearchDialog(String initialQuery, boolean selectInitialQuery, 978 Bundle appSearchData, boolean globalSearch) { 979 980 if (initialQuery == null) { 981 // Use any text typed in the launcher as the initial query 982 initialQuery = getTypedText(); 983 clearTypedText(); 984 } 985 if (appSearchData == null) { 986 appSearchData = new Bundle(); 987 appSearchData.putString(SearchManager.SOURCE, "launcher-search"); 988 } 989 990 final SearchManager searchManager = 991 (SearchManager) getSystemService(Context.SEARCH_SERVICE); 992 993 final Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); 994 if (searchWidget != null) { 995 // This gets called when the user leaves the search dialog to go back to 996 // the Launcher. 997 searchManager.setOnCancelListener(new SearchManager.OnCancelListener() { 998 public void onCancel() { 999 searchManager.setOnCancelListener(null); 1000 stopSearch(); 1001 } 1002 }); 1003 } 1004 1005 searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), 1006 appSearchData, globalSearch); 1007 } 1008 1009 /** 1010 * Cancel search dialog if it is open. 1011 */ 1012 void stopSearch() { 1013 // Close search dialog 1014 SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 1015 searchManager.stopSearch(); 1016 // Restore search widget to its normal position 1017 Search searchWidget = mWorkspace.findSearchWidgetOnCurrentScreen(); 1018 if (searchWidget != null) { 1019 searchWidget.stopSearch(false); 1020 } 1021 } 1022 1023 @Override 1024 public boolean onCreateOptionsMenu(Menu menu) { 1025 if (isWorkspaceLocked()) { 1026 return false; 1027 } 1028 1029 super.onCreateOptionsMenu(menu); 1030 menu.add(MENU_GROUP_ADD, MENU_ADD, 0, R.string.menu_add) 1031 .setIcon(android.R.drawable.ic_menu_add) 1032 .setAlphabeticShortcut('A'); 1033 menu.add(0, MENU_WALLPAPER_SETTINGS, 0, R.string.menu_wallpaper) 1034 .setIcon(android.R.drawable.ic_menu_gallery) 1035 .setAlphabeticShortcut('W'); 1036 menu.add(0, MENU_SEARCH, 0, R.string.menu_search) 1037 .setIcon(android.R.drawable.ic_search_category_default) 1038 .setAlphabeticShortcut(SearchManager.MENU_KEY); 1039 menu.add(0, MENU_NOTIFICATIONS, 0, R.string.menu_notifications) 1040 .setIcon(com.android.internal.R.drawable.ic_menu_notifications) 1041 .setAlphabeticShortcut('N'); 1042 1043 final Intent settings = new Intent(android.provider.Settings.ACTION_SETTINGS); 1044 settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 1045 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 1046 1047 menu.add(0, MENU_SETTINGS, 0, R.string.menu_settings) 1048 .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('P') 1049 .setIntent(settings); 1050 1051 return true; 1052 } 1053 1054 @Override 1055 public boolean onPrepareOptionsMenu(Menu menu) { 1056 super.onPrepareOptionsMenu(menu); 1057 1058 mMenuAddInfo = mWorkspace.findAllVacantCells(null); 1059 menu.setGroupEnabled(MENU_GROUP_ADD, mMenuAddInfo != null && mMenuAddInfo.valid); 1060 1061 return true; 1062 } 1063 1064 @Override 1065 public boolean onOptionsItemSelected(MenuItem item) { 1066 switch (item.getItemId()) { 1067 case MENU_ADD: 1068 addItems(); 1069 return true; 1070 case MENU_WALLPAPER_SETTINGS: 1071 startWallpaper(); 1072 return true; 1073 case MENU_SEARCH: 1074 onSearchRequested(); 1075 return true; 1076 case MENU_NOTIFICATIONS: 1077 showNotifications(); 1078 return true; 1079 } 1080 1081 return super.onOptionsItemSelected(item); 1082 } 1083 1084 /** 1085 * Indicates that we want global search for this activity by setting the globalSearch 1086 * argument for {@link #startSearch} to true. 1087 */ 1088 1089 @Override 1090 public boolean onSearchRequested() { 1091 startSearch(null, false, null, true); 1092 return true; 1093 } 1094 1095 public boolean isWorkspaceLocked() { 1096 return mWorkspaceLoading || mWaitingForResult; 1097 } 1098 1099 private void addItems() { 1100 closeAllApps(true); 1101 showAddDialog(mMenuAddInfo); 1102 } 1103 1104 void addAppWidget(Intent data) { 1105 // TODO: catch bad widget exception when sent 1106 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 1107 1108 String customWidget = data.getStringExtra(EXTRA_CUSTOM_WIDGET); 1109 if (SEARCH_WIDGET.equals(customWidget)) { 1110 // We don't need this any more, since this isn't a real app widget. 1111 mAppWidgetHost.deleteAppWidgetId(appWidgetId); 1112 // add the search widget 1113 addSearch(); 1114 } else { 1115 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 1116 1117 if (appWidget.configure != null) { 1118 // Launch over to configure widget, if needed 1119 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); 1120 intent.setComponent(appWidget.configure); 1121 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 1122 1123 startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); 1124 } else { 1125 // Otherwise just add it 1126 onActivityResult(REQUEST_CREATE_APPWIDGET, Activity.RESULT_OK, data); 1127 } 1128 } 1129 } 1130 1131 void addSearch() { 1132 final Widget info = Widget.makeSearch(); 1133 final CellLayout.CellInfo cellInfo = mAddItemCellInfo; 1134 1135 final int[] xy = mCellCoordinates; 1136 final int spanX = info.spanX; 1137 final int spanY = info.spanY; 1138 1139 if (!findSlot(cellInfo, xy, spanX, spanY)) return; 1140 1141 LauncherModel.addItemToDatabase(this, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, 1142 mWorkspace.getCurrentScreen(), xy[0], xy[1], false); 1143 1144 final View view = mInflater.inflate(info.layoutResource, null); 1145 view.setTag(info); 1146 Search search = (Search) view.findViewById(R.id.widget_search); 1147 search.setLauncher(this); 1148 1149 mWorkspace.addInCurrentScreen(view, xy[0], xy[1], info.spanX, spanY); 1150 } 1151 1152 void processShortcut(Intent intent, int requestCodeApplication, int requestCodeShortcut) { 1153 // Handle case where user selected "Applications" 1154 String applicationName = getResources().getString(R.string.group_applications); 1155 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 1156 1157 if (applicationName != null && applicationName.equals(shortcutName)) { 1158 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 1159 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 1160 1161 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1162 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); 1163 startActivityForResult(pickIntent, requestCodeApplication); 1164 } else { 1165 startActivityForResult(intent, requestCodeShortcut); 1166 } 1167 } 1168 1169 void addLiveFolder(Intent intent) { 1170 // Handle case where user selected "Folder" 1171 String folderName = getResources().getString(R.string.group_folder); 1172 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 1173 1174 if (folderName != null && folderName.equals(shortcutName)) { 1175 addFolder(); 1176 } else { 1177 startActivityForResult(intent, REQUEST_CREATE_LIVE_FOLDER); 1178 } 1179 } 1180 1181 void addFolder() { 1182 UserFolderInfo folderInfo = new UserFolderInfo(); 1183 folderInfo.title = getText(R.string.folder_name); 1184 1185 CellLayout.CellInfo cellInfo = mAddItemCellInfo; 1186 cellInfo.screen = mWorkspace.getCurrentScreen(); 1187 if (!findSingleSlot(cellInfo)) return; 1188 1189 // Update the model 1190 LauncherModel.addItemToDatabase(this, folderInfo, 1191 LauncherSettings.Favorites.CONTAINER_DESKTOP, 1192 mWorkspace.getCurrentScreen(), cellInfo.cellX, cellInfo.cellY, false); 1193 mFolders.put(folderInfo.id, folderInfo); 1194 1195 // Create the view 1196 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, 1197 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), folderInfo); 1198 mWorkspace.addInCurrentScreen(newFolder, 1199 cellInfo.cellX, cellInfo.cellY, 1, 1, isWorkspaceLocked()); 1200 } 1201 1202 void removeFolder(FolderInfo folder) { 1203 mFolders.remove(folder.id); 1204 } 1205 1206 private void completeAddLiveFolder(Intent data, CellLayout.CellInfo cellInfo) { 1207 cellInfo.screen = mWorkspace.getCurrentScreen(); 1208 if (!findSingleSlot(cellInfo)) return; 1209 1210 final LiveFolderInfo info = addLiveFolder(this, data, cellInfo, false); 1211 1212 if (!mRestoring) { 1213 final View view = LiveFolderIcon.fromXml(R.layout.live_folder_icon, this, 1214 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info); 1215 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, 1216 isWorkspaceLocked()); 1217 } 1218 } 1219 1220 static LiveFolderInfo addLiveFolder(Context context, Intent data, 1221 CellLayout.CellInfo cellInfo, boolean notify) { 1222 1223 Intent baseIntent = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_BASE_INTENT); 1224 String name = data.getStringExtra(LiveFolders.EXTRA_LIVE_FOLDER_NAME); 1225 1226 Drawable icon = null; 1227 boolean filtered = false; 1228 Intent.ShortcutIconResource iconResource = null; 1229 1230 Parcelable extra = data.getParcelableExtra(LiveFolders.EXTRA_LIVE_FOLDER_ICON); 1231 if (extra != null && extra instanceof Intent.ShortcutIconResource) { 1232 try { 1233 iconResource = (Intent.ShortcutIconResource) extra; 1234 final PackageManager packageManager = context.getPackageManager(); 1235 Resources resources = packageManager.getResourcesForApplication( 1236 iconResource.packageName); 1237 final int id = resources.getIdentifier(iconResource.resourceName, null, null); 1238 icon = resources.getDrawable(id); 1239 } catch (Exception e) { 1240 Log.w(TAG, "Could not load live folder icon: " + extra); 1241 } 1242 } 1243 1244 if (icon == null) { 1245 icon = context.getResources().getDrawable(R.drawable.ic_launcher_folder); 1246 } 1247 1248 final LiveFolderInfo info = new LiveFolderInfo(); 1249 info.icon = icon; 1250 info.filtered = filtered; 1251 info.title = name; 1252 info.iconResource = iconResource; 1253 info.uri = data.getData(); 1254 info.baseIntent = baseIntent; 1255 info.displayMode = data.getIntExtra(LiveFolders.EXTRA_LIVE_FOLDER_DISPLAY_MODE, 1256 LiveFolders.DISPLAY_MODE_GRID); 1257 1258 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, 1259 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); 1260 mFolders.put(info.id, info); 1261 1262 return info; 1263 } 1264 1265 private boolean findSingleSlot(CellLayout.CellInfo cellInfo) { 1266 final int[] xy = new int[2]; 1267 if (findSlot(cellInfo, xy, 1, 1)) { 1268 cellInfo.cellX = xy[0]; 1269 cellInfo.cellY = xy[1]; 1270 return true; 1271 } 1272 return false; 1273 } 1274 1275 private boolean findSlot(CellLayout.CellInfo cellInfo, int[] xy, int spanX, int spanY) { 1276 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) { 1277 boolean[] occupied = mSavedState != null ? 1278 mSavedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS) : null; 1279 cellInfo = mWorkspace.findAllVacantCells(occupied); 1280 if (!cellInfo.findCellForSpan(xy, spanX, spanY)) { 1281 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show(); 1282 return false; 1283 } 1284 } 1285 return true; 1286 } 1287 1288 private void showNotifications() { 1289 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE); 1290 if (statusBar != null) { 1291 statusBar.expand(); 1292 } 1293 } 1294 1295 private void startWallpaper() { 1296 closeAllApps(true); 1297 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); 1298 Intent chooser = Intent.createChooser(pickWallpaper, 1299 getText(R.string.chooser_wallpaper)); 1300 // NOTE: Adds a configure option to the chooser if the wallpaper supports it 1301 // Removed in Eclair MR1 1302// WallpaperManager wm = (WallpaperManager) 1303// getSystemService(Context.WALLPAPER_SERVICE); 1304// WallpaperInfo wi = wm.getWallpaperInfo(); 1305// if (wi != null && wi.getSettingsActivity() != null) { 1306// LabeledIntent li = new LabeledIntent(getPackageName(), 1307// R.string.configure_wallpaper, 0); 1308// li.setClassName(wi.getPackageName(), wi.getSettingsActivity()); 1309// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li }); 1310// } 1311 startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); 1312 } 1313 1314 /** 1315 * Registers various content observers. The current implementation registers 1316 * only a favorites observer to keep track of the favorites applications. 1317 */ 1318 private void registerContentObservers() { 1319 ContentResolver resolver = getContentResolver(); 1320 resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI, 1321 true, mWidgetObserver); 1322 } 1323 1324 @Override 1325 public boolean dispatchKeyEvent(KeyEvent event) { 1326 if (event.getAction() == KeyEvent.ACTION_DOWN) { 1327 switch (event.getKeyCode()) { 1328 case KeyEvent.KEYCODE_HOME: 1329 return true; 1330 case KeyEvent.KEYCODE_VOLUME_DOWN: 1331 if (SystemProperties.getInt("launcher2.dumpstate", 0) != 0) { 1332 dumpState(); 1333 return true; 1334 } 1335 break; 1336 } 1337 } else if (event.getAction() == KeyEvent.ACTION_UP) { 1338 switch (event.getKeyCode()) { 1339 case KeyEvent.KEYCODE_HOME: 1340 return true; 1341 } 1342 } 1343 1344 return super.dispatchKeyEvent(event); 1345 } 1346 1347 @Override 1348 public void onBackPressed() { 1349 if (isAllAppsVisible()) { 1350 closeAllApps(true); 1351 } else { 1352 closeFolder(); 1353 } 1354 dismissPreview(mPreviousView); 1355 dismissPreview(mNextView); 1356 } 1357 1358 private void closeFolder() { 1359 Folder folder = mWorkspace.getOpenFolder(); 1360 if (folder != null) { 1361 closeFolder(folder); 1362 } 1363 } 1364 1365 void closeFolder(Folder folder) { 1366 folder.getInfo().opened = false; 1367 ViewGroup parent = (ViewGroup) folder.getParent(); 1368 if (parent != null) { 1369 parent.removeView(folder); 1370 if (folder instanceof DropTarget) { 1371 // Live folders aren't DropTargets. 1372 mDragController.removeDropTarget((DropTarget)folder); 1373 } 1374 } 1375 folder.onClose(); 1376 } 1377 1378 /** 1379 * Re-listen when widgets are reset. 1380 */ 1381 private void onAppWidgetReset() { 1382 mAppWidgetHost.startListening(); 1383 } 1384 1385 /** 1386 * Go through the and disconnect any of the callbacks in the drawables and the views or we 1387 * leak the previous Home screen on orientation change. 1388 */ 1389 private void unbindDesktopItems() { 1390 for (ItemInfo item: mDesktopItems) { 1391 item.unbind(); 1392 } 1393 } 1394 1395 /** 1396 * Launches the intent referred by the clicked shortcut. 1397 * 1398 * @param v The view representing the clicked shortcut. 1399 */ 1400 public void onClick(View v) { 1401 Object tag = v.getTag(); 1402 if (tag instanceof ApplicationInfo) { 1403 // Open shortcut 1404 final Intent intent = ((ApplicationInfo) tag).intent; 1405 startActivitySafely(intent); 1406 } else if (tag instanceof FolderInfo) { 1407 handleFolderClick((FolderInfo) tag); 1408 } else if (v == mHandleView) { 1409 if (isAllAppsVisible()) { 1410 closeAllApps(true); 1411 } else { 1412 showAllApps(true); 1413 } 1414 } 1415 } 1416 1417 void startActivitySafely(Intent intent) { 1418 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1419 try { 1420 startActivity(intent); 1421 } catch (ActivityNotFoundException e) { 1422 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1423 } catch (SecurityException e) { 1424 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1425 Log.e(TAG, "Launcher does not have the permission to launch " + intent + 1426 ". Make sure to create a MAIN intent-filter for the corresponding activity " + 1427 "or use the exported attribute for this activity.", e); 1428 } 1429 } 1430 1431 private void handleFolderClick(FolderInfo folderInfo) { 1432 if (!folderInfo.opened) { 1433 // Close any open folder 1434 closeFolder(); 1435 // Open the requested folder 1436 openFolder(folderInfo); 1437 } else { 1438 // Find the open folder... 1439 Folder openFolder = mWorkspace.getFolderForTag(folderInfo); 1440 int folderScreen; 1441 if (openFolder != null) { 1442 folderScreen = mWorkspace.getScreenForView(openFolder); 1443 // .. and close it 1444 closeFolder(openFolder); 1445 if (folderScreen != mWorkspace.getCurrentScreen()) { 1446 // Close any folder open on the current screen 1447 closeFolder(); 1448 // Pull the folder onto this screen 1449 openFolder(folderInfo); 1450 } 1451 } 1452 } 1453 } 1454 1455 /** 1456 * Opens the user fodler described by the specified tag. The opening of the folder 1457 * is animated relative to the specified View. If the View is null, no animation 1458 * is played. 1459 * 1460 * @param folderInfo The FolderInfo describing the folder to open. 1461 */ 1462 private void openFolder(FolderInfo folderInfo) { 1463 Folder openFolder; 1464 1465 if (folderInfo instanceof UserFolderInfo) { 1466 openFolder = UserFolder.fromXml(this); 1467 } else if (folderInfo instanceof LiveFolderInfo) { 1468 openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo); 1469 } else { 1470 return; 1471 } 1472 1473 openFolder.setDragController(mDragController); 1474 openFolder.setLauncher(this); 1475 1476 openFolder.bind(folderInfo); 1477 folderInfo.opened = true; 1478 1479 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4); 1480 openFolder.onOpen(); 1481 } 1482 1483 public boolean onLongClick(View v) { 1484 switch (v.getId()) { 1485 case R.id.previous_screen: 1486 if (!isAllAppsVisible()) { 1487 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1488 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1489 showPreviousPreview(v); 1490 } 1491 return true; 1492 case R.id.next_screen: 1493 if (!isAllAppsVisible()) { 1494 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1495 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1496 showNextPreview(v); 1497 } 1498 return true; 1499 } 1500 1501 if (isWorkspaceLocked()) { 1502 return false; 1503 } 1504 1505 if (!(v instanceof CellLayout)) { 1506 v = (View) v.getParent(); 1507 } 1508 1509 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag(); 1510 1511 // This happens when long clicking an item with the dpad/trackball 1512 if (cellInfo == null) { 1513 return true; 1514 } 1515 1516 if (mWorkspace.allowLongPress()) { 1517 if (cellInfo.cell == null) { 1518 if (cellInfo.valid) { 1519 // User long pressed on empty space 1520 mWorkspace.setAllowLongPress(false); 1521 showAddDialog(cellInfo); 1522 } 1523 } else { 1524 if (!(cellInfo.cell instanceof Folder)) { 1525 // User long pressed on an item 1526 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1527 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1528 mWorkspace.startDrag(cellInfo); 1529 } 1530 } 1531 } 1532 return true; 1533 } 1534 1535 @SuppressWarnings({"unchecked"}) 1536 private void dismissPreview(final View v) { 1537 final PopupWindow window = (PopupWindow) v.getTag(); 1538 if (window != null) { 1539 window.setOnDismissListener(new PopupWindow.OnDismissListener() { 1540 public void onDismiss() { 1541 ViewGroup group = (ViewGroup) v.getTag(R.id.workspace); 1542 int count = group.getChildCount(); 1543 for (int i = 0; i < count; i++) { 1544 ((ImageView) group.getChildAt(i)).setImageDrawable(null); 1545 } 1546 ArrayList<Bitmap> bitmaps = (ArrayList<Bitmap>) v.getTag(R.id.icon); 1547 for (Bitmap bitmap : bitmaps) bitmap.recycle(); 1548 1549 v.setTag(R.id.workspace, null); 1550 v.setTag(R.id.icon, null); 1551 window.setOnDismissListener(null); 1552 } 1553 }); 1554 window.dismiss(); 1555 } 1556 v.setTag(null); 1557 } 1558 1559 private void showPreviousPreview(View anchor) { 1560 int current = mWorkspace.getCurrentScreen(); 1561 if (current <= 0) return; 1562 1563 showPreviews(anchor, 0, mWorkspace.getChildCount()); 1564 } 1565 1566 private void showNextPreview(View anchor) { 1567 int current = mWorkspace.getCurrentScreen(); 1568 if (current >= mWorkspace.getChildCount() - 1) return; 1569 1570 showPreviews(anchor, 0, mWorkspace.getChildCount()); 1571 } 1572 1573 private void showPreviews(final View anchor, int start, int end) { 1574 Resources resources = getResources(); 1575 1576 Workspace workspace = mWorkspace; 1577 CellLayout cell = ((CellLayout) workspace.getChildAt(start)); 1578 1579 float max = workspace.getChildCount(); 1580 1581 Rect r = new Rect(); 1582 resources.getDrawable(R.drawable.preview_background).getPadding(r); 1583 int extraW = (int) ((r.left + r.right) * max); 1584 int extraH = r.top + r.bottom; 1585 1586 int aW = cell.getWidth() - extraW; 1587 float w = aW / max; 1588 1589 int width = cell.getWidth(); 1590 int height = cell.getHeight(); 1591 int x = cell.getLeftPadding(); 1592 int y = cell.getTopPadding(); 1593 width -= (x + cell.getRightPadding()); 1594 height -= (y + cell.getBottomPadding()); 1595 1596 float scale = w / width; 1597 1598 int count = end - start; 1599 1600 final float sWidth = width * scale; 1601 float sHeight = height * scale; 1602 1603 LinearLayout preview = new LinearLayout(this); 1604 1605 PreviewTouchHandler handler = new PreviewTouchHandler(anchor); 1606 ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count); 1607 1608 for (int i = start; i < end; i++) { 1609 ImageView image = new ImageView(this); 1610 cell = (CellLayout) workspace.getChildAt(i); 1611 1612 Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight, 1613 Bitmap.Config.ARGB_8888); 1614 1615 Canvas c = new Canvas(bitmap); 1616 c.scale(scale, scale); 1617 c.translate(-cell.getLeftPadding(), -cell.getTopPadding()); 1618 cell.dispatchDraw(c); 1619 1620 image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background)); 1621 image.setImageBitmap(bitmap); 1622 image.setTag(i); 1623 image.setOnClickListener(handler); 1624 image.setOnFocusChangeListener(handler); 1625 image.setFocusable(true); 1626 if (i == mWorkspace.getCurrentScreen()) image.requestFocus(); 1627 1628 preview.addView(image, 1629 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 1630 1631 bitmaps.add(bitmap); 1632 } 1633 1634 PopupWindow p = new PopupWindow(this); 1635 p.setContentView(preview); 1636 p.setWidth((int) (sWidth * count + extraW)); 1637 p.setHeight((int) (sHeight + extraH)); 1638 p.setAnimationStyle(R.style.AnimationPreview); 1639 p.setOutsideTouchable(true); 1640 p.setFocusable(true); 1641 p.setBackgroundDrawable(new ColorDrawable(0)); 1642 p.showAsDropDown(anchor, 0, 0); 1643 1644 p.setOnDismissListener(new PopupWindow.OnDismissListener() { 1645 public void onDismiss() { 1646 dismissPreview(anchor); 1647 } 1648 }); 1649 1650 anchor.setTag(p); 1651 anchor.setTag(R.id.workspace, preview); 1652 anchor.setTag(R.id.icon, bitmaps); 1653 } 1654 1655 class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener { 1656 private final View mAnchor; 1657 1658 public PreviewTouchHandler(View anchor) { 1659 mAnchor = anchor; 1660 } 1661 1662 public void onClick(View v) { 1663 mWorkspace.snapToScreen((Integer) v.getTag()); 1664 v.post(this); 1665 } 1666 1667 public void run() { 1668 dismissPreview(mAnchor); 1669 } 1670 1671 public void onFocusChange(View v, boolean hasFocus) { 1672 if (hasFocus) { 1673 mWorkspace.snapToScreen((Integer) v.getTag()); 1674 } 1675 } 1676 } 1677 1678 View getDrawerHandle() { 1679 return mHandleView; 1680 } 1681 1682 Workspace getWorkspace() { 1683 return mWorkspace; 1684 } 1685 1686 @Override 1687 protected Dialog onCreateDialog(int id) { 1688 switch (id) { 1689 case DIALOG_CREATE_SHORTCUT: 1690 return new CreateShortcut().createDialog(); 1691 case DIALOG_RENAME_FOLDER: 1692 return new RenameFolder().createDialog(); 1693 } 1694 1695 return super.onCreateDialog(id); 1696 } 1697 1698 @Override 1699 protected void onPrepareDialog(int id, Dialog dialog) { 1700 switch (id) { 1701 case DIALOG_CREATE_SHORTCUT: 1702 break; 1703 case DIALOG_RENAME_FOLDER: 1704 if (mFolderInfo != null) { 1705 EditText input = (EditText) dialog.findViewById(R.id.folder_name); 1706 final CharSequence text = mFolderInfo.title; 1707 input.setText(text); 1708 input.setSelection(0, text.length()); 1709 } 1710 break; 1711 } 1712 } 1713 1714 void showRenameDialog(FolderInfo info) { 1715 mFolderInfo = info; 1716 mWaitingForResult = true; 1717 showDialog(DIALOG_RENAME_FOLDER); 1718 } 1719 1720 private void showAddDialog(CellLayout.CellInfo cellInfo) { 1721 mAddItemCellInfo = cellInfo; 1722 mWaitingForResult = true; 1723 showDialog(DIALOG_CREATE_SHORTCUT); 1724 } 1725 1726 private void pickShortcut(int requestCode, int title) { 1727 Bundle bundle = new Bundle(); 1728 1729 ArrayList<String> shortcutNames = new ArrayList<String>(); 1730 shortcutNames.add(getString(R.string.group_applications)); 1731 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); 1732 1733 ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>(); 1734 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, 1735 R.drawable.ic_launcher_application)); 1736 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); 1737 1738 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1739 pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT)); 1740 pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title)); 1741 pickIntent.putExtras(bundle); 1742 1743 startActivityForResult(pickIntent, requestCode); 1744 } 1745 1746 private class RenameFolder { 1747 private EditText mInput; 1748 1749 Dialog createDialog() { 1750 mWaitingForResult = true; 1751 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); 1752 mInput = (EditText) layout.findViewById(R.id.folder_name); 1753 1754 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); 1755 builder.setIcon(0); 1756 builder.setTitle(getString(R.string.rename_folder_title)); 1757 builder.setCancelable(true); 1758 builder.setOnCancelListener(new Dialog.OnCancelListener() { 1759 public void onCancel(DialogInterface dialog) { 1760 cleanup(); 1761 } 1762 }); 1763 builder.setNegativeButton(getString(R.string.cancel_action), 1764 new Dialog.OnClickListener() { 1765 public void onClick(DialogInterface dialog, int which) { 1766 cleanup(); 1767 } 1768 } 1769 ); 1770 builder.setPositiveButton(getString(R.string.rename_action), 1771 new Dialog.OnClickListener() { 1772 public void onClick(DialogInterface dialog, int which) { 1773 changeFolderName(); 1774 } 1775 } 1776 ); 1777 builder.setView(layout); 1778 1779 final AlertDialog dialog = builder.create(); 1780 dialog.setOnShowListener(new DialogInterface.OnShowListener() { 1781 public void onShow(DialogInterface dialog) { 1782 mInput.requestFocus(); 1783 InputMethodManager inputManager = (InputMethodManager) 1784 getSystemService(Context.INPUT_METHOD_SERVICE); 1785 inputManager.showSoftInput(mInput, 0); 1786 } 1787 }); 1788 1789 return dialog; 1790 } 1791 1792 private void changeFolderName() { 1793 final String name = mInput.getText().toString(); 1794 if (!TextUtils.isEmpty(name)) { 1795 // Make sure we have the right folder info 1796 mFolderInfo = mFolders.get(mFolderInfo.id); 1797 mFolderInfo.title = name; 1798 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo); 1799 1800 if (mWorkspaceLoading) { 1801 lockAllApps(); 1802 mModel.setWorkspaceDirty(); 1803 mModel.startLoader(Launcher.this, false); 1804 } else { 1805 final FolderIcon folderIcon = (FolderIcon) 1806 mWorkspace.getViewForTag(mFolderInfo); 1807 if (folderIcon != null) { 1808 folderIcon.setText(name); 1809 getWorkspace().requestLayout(); 1810 } else { 1811 lockAllApps(); 1812 mModel.setWorkspaceDirty(); 1813 mWorkspaceLoading = true; 1814 mModel.startLoader(Launcher.this, false); 1815 } 1816 } 1817 } 1818 cleanup(); 1819 } 1820 1821 private void cleanup() { 1822 dismissDialog(DIALOG_RENAME_FOLDER); 1823 mWaitingForResult = false; 1824 mFolderInfo = null; 1825 } 1826 } 1827 1828 boolean isAllAppsVisible() { 1829 return mAllAppsGrid.isVisible(); 1830 } 1831 1832 boolean isAllAppsOpaque() { 1833 return mAllAppsGrid.isOpaque(); 1834 } 1835 1836 void showAllApps(boolean animated) { 1837 mAllAppsGrid.zoom(1.0f, animated); 1838 //mWorkspace.hide(); 1839 1840 mWorkspace.startFading(false); 1841 1842 mAllAppsGrid.setFocusable(true); 1843 mAllAppsGrid.requestFocus(); 1844 1845 // TODO: fade these two too 1846 mDeleteZone.setVisibility(View.GONE); 1847 //mHandleView.setVisibility(View.GONE); 1848 } 1849 1850 void closeAllApps(boolean animated) { 1851 if (mAllAppsGrid.isVisible()) { 1852 mAllAppsGrid.zoom(0.0f, animated); 1853 mAllAppsGrid.setFocusable(false); 1854 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); 1855 mWorkspace.startFading(true); 1856 1857 // TODO: fade these two too 1858 /* 1859 mDeleteZone.setVisibility(View.VISIBLE); 1860 mHandleView.setVisibility(View.VISIBLE); 1861 */ 1862 } 1863 } 1864 1865 void lockAllApps() { 1866 // TODO 1867 } 1868 1869 void unlockAllApps() { 1870 // TODO 1871 } 1872 1873 /** 1874 * Displays the shortcut creation dialog and launches, if necessary, the 1875 * appropriate activity. 1876 */ 1877 private class CreateShortcut implements DialogInterface.OnClickListener, 1878 DialogInterface.OnCancelListener, DialogInterface.OnDismissListener, 1879 DialogInterface.OnShowListener { 1880 1881 private AddAdapter mAdapter; 1882 1883 Dialog createDialog() { 1884 mWaitingForResult = true; 1885 1886 mAdapter = new AddAdapter(Launcher.this); 1887 1888 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); 1889 builder.setTitle(getString(R.string.menu_item_add_item)); 1890 builder.setAdapter(mAdapter, this); 1891 1892 builder.setInverseBackgroundForced(true); 1893 1894 AlertDialog dialog = builder.create(); 1895 dialog.setOnCancelListener(this); 1896 dialog.setOnDismissListener(this); 1897 dialog.setOnShowListener(this); 1898 1899 return dialog; 1900 } 1901 1902 public void onCancel(DialogInterface dialog) { 1903 mWaitingForResult = false; 1904 cleanup(); 1905 } 1906 1907 public void onDismiss(DialogInterface dialog) { 1908 } 1909 1910 private void cleanup() { 1911 dismissDialog(DIALOG_CREATE_SHORTCUT); 1912 } 1913 1914 /** 1915 * Handle the action clicked in the "Add to home" dialog. 1916 */ 1917 public void onClick(DialogInterface dialog, int which) { 1918 Resources res = getResources(); 1919 cleanup(); 1920 1921 switch (which) { 1922 case AddAdapter.ITEM_SHORTCUT: { 1923 // Insert extra item to handle picking application 1924 pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut); 1925 break; 1926 } 1927 1928 case AddAdapter.ITEM_APPWIDGET: { 1929 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId(); 1930 1931 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK); 1932 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 1933 // add the search widget 1934 ArrayList<AppWidgetProviderInfo> customInfo = 1935 new ArrayList<AppWidgetProviderInfo>(); 1936 AppWidgetProviderInfo info = new AppWidgetProviderInfo(); 1937 info.provider = new ComponentName(getPackageName(), "XXX.YYY"); 1938 info.label = getString(R.string.group_search); 1939 info.icon = R.drawable.ic_search_widget; 1940 customInfo.add(info); 1941 pickIntent.putParcelableArrayListExtra( 1942 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo); 1943 ArrayList<Bundle> customExtras = new ArrayList<Bundle>(); 1944 Bundle b = new Bundle(); 1945 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET); 1946 customExtras.add(b); 1947 pickIntent.putParcelableArrayListExtra( 1948 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras); 1949 // start the pick activity 1950 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); 1951 break; 1952 } 1953 1954 case AddAdapter.ITEM_LIVE_FOLDER: { 1955 // Insert extra item to handle inserting folder 1956 Bundle bundle = new Bundle(); 1957 1958 ArrayList<String> shortcutNames = new ArrayList<String>(); 1959 shortcutNames.add(res.getString(R.string.group_folder)); 1960 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); 1961 1962 ArrayList<ShortcutIconResource> shortcutIcons = 1963 new ArrayList<ShortcutIconResource>(); 1964 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, 1965 R.drawable.ic_launcher_folder)); 1966 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); 1967 1968 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1969 pickIntent.putExtra(Intent.EXTRA_INTENT, 1970 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER)); 1971 pickIntent.putExtra(Intent.EXTRA_TITLE, 1972 getText(R.string.title_select_live_folder)); 1973 pickIntent.putExtras(bundle); 1974 1975 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER); 1976 break; 1977 } 1978 1979 case AddAdapter.ITEM_WALLPAPER: { 1980 startWallpaper(); 1981 break; 1982 } 1983 } 1984 } 1985 1986 public void onShow(DialogInterface dialog) { 1987 } 1988 } 1989 1990 /** 1991 * Receives notifications when applications are added/removed. 1992 */ 1993 private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver { 1994 @Override 1995 public void onReceive(Context context, Intent intent) { 1996 closeSystemDialogs(); 1997 } 1998 } 1999 2000 /** 2001 * Receives notifications whenever the appwidgets are reset. 2002 */ 2003 private class AppWidgetResetObserver extends ContentObserver { 2004 public AppWidgetResetObserver() { 2005 super(new Handler()); 2006 } 2007 2008 @Override 2009 public void onChange(boolean selfChange) { 2010 onAppWidgetReset(); 2011 } 2012 } 2013 2014 /** 2015 * Implementation of the method from LauncherModel.Callbacks. 2016 */ 2017 public int getCurrentWorkspaceScreen() { 2018 return mWorkspace.getCurrentScreen(); 2019 } 2020 2021 /** 2022 * Refreshes the shortcuts shown on the workspace. 2023 * 2024 * Implementation of the method from LauncherModel.Callbacks. 2025 */ 2026 public void startBinding() { 2027 final Workspace workspace = mWorkspace; 2028 int count = workspace.getChildCount(); 2029 for (int i = 0; i < count; i++) { 2030 // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate(). 2031 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout(); 2032 } 2033 2034 if (DEBUG_USER_INTERFACE) { 2035 android.widget.Button finishButton = new android.widget.Button(this); 2036 finishButton.setText("Finish"); 2037 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1); 2038 2039 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() { 2040 public void onClick(View v) { 2041 finish(); 2042 } 2043 }); 2044 } 2045 } 2046 2047 /** 2048 * Bind the items start-end from the list. 2049 * 2050 * Implementation of the method from LauncherModel.Callbacks. 2051 */ 2052 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { 2053 2054 final Workspace workspace = mWorkspace; 2055 2056 for (int i=start; i<end; i++) { 2057 final ItemInfo item = shortcuts.get(i); 2058 mDesktopItems.add(item); 2059 switch (item.itemType) { 2060 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2061 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2062 final View shortcut = createShortcut((ApplicationInfo) item); 2063 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1, 2064 false); 2065 break; 2066 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: 2067 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, 2068 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), 2069 (UserFolderInfo) item); 2070 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1, 2071 false); 2072 break; 2073 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: 2074 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml( 2075 R.layout.live_folder_icon, this, 2076 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), 2077 (LiveFolderInfo) item); 2078 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1, 2079 false); 2080 break; 2081 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: 2082 final int screen = workspace.getCurrentScreen(); 2083 final View view = mInflater.inflate(R.layout.widget_search, 2084 (ViewGroup) workspace.getChildAt(screen), false); 2085 2086 Search search = (Search) view.findViewById(R.id.widget_search); 2087 search.setLauncher(this); 2088 2089 final Widget widget = (Widget) item; 2090 view.setTag(widget); 2091 2092 workspace.addWidget(view, widget, false); 2093 break; 2094 } 2095 } 2096 2097 workspace.requestLayout(); 2098 } 2099 2100 /** 2101 * Implementation of the method from LauncherModel.Callbacks. 2102 */ 2103 public void bindFolders(HashMap<Long, FolderInfo> folders) { 2104 mFolders.clear(); 2105 mFolders.putAll(folders); 2106 } 2107 2108 /** 2109 * Add the views for a widget to the workspace. 2110 * 2111 * Implementation of the method from LauncherModel.Callbacks. 2112 */ 2113 public void bindAppWidget(LauncherAppWidgetInfo item) { 2114 final Workspace workspace = mWorkspace; 2115 2116 final int appWidgetId = item.appWidgetId; 2117 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 2118 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 2119 2120 item.hostView.setAppWidget(appWidgetId, appWidgetInfo); 2121 item.hostView.setTag(item); 2122 2123 workspace.addInScreen(item.hostView, item.screen, item.cellX, 2124 item.cellY, item.spanX, item.spanY, false); 2125 2126 workspace.requestLayout(); 2127 2128 mDesktopItems.add(item); 2129 } 2130 2131 /** 2132 * Callback saying that there aren't any more items to bind. 2133 * 2134 * Implementation of the method from LauncherModel.Callbacks. 2135 */ 2136 public void finishBindingItems() { 2137 if (mSavedState != null) { 2138 if (!mWorkspace.hasFocus()) { 2139 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); 2140 } 2141 2142 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS); 2143 if (userFolders != null) { 2144 for (long folderId : userFolders) { 2145 final FolderInfo info = mFolders.get(folderId); 2146 if (info != null) { 2147 openFolder(info); 2148 } 2149 } 2150 final Folder openFolder = mWorkspace.getOpenFolder(); 2151 if (openFolder != null) { 2152 openFolder.requestFocus(); 2153 } 2154 } 2155 2156 mSavedState = null; 2157 } 2158 2159 if (mSavedInstanceState != null) { 2160 super.onRestoreInstanceState(mSavedInstanceState); 2161 mSavedInstanceState = null; 2162 } 2163 2164 mWorkspaceLoading = false; 2165 } 2166 2167 /** 2168 * Add the icons for all apps. 2169 * 2170 * Implementation of the method from LauncherModel.Callbacks. 2171 */ 2172 public void bindAllApplications(ArrayList<ApplicationInfo> apps) { 2173 mAllAppsGrid.setApps(apps); 2174 } 2175 2176 /** 2177 * A package was installed. 2178 * 2179 * Implementation of the method from LauncherModel.Callbacks. 2180 */ 2181 public void bindPackageAdded(ArrayList<ApplicationInfo> apps) { 2182 removeDialog(DIALOG_CREATE_SHORTCUT); 2183 mAllAppsGrid.addApps(apps); 2184 } 2185 2186 /** 2187 * A package was updated. 2188 * 2189 * Implementation of the method from LauncherModel.Callbacks. 2190 */ 2191 public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps) { 2192 removeDialog(DIALOG_CREATE_SHORTCUT); 2193 mWorkspace.updateShortcutsForPackage(packageName); 2194 } 2195 2196 /** 2197 * A package was uninstalled. 2198 * 2199 * Implementation of the method from LauncherModel.Callbacks. 2200 */ 2201 public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps) { 2202 removeDialog(DIALOG_CREATE_SHORTCUT); 2203 mWorkspace.removeShortcutsForPackage(packageName); 2204 mAllAppsGrid.removeApps(apps); 2205 } 2206 2207 /** 2208 * Prints out out state for debugging. 2209 */ 2210 public void dumpState() { 2211 Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this); 2212 Log.d(TAG, "mSavedState=" + mSavedState); 2213 Log.d(TAG, "mIsNewIntent=" + mIsNewIntent); 2214 Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading); 2215 Log.d(TAG, "mRestoring=" + mRestoring); 2216 Log.d(TAG, "mWaitingForResult=" + mWaitingForResult); 2217 Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState); 2218 Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size()); 2219 Log.d(TAG, "mFolders.size=" + mFolders.size()); 2220 mModel.dumpState(); 2221 mAllAppsGrid.dumpState(); 2222 Log.d(TAG, "END launcher2 dump state"); 2223 } 2224} 2225