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