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