Launcher.java revision 39bfc13a77b25aa9e1dc322b223030545c9af2c1
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.launcher2; 18 19import android.app.Activity; 20import android.app.AlertDialog; 21import android.app.Dialog; 22import android.app.ISearchManager; 23import android.app.SearchManager; 24import android.app.StatusBarManager; 25import android.app.WallpaperManager; 26import android.content.ActivityNotFoundException; 27import android.content.BroadcastReceiver; 28import android.content.ComponentName; 29import android.content.ContentResolver; 30import android.content.Context; 31import android.content.DialogInterface; 32import android.content.Intent; 33import android.content.Intent.ShortcutIconResource; 34import android.content.IntentFilter; 35import android.content.pm.ActivityInfo; 36import android.content.pm.PackageManager; 37import android.content.pm.PackageManager.NameNotFoundException; 38import android.content.res.Configuration; 39import android.content.res.Resources; 40import android.database.ContentObserver; 41import android.graphics.Bitmap; 42import android.graphics.Rect; 43import android.graphics.Canvas; 44import android.graphics.drawable.Drawable; 45import android.graphics.drawable.ColorDrawable; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.Parcelable; 49import android.os.RemoteException; 50import android.os.ServiceManager; 51import android.os.SystemProperties; 52import android.provider.LiveFolders; 53import android.text.Selection; 54import android.text.SpannableStringBuilder; 55import android.text.TextUtils; 56import android.text.method.TextKeyListener; 57import android.util.Log; 58import android.view.Display; 59import android.view.HapticFeedbackConstants; 60import android.view.KeyEvent; 61import android.view.LayoutInflater; 62import android.view.Menu; 63import android.view.MenuItem; 64import android.view.View; 65import android.view.ViewGroup; 66import android.view.View.OnLongClickListener; 67import android.view.inputmethod.InputMethodManager; 68import android.widget.EditText; 69import android.widget.TextView; 70import android.widget.Toast; 71import android.widget.ImageView; 72import android.widget.PopupWindow; 73import android.widget.LinearLayout; 74import android.appwidget.AppWidgetManager; 75import android.appwidget.AppWidgetProviderInfo; 76 77import java.util.ArrayList; 78import java.util.HashMap; 79import java.io.DataOutputStream; 80import java.io.FileNotFoundException; 81import java.io.IOException; 82import java.io.DataInputStream; 83 84/** 85 * Default launcher application. 86 */ 87public final class Launcher extends Activity 88 implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks { 89 static final String TAG = "Launcher"; 90 static final boolean LOGD = false; 91 92 static final boolean PROFILE_STARTUP = false; 93 static final boolean PROFILE_ROTATE = false; 94 static final boolean DEBUG_USER_INTERFACE = false; 95 96 private static final int WALLPAPER_SCREENS_SPAN = 2; 97 98 private static final int MENU_GROUP_ADD = 1; 99 private static final int MENU_ADD = Menu.FIRST + 1; 100 private static final int MENU_WALLPAPER_SETTINGS = MENU_ADD + 1; 101 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1; 102 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1; 103 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1; 104 105 private static final int REQUEST_CREATE_SHORTCUT = 1; 106 private static final int REQUEST_CREATE_LIVE_FOLDER = 4; 107 private static final int REQUEST_CREATE_APPWIDGET = 5; 108 private static final int REQUEST_PICK_APPLICATION = 6; 109 private static final int REQUEST_PICK_SHORTCUT = 7; 110 private static final int REQUEST_PICK_LIVE_FOLDER = 8; 111 private static final int REQUEST_PICK_APPWIDGET = 9; 112 private static final int REQUEST_PICK_WALLPAPER = 10; 113 114 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; 115 116 static final String EXTRA_CUSTOM_WIDGET = "custom_widget"; 117 static final String SEARCH_WIDGET = "search_widget"; 118 119 static final int SCREEN_COUNT = 5; 120 static final int DEFAULT_SCREEN = 2; 121 static final int NUMBER_CELLS_X = 4; 122 static final int NUMBER_CELLS_Y = 4; 123 124 static final int DIALOG_CREATE_SHORTCUT = 1; 125 static final int DIALOG_RENAME_FOLDER = 2; 126 127 private static final String PREFERENCES = "launcher.preferences"; 128 129 // Type: int 130 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; 131 // Type: boolean 132 private static final String RUNTIME_STATE_ALL_APPS_FOLDER = "launcher.all_apps_folder"; 133 // Type: long 134 private static final String RUNTIME_STATE_USER_FOLDERS = "launcher.user_folder"; 135 // Type: int 136 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; 137 // Type: int 138 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cellX"; 139 // Type: int 140 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cellY"; 141 // Type: int 142 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_X = "launcher.add_spanX"; 143 // Type: int 144 private static final String RUNTIME_STATE_PENDING_ADD_SPAN_Y = "launcher.add_spanY"; 145 // Type: int 146 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_X = "launcher.add_countX"; 147 // Type: int 148 private static final String RUNTIME_STATE_PENDING_ADD_COUNT_Y = "launcher.add_countY"; 149 // Type: int[] 150 private static final String RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS = "launcher.add_occupied_cells"; 151 // Type: boolean 152 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; 153 // Type: long 154 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; 155 156 static final int APPWIDGET_HOST_ID = 1024; 157 158 private static final Object sLock = new Object(); 159 private static int sScreen = DEFAULT_SCREEN; 160 161 private final BroadcastReceiver mCloseSystemDialogsReceiver 162 = new CloseSystemDialogsIntentReceiver(); 163 private final ContentObserver mWidgetObserver = new AppWidgetResetObserver(); 164 165 private LayoutInflater mInflater; 166 167 private DragController mDragController; 168 private Workspace mWorkspace; 169 170 private AppWidgetManager mAppWidgetManager; 171 private LauncherAppWidgetHost mAppWidgetHost; 172 173 private CellLayout.CellInfo mAddItemCellInfo; 174 private CellLayout.CellInfo mMenuAddInfo; 175 private final int[] mCellCoordinates = new int[2]; 176 private FolderInfo mFolderInfo; 177 178 private DeleteZone mDeleteZone; 179 private HandleView mHandleView; 180 private AllAppsView mAllAppsGrid; 181 182 private Bundle mSavedState; 183 184 private SpannableStringBuilder mDefaultKeySsb = null; 185 186 private boolean mIsNewIntent; 187 188 private boolean mWorkspaceLoading = true; 189 190 private boolean mRestoring; 191 private boolean mWaitingForResult; 192 193 private Bundle mSavedInstanceState; 194 195 private LauncherModel mModel; 196 197 private ArrayList<ItemInfo> mDesktopItems = new ArrayList<ItemInfo>(); 198 private static HashMap<Long, FolderInfo> mFolders = new HashMap<Long, FolderInfo>(); 199 200 private ImageView mPreviousView; 201 private ImageView mNextView; 202 203 @Override 204 protected void onCreate(Bundle savedInstanceState) { 205 super.onCreate(savedInstanceState); 206 207 mModel = ((LauncherApplication)getApplication()).setLauncher(this); 208 mDragController = new DragController(this); 209 mInflater = getLayoutInflater(); 210 211 IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 212 registerReceiver(mCloseSystemDialogsReceiver, filter); 213 214 mAppWidgetManager = AppWidgetManager.getInstance(this); 215 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); 216 mAppWidgetHost.startListening(); 217 218 if (PROFILE_STARTUP) { 219 android.os.Debug.startMethodTracing("/sdcard/launcher"); 220 } 221 222 checkForLocaleChange(); 223 setWallpaperDimension(); 224 225 setContentView(R.layout.launcher); 226 setupViews(); 227 228 registerContentObservers(); 229 230 lockAllApps(); 231 232 mSavedState = savedInstanceState; 233 restoreState(mSavedState); 234 235 if (PROFILE_STARTUP) { 236 android.os.Debug.stopMethodTracing(); 237 } 238 239 // We have a new AllAppsView, we need to re-bind everything, and it could have 240 // changed in our absence. 241 mModel.setAllAppsDirty(); 242 mModel.setWorkspaceDirty(); 243 244 if (!mRestoring) { 245 mModel.startLoader(this, true); 246 } 247 248 // For handling default keys 249 mDefaultKeySsb = new SpannableStringBuilder(); 250 Selection.setSelection(mDefaultKeySsb, 0); 251 } 252 253 private void checkForLocaleChange() { 254 final LocaleConfiguration localeConfiguration = new LocaleConfiguration(); 255 readConfiguration(this, localeConfiguration); 256 257 final Configuration configuration = getResources().getConfiguration(); 258 259 final String previousLocale = localeConfiguration.locale; 260 final String locale = configuration.locale.toString(); 261 262 final int previousMcc = localeConfiguration.mcc; 263 final int mcc = configuration.mcc; 264 265 final int previousMnc = localeConfiguration.mnc; 266 final int mnc = configuration.mnc; 267 268 boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; 269 270 if (localeChanged) { 271 localeConfiguration.locale = locale; 272 localeConfiguration.mcc = mcc; 273 localeConfiguration.mnc = mnc; 274 275 writeConfiguration(this, localeConfiguration); 276 AppInfoCache.flush(); 277 } 278 } 279 280 private static class LocaleConfiguration { 281 public String locale; 282 public int mcc = -1; 283 public int mnc = -1; 284 } 285 286 private static void readConfiguration(Context context, LocaleConfiguration configuration) { 287 DataInputStream in = null; 288 try { 289 in = new DataInputStream(context.openFileInput(PREFERENCES)); 290 configuration.locale = in.readUTF(); 291 configuration.mcc = in.readInt(); 292 configuration.mnc = in.readInt(); 293 } catch (FileNotFoundException e) { 294 // Ignore 295 } catch (IOException e) { 296 // Ignore 297 } finally { 298 if (in != null) { 299 try { 300 in.close(); 301 } catch (IOException e) { 302 // Ignore 303 } 304 } 305 } 306 } 307 308 private static void writeConfiguration(Context context, LocaleConfiguration configuration) { 309 DataOutputStream out = null; 310 try { 311 out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); 312 out.writeUTF(configuration.locale); 313 out.writeInt(configuration.mcc); 314 out.writeInt(configuration.mnc); 315 out.flush(); 316 } catch (FileNotFoundException e) { 317 // Ignore 318 } catch (IOException e) { 319 //noinspection ResultOfMethodCallIgnored 320 context.getFileStreamPath(PREFERENCES).delete(); 321 } finally { 322 if (out != null) { 323 try { 324 out.close(); 325 } catch (IOException e) { 326 // Ignore 327 } 328 } 329 } 330 } 331 332 static int getScreen() { 333 synchronized (sLock) { 334 return sScreen; 335 } 336 } 337 338 static void setScreen(int screen) { 339 synchronized (sLock) { 340 sScreen = screen; 341 } 342 } 343 344 private void setWallpaperDimension() { 345 WallpaperManager wpm = (WallpaperManager)getSystemService(WALLPAPER_SERVICE); 346 347 Display display = getWindowManager().getDefaultDisplay(); 348 boolean isPortrait = display.getWidth() < display.getHeight(); 349 350 final int width = isPortrait ? display.getWidth() : display.getHeight(); 351 final int height = isPortrait ? display.getHeight() : display.getWidth(); 352 wpm.suggestDesiredDimensions(width * WALLPAPER_SCREENS_SPAN, height); 353 } 354 355 @Override 356 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 357 mWaitingForResult = false; 358 359 // The pattern used here is that a user PICKs a specific application, 360 // which, depending on the target, might need to CREATE the actual target. 361 362 // For example, the user would PICK_SHORTCUT for "Music playlist", and we 363 // launch over to the Music app to actually CREATE_SHORTCUT. 364 365 if (resultCode == RESULT_OK && mAddItemCellInfo != null) { 366 switch (requestCode) { 367 case REQUEST_PICK_APPLICATION: 368 completeAddApplication(this, data, mAddItemCellInfo); 369 break; 370 case REQUEST_PICK_SHORTCUT: 371 processShortcut(data, REQUEST_PICK_APPLICATION, REQUEST_CREATE_SHORTCUT); 372 break; 373 case REQUEST_CREATE_SHORTCUT: 374 completeAddShortcut(data, mAddItemCellInfo); 375 break; 376 case REQUEST_PICK_LIVE_FOLDER: 377 addLiveFolder(data); 378 break; 379 case REQUEST_CREATE_LIVE_FOLDER: 380 completeAddLiveFolder(data, mAddItemCellInfo); 381 break; 382 case REQUEST_PICK_APPWIDGET: 383 addAppWidget(data); 384 break; 385 case REQUEST_CREATE_APPWIDGET: 386 completeAddAppWidget(data, mAddItemCellInfo); 387 break; 388 case REQUEST_PICK_WALLPAPER: 389 // We just wanted the activity result here so we can clear mWaitingForResult 390 break; 391 } 392 } else if ((requestCode == REQUEST_PICK_APPWIDGET || 393 requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED && 394 data != null) { 395 // Clean up the appWidgetId if we canceled 396 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 397 if (appWidgetId != -1) { 398 mAppWidgetHost.deleteAppWidgetId(appWidgetId); 399 } 400 } 401 } 402 403 @Override 404 protected void onResume() { 405 super.onResume(); 406 407 if (mRestoring) { 408 mWorkspaceLoading = true; 409 mModel.startLoader(this, true); 410 mRestoring = false; 411 } 412 413 // If this was a new intent (i.e., the mIsNewIntent flag got set to true by 414 // onNewIntent), then close the search dialog if needed, because it probably 415 // came from the user pressing 'home' (rather than, for example, pressing 'back'). 416 if (mIsNewIntent) { 417 // Post to a handler so that this happens after the search dialog tries to open 418 // itself again. 419 mWorkspace.post(new Runnable() { 420 public void run() { 421 ISearchManager searchManagerService = ISearchManager.Stub.asInterface( 422 ServiceManager.getService(Context.SEARCH_SERVICE)); 423 try { 424 searchManagerService.stopSearch(); 425 } catch (RemoteException e) { 426 Log.e(TAG, "error stopping search", e); 427 } 428 } 429 }); 430 } 431 432 mIsNewIntent = false; 433 } 434 435 @Override 436 protected void onPause() { 437 super.onPause(); 438 dismissPreview(mPreviousView); 439 dismissPreview(mNextView); 440 mDragController.cancelDrag(); 441 } 442 443 @Override 444 public Object onRetainNonConfigurationInstance() { 445 // Flag the loader to stop early before switching 446 mModel.stopLoader(); 447 448 if (PROFILE_ROTATE) { 449 android.os.Debug.startMethodTracing("/sdcard/launcher-rotate"); 450 } 451 return null; 452 } 453 454 private boolean acceptFilter() { 455 final InputMethodManager inputManager = (InputMethodManager) 456 getSystemService(Context.INPUT_METHOD_SERVICE); 457 return !inputManager.isFullscreenMode(); 458 } 459 460 @Override 461 public boolean onKeyDown(int keyCode, KeyEvent event) { 462 boolean handled = super.onKeyDown(keyCode, event); 463 if (!handled && acceptFilter() && keyCode != KeyEvent.KEYCODE_ENTER) { 464 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, 465 keyCode, event); 466 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { 467 // something usable has been typed - start a search 468 // the typed text will be retrieved and cleared by 469 // showSearchDialog() 470 // If there are multiple keystrokes before the search dialog takes focus, 471 // onSearchRequested() will be called for every keystroke, 472 // but it is idempotent, so it's fine. 473 return onSearchRequested(); 474 } 475 } 476 477 return handled; 478 } 479 480 private String getTypedText() { 481 return mDefaultKeySsb.toString(); 482 } 483 484 private void clearTypedText() { 485 mDefaultKeySsb.clear(); 486 mDefaultKeySsb.clearSpans(); 487 Selection.setSelection(mDefaultKeySsb, 0); 488 } 489 490 /** 491 * Restores the previous state, if it exists. 492 * 493 * @param savedState The previous state. 494 */ 495 private void restoreState(Bundle savedState) { 496 if (savedState == null) { 497 return; 498 } 499 500 final boolean allApps = savedState.getBoolean(RUNTIME_STATE_ALL_APPS_FOLDER, false); 501 if (allApps) { 502 showAllApps(false); 503 } 504 505 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); 506 if (currentScreen > -1) { 507 mWorkspace.setCurrentScreen(currentScreen); 508 } 509 510 final int addScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); 511 if (addScreen > -1) { 512 mAddItemCellInfo = new CellLayout.CellInfo(); 513 final CellLayout.CellInfo addItemCellInfo = mAddItemCellInfo; 514 addItemCellInfo.valid = true; 515 addItemCellInfo.screen = addScreen; 516 addItemCellInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); 517 addItemCellInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); 518 addItemCellInfo.spanX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_X); 519 addItemCellInfo.spanY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SPAN_Y); 520 addItemCellInfo.findVacantCellsFromOccupied( 521 savedState.getBooleanArray(RUNTIME_STATE_PENDING_ADD_OCCUPIED_CELLS), 522 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_X), 523 savedState.getInt(RUNTIME_STATE_PENDING_ADD_COUNT_Y)); 524 mRestoring = true; 525 } 526 527 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); 528 if (renameFolder) { 529 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); 530 mFolderInfo = mModel.getFolderById(this, mFolders, id); 531 mRestoring = true; 532 } 533 } 534 535 /** 536 * Finds all the views we need and configure them properly. 537 */ 538 private void setupViews() { 539 DragController dragController = mDragController; 540 541 DragLayer dragLayer = (DragLayer) findViewById(R.id.drag_layer); 542 dragLayer.setDragController(dragController); 543 544 mAllAppsGrid = (AllAppsView)dragLayer.findViewById(R.id.all_apps_view); 545 mAllAppsGrid.setLauncher(this); 546 mAllAppsGrid.setDragController(dragController); 547 mAllAppsGrid.setWillNotDraw(false); // We don't want a hole punched in our window. 548 // Manage focusability manually since this thing is always visible 549 mAllAppsGrid.setFocusable(false); 550 551 mWorkspace = (Workspace) dragLayer.findViewById(R.id.workspace); 552 final Workspace workspace = mWorkspace; 553 554 DeleteZone deleteZone = (DeleteZone) dragLayer.findViewById(R.id.delete_zone); 555 mDeleteZone = deleteZone; 556 557 mHandleView = (HandleView) findViewById(R.id.all_apps_button); 558 mHandleView.setLauncher(this); 559 mHandleView.setOnClickListener(this); 560 561 mPreviousView = (ImageView) dragLayer.findViewById(R.id.previous_screen); 562 mNextView = (ImageView) dragLayer.findViewById(R.id.next_screen); 563 564 Drawable previous = mPreviousView.getDrawable(); 565 Drawable next = mNextView.getDrawable(); 566 mWorkspace.setIndicators(previous, next); 567 568 mPreviousView.setHapticFeedbackEnabled(false); 569 mPreviousView.setOnLongClickListener(this); 570 mNextView.setHapticFeedbackEnabled(false); 571 mNextView.setOnLongClickListener(this); 572 573 workspace.setOnLongClickListener(this); 574 workspace.setDragController(dragController); 575 workspace.setLauncher(this); 576 577 deleteZone.setLauncher(this); 578 deleteZone.setDragController(dragController); 579 deleteZone.setHandle(mHandleView); 580 581 dragController.setDragScoller(workspace); 582 dragController.setDragListener(deleteZone); 583 dragController.setScrollView(dragLayer); 584 585 // The order here is bottom to top. 586 dragController.addDropTarget(workspace); 587 dragController.addDropTarget(deleteZone); 588 } 589 590 @SuppressWarnings({"UnusedDeclaration"}) 591 public void previousScreen(View v) { 592 mWorkspace.scrollLeft(); 593 } 594 595 @SuppressWarnings({"UnusedDeclaration"}) 596 public void nextScreen(View v) { 597 mWorkspace.scrollRight(); 598 } 599 600 /** 601 * Creates a view representing a shortcut. 602 * 603 * @param info The data structure describing the shortcut. 604 * 605 * @return A View inflated from R.layout.application. 606 */ 607 View createShortcut(ApplicationInfo info) { 608 return createShortcut(R.layout.application, 609 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentScreen()), info); 610 } 611 612 /** 613 * Creates a view representing a shortcut inflated from the specified resource. 614 * 615 * @param layoutResId The id of the XML layout used to create the shortcut. 616 * @param parent The group the shortcut belongs to. 617 * @param info The data structure describing the shortcut. 618 * 619 * @return A View inflated from layoutResId. 620 */ 621 View createShortcut(int layoutResId, ViewGroup parent, ApplicationInfo info) { 622 TextView favorite = (TextView) mInflater.inflate(layoutResId, parent, false); 623 624 if (info.icon == null) { 625 info.icon = AppInfoCache.getIconDrawable(getPackageManager(), info); 626 } 627 if (!info.filtered) { 628 info.icon = Utilities.createIconThumbnail(info.icon, this); 629 info.filtered = true; 630 } 631 632 favorite.setCompoundDrawablesWithIntrinsicBounds(null, info.icon, null, null); 633 favorite.setText(info.title); 634 favorite.setTag(info); 635 favorite.setOnClickListener(this); 636 637 return favorite; 638 } 639 640 /** 641 * Add an application shortcut to the workspace. 642 * 643 * @param data The intent describing the application. 644 * @param cellInfo The position on screen where to create the shortcut. 645 */ 646 void completeAddApplication(Context context, Intent data, CellLayout.CellInfo cellInfo) { 647 cellInfo.screen = mWorkspace.getCurrentScreen(); 648 if (!findSingleSlot(cellInfo)) return; 649 650 final ApplicationInfo info = infoFromApplicationIntent(context, data); 651 if (info != null) { 652 mWorkspace.addApplicationShortcut(info, cellInfo, isWorkspaceLocked()); 653 } 654 } 655 656 private static ApplicationInfo infoFromApplicationIntent(Context context, Intent data) { 657 ComponentName component = data.getComponent(); 658 PackageManager packageManager = context.getPackageManager(); 659 ActivityInfo activityInfo = null; 660 try { 661 activityInfo = packageManager.getActivityInfo(component, 0 /* no flags */); 662 } catch (NameNotFoundException e) { 663 Log.e(TAG, "Couldn't find ActivityInfo for selected application", e); 664 } 665 666 if (activityInfo != null) { 667 ApplicationInfo itemInfo = new ApplicationInfo(); 668 669 itemInfo.title = activityInfo.loadLabel(packageManager); 670 if (itemInfo.title == null) { 671 itemInfo.title = activityInfo.name; 672 } 673 674 itemInfo.setActivity(component, Intent.FLAG_ACTIVITY_NEW_TASK | 675 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 676 itemInfo.icon = activityInfo.loadIcon(packageManager); 677 itemInfo.container = ItemInfo.NO_ID; 678 679 return itemInfo; 680 } 681 682 return null; 683 } 684 685 /** 686 * Add a shortcut to the workspace. 687 * 688 * @param data The intent describing the shortcut. 689 * @param cellInfo The position on screen where to create the shortcut. 690 */ 691 private void completeAddShortcut(Intent data, CellLayout.CellInfo cellInfo) { 692 cellInfo.screen = mWorkspace.getCurrentScreen(); 693 if (!findSingleSlot(cellInfo)) return; 694 695 final ApplicationInfo info = addShortcut(this, data, cellInfo, false); 696 697 if (!mRestoring) { 698 final View view = createShortcut(info); 699 mWorkspace.addInCurrentScreen(view, cellInfo.cellX, cellInfo.cellY, 1, 1, 700 isWorkspaceLocked()); 701 } 702 } 703 704 705 /** 706 * Add a widget to the workspace. 707 * 708 * @param data The intent describing the appWidgetId. 709 * @param cellInfo The position on screen where to create the widget. 710 */ 711 private void completeAddAppWidget(Intent data, CellLayout.CellInfo cellInfo) { 712 Bundle extras = data.getExtras(); 713 int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 714 715 if (LOGD) Log.d(TAG, "dumping extras content=" + extras.toString()); 716 717 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 718 719 // Calculate the grid spans needed to fit this widget 720 CellLayout layout = (CellLayout) mWorkspace.getChildAt(cellInfo.screen); 721 int[] spans = layout.rectToCell(appWidgetInfo.minWidth, appWidgetInfo.minHeight); 722 723 // Try finding open space on Launcher screen 724 final int[] xy = mCellCoordinates; 725 if (!findSlot(cellInfo, xy, spans[0], spans[1])) { 726 if (appWidgetId != -1) mAppWidgetHost.deleteAppWidgetId(appWidgetId); 727 return; 728 } 729 730 // Build Launcher-specific widget info and save to database 731 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId); 732 launcherInfo.spanX = spans[0]; 733 launcherInfo.spanY = spans[1]; 734 735 LauncherModel.addItemToDatabase(this, launcherInfo, 736 LauncherSettings.Favorites.CONTAINER_DESKTOP, 737 mWorkspace.getCurrentScreen(), xy[0], xy[1], false); 738 739 if (!mRestoring) { 740 mDesktopItems.add(launcherInfo); 741 742 // Perform actual inflation because we're live 743 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 744 745 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); 746 launcherInfo.hostView.setTag(launcherInfo); 747 748 mWorkspace.addInCurrentScreen(launcherInfo.hostView, xy[0], xy[1], 749 launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); 750 } 751 } 752 753 public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { 754 mDesktopItems.remove(launcherInfo); 755 launcherInfo.hostView = null; 756 } 757 758 public LauncherAppWidgetHost getAppWidgetHost() { 759 return mAppWidgetHost; 760 } 761 762 static ApplicationInfo addShortcut(Context context, Intent data, 763 CellLayout.CellInfo cellInfo, boolean notify) { 764 765 final ApplicationInfo info = infoFromShortcutIntent(context, data); 766 LauncherModel.addItemToDatabase(context, info, LauncherSettings.Favorites.CONTAINER_DESKTOP, 767 cellInfo.screen, cellInfo.cellX, cellInfo.cellY, notify); 768 769 return info; 770 } 771 772 private static ApplicationInfo infoFromShortcutIntent(Context context, Intent data) { 773 Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); 774 String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 775 Bitmap bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); 776 777 Drawable icon = null; 778 boolean filtered = false; 779 boolean customIcon = false; 780 ShortcutIconResource iconResource = null; 781 782 if (bitmap != null) { 783 icon = new FastBitmapDrawable(Utilities.createBitmapThumbnail(bitmap, context)); 784 filtered = true; 785 customIcon = true; 786 } else { 787 Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); 788 if (extra != null && extra instanceof ShortcutIconResource) { 789 try { 790 iconResource = (ShortcutIconResource) extra; 791 final PackageManager packageManager = context.getPackageManager(); 792 Resources resources = packageManager.getResourcesForApplication( 793 iconResource.packageName); 794 final int id = resources.getIdentifier(iconResource.resourceName, null, null); 795 icon = resources.getDrawable(id); 796 } catch (Exception e) { 797 Log.w(TAG, "Could not load shortcut icon: " + extra); 798 } 799 } 800 } 801 802 if (icon == null) { 803 icon = context.getPackageManager().getDefaultActivityIcon(); 804 } 805 806 final ApplicationInfo info = new ApplicationInfo(); 807 info.icon = icon; 808 info.filtered = filtered; 809 info.title = name; 810 info.intent = intent; 811 info.customIcon = customIcon; 812 info.iconResource = iconResource; 813 814 return info; 815 } 816 817 void closeSystemDialogs() { 818 closeAllApps(false); 819 getWindow().closeAllPanels(); 820 821 try { 822 dismissDialog(DIALOG_CREATE_SHORTCUT); 823 // Unlock the workspace if the dialog was showing 824 } catch (Exception e) { 825 // An exception is thrown if the dialog is not visible, which is fine 826 } 827 828 try { 829 dismissDialog(DIALOG_RENAME_FOLDER); 830 // Unlock the workspace if the dialog was showing 831 } catch (Exception e) { 832 // An exception is thrown if the dialog is not visible, which is fine 833 } 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 closeSystemDialogs(); 843 844 // Whatever we were doing is hereby canceled. 845 mWaitingForResult = false; 846 847 // Set this flag so that onResume knows to close the search dialog if it's open, 848 // because this was a new intent (thus a press of 'home' or some such) rather than 849 // for example onResume being called when the user pressed the 'back' button. 850 mIsNewIntent = true; 851 852 if (!mWorkspace.isDefaultScreenShowing()) { 853 mWorkspace.moveToDefaultScreen(); 854 } 855 856 closeAllApps(false); 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_BACK: 1322 return true; 1323 case KeyEvent.KEYCODE_HOME: 1324 return true; 1325 case KeyEvent.KEYCODE_VOLUME_DOWN: 1326 if (SystemProperties.getInt("launcher2.dumpstate", 0) != 0) { 1327 dumpState(); 1328 return true; 1329 } 1330 break; 1331 } 1332 } else if (event.getAction() == KeyEvent.ACTION_UP) { 1333 switch (event.getKeyCode()) { 1334 case KeyEvent.KEYCODE_BACK: 1335 if (!event.isCanceled()) { 1336 mWorkspace.dispatchKeyEvent(event); 1337 if (isAllAppsVisible()) { 1338 closeAllApps(true); 1339 } else { 1340 closeFolder(); 1341 } 1342 dismissPreview(mPreviousView); 1343 dismissPreview(mNextView); 1344 } 1345 return true; 1346 case KeyEvent.KEYCODE_HOME: 1347 return true; 1348 } 1349 } 1350 1351 return super.dispatchKeyEvent(event); 1352 } 1353 1354 private void closeFolder() { 1355 Folder folder = mWorkspace.getOpenFolder(); 1356 if (folder != null) { 1357 closeFolder(folder); 1358 } 1359 } 1360 1361 void closeFolder(Folder folder) { 1362 folder.getInfo().opened = false; 1363 ViewGroup parent = (ViewGroup) folder.getParent(); 1364 if (parent != null) { 1365 parent.removeView(folder); 1366 if (folder instanceof DropTarget) { 1367 // Live folders aren't DropTargets. 1368 mDragController.removeDropTarget((DropTarget)folder); 1369 } 1370 } 1371 folder.onClose(); 1372 } 1373 1374 /** 1375 * Re-listen when widgets are reset. 1376 */ 1377 private void onAppWidgetReset() { 1378 mAppWidgetHost.startListening(); 1379 } 1380 1381 /** 1382 * Go through the and disconnect any of the callbacks in the drawables and the views or we 1383 * leak the previous Home screen on orientation change. 1384 */ 1385 private void unbindDesktopItems() { 1386 for (ItemInfo item: mDesktopItems) { 1387 item.unbind(); 1388 } 1389 } 1390 1391 /** 1392 * Launches the intent referred by the clicked shortcut. 1393 * 1394 * @param v The view representing the clicked shortcut. 1395 */ 1396 public void onClick(View v) { 1397 Object tag = v.getTag(); 1398 if (tag instanceof ApplicationInfo) { 1399 // Open shortcut 1400 final Intent intent = ((ApplicationInfo) tag).intent; 1401 startActivitySafely(intent); 1402 } else if (tag instanceof FolderInfo) { 1403 handleFolderClick((FolderInfo) tag); 1404 } else if (v == mHandleView) { 1405 if (isAllAppsVisible()) { 1406 closeAllApps(true); 1407 } else { 1408 showAllApps(true); 1409 } 1410 } 1411 } 1412 1413 void startActivitySafely(Intent intent) { 1414 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1415 try { 1416 startActivity(intent); 1417 } catch (ActivityNotFoundException e) { 1418 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1419 } catch (SecurityException e) { 1420 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1421 Log.e(TAG, "Launcher does not have the permission to launch " + intent + 1422 ". Make sure to create a MAIN intent-filter for the corresponding activity " + 1423 "or use the exported attribute for this activity.", e); 1424 } 1425 } 1426 1427 private void handleFolderClick(FolderInfo folderInfo) { 1428 if (!folderInfo.opened) { 1429 // Close any open folder 1430 closeFolder(); 1431 // Open the requested folder 1432 openFolder(folderInfo); 1433 } else { 1434 // Find the open folder... 1435 Folder openFolder = mWorkspace.getFolderForTag(folderInfo); 1436 int folderScreen; 1437 if (openFolder != null) { 1438 folderScreen = mWorkspace.getScreenForView(openFolder); 1439 // .. and close it 1440 closeFolder(openFolder); 1441 if (folderScreen != mWorkspace.getCurrentScreen()) { 1442 // Close any folder open on the current screen 1443 closeFolder(); 1444 // Pull the folder onto this screen 1445 openFolder(folderInfo); 1446 } 1447 } 1448 } 1449 } 1450 1451 /** 1452 * Opens the user fodler described by the specified tag. The opening of the folder 1453 * is animated relative to the specified View. If the View is null, no animation 1454 * is played. 1455 * 1456 * @param folderInfo The FolderInfo describing the folder to open. 1457 */ 1458 private void openFolder(FolderInfo folderInfo) { 1459 Folder openFolder; 1460 1461 if (folderInfo instanceof UserFolderInfo) { 1462 openFolder = UserFolder.fromXml(this); 1463 } else if (folderInfo instanceof LiveFolderInfo) { 1464 openFolder = com.android.launcher2.LiveFolder.fromXml(this, folderInfo); 1465 } else { 1466 return; 1467 } 1468 1469 openFolder.setDragController(mDragController); 1470 openFolder.setLauncher(this); 1471 1472 openFolder.bind(folderInfo); 1473 folderInfo.opened = true; 1474 1475 mWorkspace.addInScreen(openFolder, folderInfo.screen, 0, 0, 4, 4); 1476 openFolder.onOpen(); 1477 } 1478 1479 public boolean onLongClick(View v) { 1480 switch (v.getId()) { 1481 case R.id.previous_screen: 1482 if (!isAllAppsVisible()) { 1483 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1484 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1485 showPreviousPreview(v); 1486 } 1487 return true; 1488 case R.id.next_screen: 1489 if (!isAllAppsVisible()) { 1490 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1491 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1492 showNextPreview(v); 1493 } 1494 return true; 1495 } 1496 1497 if (isWorkspaceLocked()) { 1498 return false; 1499 } 1500 1501 if (!(v instanceof CellLayout)) { 1502 v = (View) v.getParent(); 1503 } 1504 1505 CellLayout.CellInfo cellInfo = (CellLayout.CellInfo) v.getTag(); 1506 1507 // This happens when long clicking an item with the dpad/trackball 1508 if (cellInfo == null) { 1509 return true; 1510 } 1511 1512 if (mWorkspace.allowLongPress()) { 1513 if (cellInfo.cell == null) { 1514 if (cellInfo.valid) { 1515 // User long pressed on empty space 1516 mWorkspace.setAllowLongPress(false); 1517 showAddDialog(cellInfo); 1518 } 1519 } else { 1520 if (!(cellInfo.cell instanceof Folder)) { 1521 // User long pressed on an item 1522 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1523 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1524 mWorkspace.startDrag(cellInfo); 1525 } 1526 } 1527 } 1528 return true; 1529 } 1530 1531 @SuppressWarnings({"unchecked"}) 1532 private void dismissPreview(final View v) { 1533 final PopupWindow window = (PopupWindow) v.getTag(); 1534 if (window != null) { 1535 window.setOnDismissListener(new PopupWindow.OnDismissListener() { 1536 public void onDismiss() { 1537 ViewGroup group = (ViewGroup) v.getTag(R.id.workspace); 1538 int count = group.getChildCount(); 1539 for (int i = 0; i < count; i++) { 1540 ((ImageView) group.getChildAt(i)).setImageDrawable(null); 1541 } 1542 ArrayList<Bitmap> bitmaps = (ArrayList<Bitmap>) v.getTag(R.id.icon); 1543 for (Bitmap bitmap : bitmaps) bitmap.recycle(); 1544 1545 v.setTag(R.id.workspace, null); 1546 v.setTag(R.id.icon, null); 1547 window.setOnDismissListener(null); 1548 } 1549 }); 1550 window.dismiss(); 1551 } 1552 v.setTag(null); 1553 } 1554 1555 private void showPreviousPreview(View anchor) { 1556 int current = mWorkspace.getCurrentScreen(); 1557 if (current <= 0) return; 1558 1559 showPreviews(anchor, 0, mWorkspace.getChildCount()); 1560 } 1561 1562 private void showNextPreview(View anchor) { 1563 int current = mWorkspace.getCurrentScreen(); 1564 if (current >= mWorkspace.getChildCount() - 1) return; 1565 1566 showPreviews(anchor, 0, mWorkspace.getChildCount()); 1567 } 1568 1569 private void showPreviews(final View anchor, int start, int end) { 1570 Resources resources = getResources(); 1571 1572 Workspace workspace = mWorkspace; 1573 CellLayout cell = ((CellLayout) workspace.getChildAt(start)); 1574 1575 float max = workspace.getChildCount(); 1576 1577 Rect r = new Rect(); 1578 resources.getDrawable(R.drawable.preview_background).getPadding(r); 1579 int extraW = (int) ((r.left + r.right) * max); 1580 int extraH = r.top + r.bottom; 1581 1582 int aW = cell.getWidth() - extraW; 1583 float w = aW / max; 1584 1585 int width = cell.getWidth(); 1586 int height = cell.getHeight(); 1587 int x = cell.getLeftPadding(); 1588 int y = cell.getTopPadding(); 1589 width -= (x + cell.getRightPadding()); 1590 height -= (y + cell.getBottomPadding()); 1591 1592 float scale = w / width; 1593 1594 int count = end - start; 1595 1596 final float sWidth = width * scale; 1597 float sHeight = height * scale; 1598 1599 LinearLayout preview = new LinearLayout(this); 1600 1601 PreviewTouchHandler handler = new PreviewTouchHandler(anchor); 1602 ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>(count); 1603 1604 for (int i = start; i < end; i++) { 1605 ImageView image = new ImageView(this); 1606 cell = (CellLayout) workspace.getChildAt(i); 1607 1608 Bitmap bitmap = Bitmap.createBitmap((int) sWidth, (int) sHeight, 1609 Bitmap.Config.ARGB_8888); 1610 1611 Canvas c = new Canvas(bitmap); 1612 c.scale(scale, scale); 1613 c.translate(-cell.getLeftPadding(), -cell.getTopPadding()); 1614 cell.dispatchDraw(c); 1615 1616 image.setBackgroundDrawable(resources.getDrawable(R.drawable.preview_background)); 1617 image.setImageBitmap(bitmap); 1618 image.setTag(i); 1619 image.setOnClickListener(handler); 1620 image.setOnFocusChangeListener(handler); 1621 image.setFocusable(true); 1622 if (i == mWorkspace.getCurrentScreen()) image.requestFocus(); 1623 1624 preview.addView(image, 1625 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 1626 1627 bitmaps.add(bitmap); 1628 } 1629 1630 PopupWindow p = new PopupWindow(this); 1631 p.setContentView(preview); 1632 p.setWidth((int) (sWidth * count + extraW)); 1633 p.setHeight((int) (sHeight + extraH)); 1634 p.setAnimationStyle(R.style.AnimationPreview); 1635 p.setOutsideTouchable(true); 1636 p.setFocusable(true); 1637 p.setBackgroundDrawable(new ColorDrawable(0)); 1638 p.showAsDropDown(anchor, 0, 0); 1639 1640 p.setOnDismissListener(new PopupWindow.OnDismissListener() { 1641 public void onDismiss() { 1642 dismissPreview(anchor); 1643 } 1644 }); 1645 1646 anchor.setTag(p); 1647 anchor.setTag(R.id.workspace, preview); 1648 anchor.setTag(R.id.icon, bitmaps); 1649 } 1650 1651 class PreviewTouchHandler implements View.OnClickListener, Runnable, View.OnFocusChangeListener { 1652 private final View mAnchor; 1653 1654 public PreviewTouchHandler(View anchor) { 1655 mAnchor = anchor; 1656 } 1657 1658 public void onClick(View v) { 1659 mWorkspace.snapToScreen((Integer) v.getTag()); 1660 v.post(this); 1661 } 1662 1663 public void run() { 1664 dismissPreview(mAnchor); 1665 } 1666 1667 public void onFocusChange(View v, boolean hasFocus) { 1668 if (hasFocus) { 1669 mWorkspace.snapToScreen((Integer) v.getTag()); 1670 } 1671 } 1672 } 1673 1674 View getDrawerHandle() { 1675 return mHandleView; 1676 } 1677 1678 Workspace getWorkspace() { 1679 return mWorkspace; 1680 } 1681 1682 @Override 1683 protected Dialog onCreateDialog(int id) { 1684 switch (id) { 1685 case DIALOG_CREATE_SHORTCUT: 1686 return new CreateShortcut().createDialog(); 1687 case DIALOG_RENAME_FOLDER: 1688 return new RenameFolder().createDialog(); 1689 } 1690 1691 return super.onCreateDialog(id); 1692 } 1693 1694 @Override 1695 protected void onPrepareDialog(int id, Dialog dialog) { 1696 switch (id) { 1697 case DIALOG_CREATE_SHORTCUT: 1698 break; 1699 case DIALOG_RENAME_FOLDER: 1700 if (mFolderInfo != null) { 1701 EditText input = (EditText) dialog.findViewById(R.id.folder_name); 1702 final CharSequence text = mFolderInfo.title; 1703 input.setText(text); 1704 input.setSelection(0, text.length()); 1705 } 1706 break; 1707 } 1708 } 1709 1710 void showRenameDialog(FolderInfo info) { 1711 mFolderInfo = info; 1712 mWaitingForResult = true; 1713 showDialog(DIALOG_RENAME_FOLDER); 1714 } 1715 1716 private void showAddDialog(CellLayout.CellInfo cellInfo) { 1717 mAddItemCellInfo = cellInfo; 1718 mWaitingForResult = true; 1719 showDialog(DIALOG_CREATE_SHORTCUT); 1720 } 1721 1722 private void pickShortcut(int requestCode, int title) { 1723 Bundle bundle = new Bundle(); 1724 1725 ArrayList<String> shortcutNames = new ArrayList<String>(); 1726 shortcutNames.add(getString(R.string.group_applications)); 1727 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); 1728 1729 ArrayList<ShortcutIconResource> shortcutIcons = new ArrayList<ShortcutIconResource>(); 1730 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, 1731 R.drawable.ic_launcher_application)); 1732 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); 1733 1734 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1735 pickIntent.putExtra(Intent.EXTRA_INTENT, new Intent(Intent.ACTION_CREATE_SHORTCUT)); 1736 pickIntent.putExtra(Intent.EXTRA_TITLE, getText(title)); 1737 pickIntent.putExtras(bundle); 1738 1739 startActivityForResult(pickIntent, requestCode); 1740 } 1741 1742 private class RenameFolder { 1743 private EditText mInput; 1744 1745 Dialog createDialog() { 1746 mWaitingForResult = true; 1747 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); 1748 mInput = (EditText) layout.findViewById(R.id.folder_name); 1749 1750 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); 1751 builder.setIcon(0); 1752 builder.setTitle(getString(R.string.rename_folder_title)); 1753 builder.setCancelable(true); 1754 builder.setOnCancelListener(new Dialog.OnCancelListener() { 1755 public void onCancel(DialogInterface dialog) { 1756 cleanup(); 1757 } 1758 }); 1759 builder.setNegativeButton(getString(R.string.cancel_action), 1760 new Dialog.OnClickListener() { 1761 public void onClick(DialogInterface dialog, int which) { 1762 cleanup(); 1763 } 1764 } 1765 ); 1766 builder.setPositiveButton(getString(R.string.rename_action), 1767 new Dialog.OnClickListener() { 1768 public void onClick(DialogInterface dialog, int which) { 1769 changeFolderName(); 1770 } 1771 } 1772 ); 1773 builder.setView(layout); 1774 1775 final AlertDialog dialog = builder.create(); 1776 dialog.setOnShowListener(new DialogInterface.OnShowListener() { 1777 public void onShow(DialogInterface dialog) { 1778 mInput.requestFocus(); 1779 InputMethodManager inputManager = (InputMethodManager) 1780 getSystemService(Context.INPUT_METHOD_SERVICE); 1781 inputManager.showSoftInput(mInput, 0); 1782 } 1783 }); 1784 1785 return dialog; 1786 } 1787 1788 private void changeFolderName() { 1789 final String name = mInput.getText().toString(); 1790 if (!TextUtils.isEmpty(name)) { 1791 // Make sure we have the right folder info 1792 mFolderInfo = mFolders.get(mFolderInfo.id); 1793 mFolderInfo.title = name; 1794 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo); 1795 1796 if (mWorkspaceLoading) { 1797 lockAllApps(); 1798 mModel.setWorkspaceDirty(); 1799 mModel.startLoader(Launcher.this, false); 1800 } else { 1801 final FolderIcon folderIcon = (FolderIcon) 1802 mWorkspace.getViewForTag(mFolderInfo); 1803 if (folderIcon != null) { 1804 folderIcon.setText(name); 1805 getWorkspace().requestLayout(); 1806 } else { 1807 lockAllApps(); 1808 mModel.setWorkspaceDirty(); 1809 mWorkspaceLoading = true; 1810 mModel.startLoader(Launcher.this, false); 1811 } 1812 } 1813 } 1814 cleanup(); 1815 } 1816 1817 private void cleanup() { 1818 dismissDialog(DIALOG_RENAME_FOLDER); 1819 mWaitingForResult = false; 1820 mFolderInfo = null; 1821 } 1822 } 1823 1824 boolean isAllAppsVisible() { 1825 return mAllAppsGrid.isVisible(); 1826 } 1827 1828 boolean isAllAppsOpaque() { 1829 return mAllAppsGrid.isOpaque(); 1830 } 1831 1832 void showAllApps(boolean animated) { 1833 mAllAppsGrid.zoom(1.0f, animated); 1834 //mWorkspace.hide(); 1835 1836 mWorkspace.startFading(false); 1837 1838 mAllAppsGrid.setFocusable(true); 1839 mAllAppsGrid.requestFocus(); 1840 1841 // TODO: fade these two too 1842 mDeleteZone.setVisibility(View.GONE); 1843 //mHandleView.setVisibility(View.GONE); 1844 } 1845 1846 void closeAllApps(boolean animated) { 1847 if (mAllAppsGrid.isVisible()) { 1848 mAllAppsGrid.zoom(0.0f, animated); 1849 mAllAppsGrid.setFocusable(false); 1850 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); 1851 mWorkspace.startFading(true); 1852 1853 // TODO: fade these two too 1854 /* 1855 mDeleteZone.setVisibility(View.VISIBLE); 1856 mHandleView.setVisibility(View.VISIBLE); 1857 */ 1858 } 1859 } 1860 1861 void lockAllApps() { 1862 // TODO 1863 } 1864 1865 void unlockAllApps() { 1866 // TODO 1867 } 1868 1869 /** 1870 * Displays the shortcut creation dialog and launches, if necessary, the 1871 * appropriate activity. 1872 */ 1873 private class CreateShortcut implements DialogInterface.OnClickListener, 1874 DialogInterface.OnCancelListener, DialogInterface.OnDismissListener, 1875 DialogInterface.OnShowListener { 1876 1877 private AddAdapter mAdapter; 1878 1879 Dialog createDialog() { 1880 mWaitingForResult = true; 1881 1882 mAdapter = new AddAdapter(Launcher.this); 1883 1884 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); 1885 builder.setTitle(getString(R.string.menu_item_add_item)); 1886 builder.setAdapter(mAdapter, this); 1887 1888 builder.setInverseBackgroundForced(true); 1889 1890 AlertDialog dialog = builder.create(); 1891 dialog.setOnCancelListener(this); 1892 dialog.setOnDismissListener(this); 1893 dialog.setOnShowListener(this); 1894 1895 return dialog; 1896 } 1897 1898 public void onCancel(DialogInterface dialog) { 1899 mWaitingForResult = false; 1900 cleanup(); 1901 } 1902 1903 public void onDismiss(DialogInterface dialog) { 1904 } 1905 1906 private void cleanup() { 1907 dismissDialog(DIALOG_CREATE_SHORTCUT); 1908 } 1909 1910 /** 1911 * Handle the action clicked in the "Add to home" dialog. 1912 */ 1913 public void onClick(DialogInterface dialog, int which) { 1914 Resources res = getResources(); 1915 cleanup(); 1916 1917 switch (which) { 1918 case AddAdapter.ITEM_SHORTCUT: { 1919 // Insert extra item to handle picking application 1920 pickShortcut(REQUEST_PICK_SHORTCUT, R.string.title_select_shortcut); 1921 break; 1922 } 1923 1924 case AddAdapter.ITEM_APPWIDGET: { 1925 int appWidgetId = Launcher.this.mAppWidgetHost.allocateAppWidgetId(); 1926 1927 Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK); 1928 pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 1929 // add the search widget 1930 ArrayList<AppWidgetProviderInfo> customInfo = 1931 new ArrayList<AppWidgetProviderInfo>(); 1932 AppWidgetProviderInfo info = new AppWidgetProviderInfo(); 1933 info.provider = new ComponentName(getPackageName(), "XXX.YYY"); 1934 info.label = getString(R.string.group_search); 1935 info.icon = R.drawable.ic_search_widget; 1936 customInfo.add(info); 1937 pickIntent.putParcelableArrayListExtra( 1938 AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo); 1939 ArrayList<Bundle> customExtras = new ArrayList<Bundle>(); 1940 Bundle b = new Bundle(); 1941 b.putString(EXTRA_CUSTOM_WIDGET, SEARCH_WIDGET); 1942 customExtras.add(b); 1943 pickIntent.putParcelableArrayListExtra( 1944 AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras); 1945 // start the pick activity 1946 startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET); 1947 break; 1948 } 1949 1950 case AddAdapter.ITEM_LIVE_FOLDER: { 1951 // Insert extra item to handle inserting folder 1952 Bundle bundle = new Bundle(); 1953 1954 ArrayList<String> shortcutNames = new ArrayList<String>(); 1955 shortcutNames.add(res.getString(R.string.group_folder)); 1956 bundle.putStringArrayList(Intent.EXTRA_SHORTCUT_NAME, shortcutNames); 1957 1958 ArrayList<ShortcutIconResource> shortcutIcons = 1959 new ArrayList<ShortcutIconResource>(); 1960 shortcutIcons.add(ShortcutIconResource.fromContext(Launcher.this, 1961 R.drawable.ic_launcher_folder)); 1962 bundle.putParcelableArrayList(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, shortcutIcons); 1963 1964 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1965 pickIntent.putExtra(Intent.EXTRA_INTENT, 1966 new Intent(LiveFolders.ACTION_CREATE_LIVE_FOLDER)); 1967 pickIntent.putExtra(Intent.EXTRA_TITLE, 1968 getText(R.string.title_select_live_folder)); 1969 pickIntent.putExtras(bundle); 1970 1971 startActivityForResult(pickIntent, REQUEST_PICK_LIVE_FOLDER); 1972 break; 1973 } 1974 1975 case AddAdapter.ITEM_WALLPAPER: { 1976 startWallpaper(); 1977 break; 1978 } 1979 } 1980 } 1981 1982 public void onShow(DialogInterface dialog) { 1983 } 1984 } 1985 1986 /** 1987 * Receives notifications when applications are added/removed. 1988 */ 1989 private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver { 1990 @Override 1991 public void onReceive(Context context, Intent intent) { 1992 closeSystemDialogs(); 1993 } 1994 } 1995 1996 /** 1997 * Receives notifications whenever the appwidgets are reset. 1998 */ 1999 private class AppWidgetResetObserver extends ContentObserver { 2000 public AppWidgetResetObserver() { 2001 super(new Handler()); 2002 } 2003 2004 @Override 2005 public void onChange(boolean selfChange) { 2006 onAppWidgetReset(); 2007 } 2008 } 2009 2010 /** 2011 * Implementation of the method from LauncherModel.Callbacks. 2012 */ 2013 public int getCurrentWorkspaceScreen() { 2014 return mWorkspace.getCurrentScreen(); 2015 } 2016 2017 /** 2018 * Refreshes the shortcuts shown on the workspace. 2019 * 2020 * Implementation of the method from LauncherModel.Callbacks. 2021 */ 2022 public void startBinding() { 2023 final Workspace workspace = mWorkspace; 2024 int count = workspace.getChildCount(); 2025 for (int i = 0; i < count; i++) { 2026 // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate(). 2027 ((ViewGroup) workspace.getChildAt(i)).removeAllViewsInLayout(); 2028 } 2029 2030 if (DEBUG_USER_INTERFACE) { 2031 android.widget.Button finishButton = new android.widget.Button(this); 2032 finishButton.setText("Finish"); 2033 workspace.addInScreen(finishButton, 1, 0, 0, 1, 1); 2034 2035 finishButton.setOnClickListener(new android.widget.Button.OnClickListener() { 2036 public void onClick(View v) { 2037 finish(); 2038 } 2039 }); 2040 } 2041 } 2042 2043 /** 2044 * Bind the items start-end from the list. 2045 * 2046 * Implementation of the method from LauncherModel.Callbacks. 2047 */ 2048 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { 2049 2050 final Workspace workspace = mWorkspace; 2051 2052 for (int i=start; i<end; i++) { 2053 final ItemInfo item = shortcuts.get(i); 2054 mDesktopItems.add(item); 2055 switch (item.itemType) { 2056 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2057 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2058 final View shortcut = createShortcut((ApplicationInfo) item); 2059 workspace.addInScreen(shortcut, item.screen, item.cellX, item.cellY, 1, 1, 2060 false); 2061 break; 2062 case LauncherSettings.Favorites.ITEM_TYPE_USER_FOLDER: 2063 final FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, 2064 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), 2065 (UserFolderInfo) item); 2066 workspace.addInScreen(newFolder, item.screen, item.cellX, item.cellY, 1, 1, 2067 false); 2068 break; 2069 case LauncherSettings.Favorites.ITEM_TYPE_LIVE_FOLDER: 2070 final FolderIcon newLiveFolder = LiveFolderIcon.fromXml( 2071 R.layout.live_folder_icon, this, 2072 (ViewGroup) workspace.getChildAt(workspace.getCurrentScreen()), 2073 (LiveFolderInfo) item); 2074 workspace.addInScreen(newLiveFolder, item.screen, item.cellX, item.cellY, 1, 1, 2075 false); 2076 break; 2077 case LauncherSettings.Favorites.ITEM_TYPE_WIDGET_SEARCH: 2078 final int screen = workspace.getCurrentScreen(); 2079 final View view = mInflater.inflate(R.layout.widget_search, 2080 (ViewGroup) workspace.getChildAt(screen), false); 2081 2082 Search search = (Search) view.findViewById(R.id.widget_search); 2083 search.setLauncher(this); 2084 2085 final Widget widget = (Widget) item; 2086 view.setTag(widget); 2087 2088 workspace.addWidget(view, widget, false); 2089 break; 2090 } 2091 } 2092 2093 workspace.requestLayout(); 2094 } 2095 2096 /** 2097 * Implementation of the method from LauncherModel.Callbacks. 2098 */ 2099 public void bindFolders(HashMap<Long, FolderInfo> folders) { 2100 mFolders.clear(); 2101 mFolders.putAll(folders); 2102 } 2103 2104 /** 2105 * Add the views for a widget to the workspace. 2106 * 2107 * Implementation of the method from LauncherModel.Callbacks. 2108 */ 2109 public void bindAppWidget(LauncherAppWidgetInfo item) { 2110 final Workspace workspace = mWorkspace; 2111 2112 final int appWidgetId = item.appWidgetId; 2113 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 2114 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 2115 2116 item.hostView.setAppWidget(appWidgetId, appWidgetInfo); 2117 item.hostView.setTag(item); 2118 2119 workspace.addInScreen(item.hostView, item.screen, item.cellX, 2120 item.cellY, item.spanX, item.spanY, false); 2121 2122 workspace.requestLayout(); 2123 2124 mDesktopItems.add(item); 2125 } 2126 2127 /** 2128 * Callback saying that there aren't any more items to bind. 2129 * 2130 * Implementation of the method from LauncherModel.Callbacks. 2131 */ 2132 public void finishBindingItems() { 2133 if (mSavedState != null) { 2134 if (!mWorkspace.hasFocus()) { 2135 mWorkspace.getChildAt(mWorkspace.getCurrentScreen()).requestFocus(); 2136 } 2137 2138 final long[] userFolders = mSavedState.getLongArray(RUNTIME_STATE_USER_FOLDERS); 2139 if (userFolders != null) { 2140 for (long folderId : userFolders) { 2141 final FolderInfo info = mFolders.get(folderId); 2142 if (info != null) { 2143 openFolder(info); 2144 } 2145 } 2146 final Folder openFolder = mWorkspace.getOpenFolder(); 2147 if (openFolder != null) { 2148 openFolder.requestFocus(); 2149 } 2150 } 2151 2152 mSavedState = null; 2153 } 2154 2155 if (mSavedInstanceState != null) { 2156 super.onRestoreInstanceState(mSavedInstanceState); 2157 mSavedInstanceState = null; 2158 } 2159 2160 mWorkspaceLoading = false; 2161 } 2162 2163 /** 2164 * Add the icons for all apps. 2165 * 2166 * Implementation of the method from LauncherModel.Callbacks. 2167 */ 2168 public void bindAllApplications(ArrayList<ApplicationInfo> apps) { 2169 mAllAppsGrid.setApps(apps); 2170 } 2171 2172 /** 2173 * A package was installed. 2174 * 2175 * Implementation of the method from LauncherModel.Callbacks. 2176 */ 2177 public void bindPackageAdded(ArrayList<ApplicationInfo> apps) { 2178 removeDialog(DIALOG_CREATE_SHORTCUT); 2179 mAllAppsGrid.addApps(apps); 2180 } 2181 2182 /** 2183 * A package was updated. 2184 * 2185 * Implementation of the method from LauncherModel.Callbacks. 2186 */ 2187 public void bindPackageUpdated(String packageName, ArrayList<ApplicationInfo> apps) { 2188 removeDialog(DIALOG_CREATE_SHORTCUT); 2189 mWorkspace.updateShortcutsForPackage(packageName); 2190 } 2191 2192 /** 2193 * A package was uninstalled. 2194 * 2195 * Implementation of the method from LauncherModel.Callbacks. 2196 */ 2197 public void bindPackageRemoved(String packageName, ArrayList<ApplicationInfo> apps) { 2198 removeDialog(DIALOG_CREATE_SHORTCUT); 2199 mWorkspace.removeShortcutsForPackage(packageName); 2200 mAllAppsGrid.removeApps(apps); 2201 } 2202 2203 /** 2204 * Prints out out state for debugging. 2205 */ 2206 public void dumpState() { 2207 Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this); 2208 Log.d(TAG, "mSavedState=" + mSavedState); 2209 Log.d(TAG, "mIsNewIntent=" + mIsNewIntent); 2210 Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading); 2211 Log.d(TAG, "mRestoring=" + mRestoring); 2212 Log.d(TAG, "mWaitingForResult=" + mWaitingForResult); 2213 Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState); 2214 Log.d(TAG, "mDesktopItems.size=" + mDesktopItems.size()); 2215 Log.d(TAG, "mFolders.size=" + mFolders.size()); 2216 mModel.dumpState(); 2217 mAllAppsGrid.dumpState(); 2218 Log.d(TAG, "END launcher2 dump state"); 2219 } 2220} 2221