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