Launcher.java revision 57e0ae249038ed9fda446ae45d0b916110eca50f
1 2/* 3 * Copyright (C) 2008 The Android Open Source Project 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18package com.android.launcher2; 19 20import android.animation.Animator; 21import android.animation.AnimatorListenerAdapter; 22import android.animation.AnimatorSet; 23import android.animation.ObjectAnimator; 24import android.animation.PropertyValuesHolder; 25import android.animation.ValueAnimator; 26import android.app.Activity; 27import android.app.AlertDialog; 28import android.app.Dialog; 29import android.app.SearchManager; 30import android.app.StatusBarManager; 31import android.appwidget.AppWidgetManager; 32import android.appwidget.AppWidgetProviderInfo; 33import android.content.ActivityNotFoundException; 34import android.content.BroadcastReceiver; 35import android.content.ClipData; 36import android.content.ClipDescription; 37import android.content.ComponentName; 38import android.content.ContentResolver; 39import android.content.Context; 40import android.content.DialogInterface; 41import android.content.Intent; 42import android.content.IntentFilter; 43import android.content.Intent.ShortcutIconResource; 44import android.content.pm.ActivityInfo; 45import android.content.pm.PackageManager; 46import android.content.pm.PackageManager.NameNotFoundException; 47import android.content.res.Configuration; 48import android.content.res.Resources; 49import android.database.ContentObserver; 50import android.graphics.Rect; 51import android.graphics.drawable.Drawable; 52import android.net.Uri; 53import android.os.AsyncTask; 54import android.os.Build; 55import android.os.Bundle; 56import android.os.Environment; 57import android.os.Handler; 58import android.os.Message; 59import android.os.SystemClock; 60import android.os.SystemProperties; 61import android.provider.Settings; 62import android.speech.RecognizerIntent; 63import android.text.Selection; 64import android.text.SpannableStringBuilder; 65import android.text.TextUtils; 66import android.text.method.TextKeyListener; 67import android.util.Log; 68import android.view.Display; 69import android.view.HapticFeedbackConstants; 70import android.view.KeyEvent; 71import android.view.LayoutInflater; 72import android.view.Menu; 73import android.view.MenuItem; 74import android.view.MotionEvent; 75import android.view.Surface; 76import android.view.View; 77import android.view.ViewGroup; 78import android.view.View.OnLongClickListener; 79import android.view.accessibility.AccessibilityEvent; 80import android.view.animation.DecelerateInterpolator; 81import android.view.inputmethod.InputMethodManager; 82import android.widget.Advanceable; 83import android.widget.EditText; 84import android.widget.ImageView; 85import android.widget.TextView; 86import android.widget.Toast; 87 88import com.android.common.Search; 89import com.android.launcher.R; 90 91import java.io.DataInputStream; 92import java.io.DataOutputStream; 93import java.io.FileNotFoundException; 94import java.io.IOException; 95import java.util.ArrayList; 96import java.util.HashMap; 97 98/** 99 * Default launcher application. 100 */ 101public final class Launcher extends Activity 102 implements View.OnClickListener, OnLongClickListener, LauncherModel.Callbacks, 103 AllAppsView.Watcher, View.OnTouchListener { 104 static final String TAG = "Launcher"; 105 static final boolean LOGD = false; 106 107 static final boolean PROFILE_STARTUP = false; 108 static final boolean DEBUG_WIDGETS = false; 109 110 private static final int MENU_GROUP_ADD = 1; 111 private static final int MENU_GROUP_WALLPAPER = MENU_GROUP_ADD + 1; 112 113 private static final int MENU_ADD = Menu.FIRST + 1; 114 private static final int MENU_MANAGE_APPS = MENU_ADD + 1; 115 private static final int MENU_WALLPAPER_SETTINGS = MENU_MANAGE_APPS + 1; 116 private static final int MENU_SEARCH = MENU_WALLPAPER_SETTINGS + 1; 117 private static final int MENU_NOTIFICATIONS = MENU_SEARCH + 1; 118 private static final int MENU_SETTINGS = MENU_NOTIFICATIONS + 1; 119 120 private static final int REQUEST_CREATE_SHORTCUT = 1; 121 private static final int REQUEST_CREATE_APPWIDGET = 5; 122 private static final int REQUEST_PICK_APPLICATION = 6; 123 private static final int REQUEST_PICK_SHORTCUT = 7; 124 private static final int REQUEST_PICK_APPWIDGET = 9; 125 private static final int REQUEST_PICK_WALLPAPER = 10; 126 127 static final String EXTRA_SHORTCUT_DUPLICATE = "duplicate"; 128 129 static final int SCREEN_COUNT = 5; 130 static final int DEFAULT_SCREEN = 2; 131 132 static final int DIALOG_CREATE_SHORTCUT = 1; 133 static final int DIALOG_RENAME_FOLDER = 2; 134 135 private static final String PREFERENCES = "launcher.preferences"; 136 137 // Type: int 138 private static final String RUNTIME_STATE_CURRENT_SCREEN = "launcher.current_screen"; 139 // Type: int 140 private static final String RUNTIME_STATE = "launcher.state"; 141 // Type: int 142 private static final String RUNTIME_STATE_PENDING_ADD_CONTAINER = "launcher.add_container"; 143 // Type: int 144 private static final String RUNTIME_STATE_PENDING_ADD_SCREEN = "launcher.add_screen"; 145 // Type: int 146 private static final String RUNTIME_STATE_PENDING_ADD_CELL_X = "launcher.add_cell_x"; 147 // Type: int 148 private static final String RUNTIME_STATE_PENDING_ADD_CELL_Y = "launcher.add_cell_y"; 149 // Type: boolean 150 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME = "launcher.rename_folder"; 151 // Type: long 152 private static final String RUNTIME_STATE_PENDING_FOLDER_RENAME_ID = "launcher.rename_folder_id"; 153 154 private static final String TOOLBAR_ICON_METADATA_NAME = "com.android.launcher.toolbar_icon"; 155 156 /** The different states that Launcher can be in. */ 157 private enum State { WORKSPACE, APPS_CUSTOMIZE, APPS_CUSTOMIZE_SPRING_LOADED }; 158 private State mState = State.WORKSPACE; 159 private AnimatorSet mStateAnimation; 160 161 static final int APPWIDGET_HOST_ID = 1024; 162 private static final int EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT = 300; 163 private static final int EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT = 600; 164 165 private static final Object sLock = new Object(); 166 private static int sScreen = DEFAULT_SCREEN; 167 168 private final BroadcastReceiver mCloseSystemDialogsReceiver 169 = new CloseSystemDialogsIntentReceiver(); 170 private final ContentObserver mWidgetObserver = new AppWidgetResetObserver(); 171 172 private LayoutInflater mInflater; 173 174 private DragController mDragController; 175 private Workspace mWorkspace; 176 177 private AppWidgetManager mAppWidgetManager; 178 private LauncherAppWidgetHost mAppWidgetHost; 179 180 private ItemInfo mPendingAddInfo = new ItemInfo(); 181 private int[] mTmpAddItemCellCoordinates = new int[2]; 182 183 private FolderInfo mFolderInfo; 184 185 private Hotseat mHotseat; 186 private View mAllAppsButton; 187 188 private SearchDropTargetBar mSearchDeleteBar; 189 private AppsCustomizeTabHost mAppsCustomizeTabHost; 190 private AppsCustomizePagedView mAppsCustomizeContent; 191 private boolean mAutoAdvanceRunning = false; 192 193 private Bundle mSavedState; 194 195 private SpannableStringBuilder mDefaultKeySsb = null; 196 197 private boolean mWorkspaceLoading = true; 198 199 private boolean mPaused = true; 200 private boolean mRestoring; 201 private boolean mWaitingForResult; 202 private boolean mOnResumeNeedsLoad; 203 204 private Bundle mSavedInstanceState; 205 206 private LauncherModel mModel; 207 private IconCache mIconCache; 208 private boolean mUserPresent = true; 209 private boolean mVisible = false; 210 private boolean mAttached = false; 211 212 private static LocaleConfiguration sLocaleConfiguration = null; 213 214 private static HashMap<Long, FolderInfo> sFolders = new HashMap<Long, FolderInfo>(); 215 216 private Intent mAppMarketIntent = null; 217 218 // Related to the auto-advancing of widgets 219 private final int ADVANCE_MSG = 1; 220 private final int mAdvanceInterval = 20000; 221 private final int mAdvanceStagger = 250; 222 private long mAutoAdvanceSentTime; 223 private long mAutoAdvanceTimeLeft = -1; 224 private HashMap<View, AppWidgetProviderInfo> mWidgetsToAdvance = 225 new HashMap<View, AppWidgetProviderInfo>(); 226 227 // Determines how long to wait after a rotation before restoring the screen orientation to 228 // match the sensor state. 229 private final int mRestoreScreenOrientationDelay = 500; 230 231 // External icons saved in case of resource changes, orientation, etc. 232 private static Drawable.ConstantState sGlobalSearchIcon; 233 private static Drawable.ConstantState sVoiceSearchIcon; 234 private static Drawable.ConstantState sAppMarketIcon; 235 236 private DragLayer mDragLayer; 237 238 private BubbleTextView mWaitingForResume; 239 240 private static ArrayList<PendingAddArguments> sPendingAddList 241 = new ArrayList<PendingAddArguments>(); 242 243 private static class PendingAddArguments { 244 int requestCode; 245 Intent intent; 246 long container; 247 int screen; 248 int cellX; 249 int cellY; 250 } 251 252 @Override 253 protected void onCreate(Bundle savedInstanceState) { 254 super.onCreate(savedInstanceState); 255 LauncherApplication app = ((LauncherApplication)getApplication()); 256 mModel = app.setLauncher(this); 257 mIconCache = app.getIconCache(); 258 mDragController = new DragController(this); 259 mInflater = getLayoutInflater(); 260 261 mAppWidgetManager = AppWidgetManager.getInstance(this); 262 mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID); 263 mAppWidgetHost.startListening(); 264 265 if (PROFILE_STARTUP) { 266 android.os.Debug.startMethodTracing( 267 Environment.getExternalStorageDirectory() + "/launcher"); 268 } 269 270 checkForLocaleChange(); 271 setContentView(R.layout.launcher); 272 setupViews(); 273 274 registerContentObservers(); 275 276 lockAllApps(); 277 278 mSavedState = savedInstanceState; 279 restoreState(mSavedState); 280 281 // Update customization drawer _after_ restoring the states 282 if (mAppsCustomizeContent != null) { 283 mAppsCustomizeContent.onPackagesUpdated(); 284 } 285 286 if (PROFILE_STARTUP) { 287 android.os.Debug.stopMethodTracing(); 288 } 289 290 if (!mRestoring) { 291 mModel.startLoader(this, true); 292 } 293 294 // For handling default keys 295 mDefaultKeySsb = new SpannableStringBuilder(); 296 Selection.setSelection(mDefaultKeySsb, 0); 297 298 IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 299 registerReceiver(mCloseSystemDialogsReceiver, filter); 300 301 // If we have a saved version of these external icons, we load them up immediately 302 if (sGlobalSearchIcon == null || sVoiceSearchIcon == null || sAppMarketIcon == null) { 303 updateIconsAffectedByPackageManagerChanges(); 304 updateGlobalSearchIcon(); 305 } 306 if (sGlobalSearchIcon != null) { 307 updateGlobalSearchIcon(sGlobalSearchIcon); 308 } 309 if (sVoiceSearchIcon != null) { 310 updateVoiceSearchIcon(sVoiceSearchIcon); 311 } 312 if (sAppMarketIcon != null) { 313 updateAppMarketIcon(sAppMarketIcon); 314 } 315 } 316 317 private void checkForLocaleChange() { 318 if (sLocaleConfiguration == null) { 319 new AsyncTask<Void, Void, LocaleConfiguration>() { 320 @Override 321 protected LocaleConfiguration doInBackground(Void... unused) { 322 LocaleConfiguration localeConfiguration = new LocaleConfiguration(); 323 readConfiguration(Launcher.this, localeConfiguration); 324 return localeConfiguration; 325 } 326 327 @Override 328 protected void onPostExecute(LocaleConfiguration result) { 329 sLocaleConfiguration = result; 330 checkForLocaleChange(); // recursive, but now with a locale configuration 331 } 332 }.execute(); 333 return; 334 } 335 336 final Configuration configuration = getResources().getConfiguration(); 337 338 final String previousLocale = sLocaleConfiguration.locale; 339 final String locale = configuration.locale.toString(); 340 341 final int previousMcc = sLocaleConfiguration.mcc; 342 final int mcc = configuration.mcc; 343 344 final int previousMnc = sLocaleConfiguration.mnc; 345 final int mnc = configuration.mnc; 346 347 boolean localeChanged = !locale.equals(previousLocale) || mcc != previousMcc || mnc != previousMnc; 348 349 if (localeChanged) { 350 sLocaleConfiguration.locale = locale; 351 sLocaleConfiguration.mcc = mcc; 352 sLocaleConfiguration.mnc = mnc; 353 354 mIconCache.flush(); 355 356 final LocaleConfiguration localeConfiguration = sLocaleConfiguration; 357 new Thread("WriteLocaleConfiguration") { 358 @Override 359 public void run() { 360 writeConfiguration(Launcher.this, localeConfiguration); 361 } 362 }.start(); 363 } 364 } 365 366 private static class LocaleConfiguration { 367 public String locale; 368 public int mcc = -1; 369 public int mnc = -1; 370 } 371 372 private static void readConfiguration(Context context, LocaleConfiguration configuration) { 373 DataInputStream in = null; 374 try { 375 in = new DataInputStream(context.openFileInput(PREFERENCES)); 376 configuration.locale = in.readUTF(); 377 configuration.mcc = in.readInt(); 378 configuration.mnc = in.readInt(); 379 } catch (FileNotFoundException e) { 380 // Ignore 381 } catch (IOException e) { 382 // Ignore 383 } finally { 384 if (in != null) { 385 try { 386 in.close(); 387 } catch (IOException e) { 388 // Ignore 389 } 390 } 391 } 392 } 393 394 private static void writeConfiguration(Context context, LocaleConfiguration configuration) { 395 DataOutputStream out = null; 396 try { 397 out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE)); 398 out.writeUTF(configuration.locale); 399 out.writeInt(configuration.mcc); 400 out.writeInt(configuration.mnc); 401 out.flush(); 402 } catch (FileNotFoundException e) { 403 // Ignore 404 } catch (IOException e) { 405 //noinspection ResultOfMethodCallIgnored 406 context.getFileStreamPath(PREFERENCES).delete(); 407 } finally { 408 if (out != null) { 409 try { 410 out.close(); 411 } catch (IOException e) { 412 // Ignore 413 } 414 } 415 } 416 } 417 418 public DragLayer getDragLayer() { 419 return mDragLayer; 420 } 421 422 static int getScreen() { 423 synchronized (sLock) { 424 return sScreen; 425 } 426 } 427 428 static void setScreen(int screen) { 429 synchronized (sLock) { 430 sScreen = screen; 431 } 432 } 433 434 /** 435 * Returns whether we should delay spring loaded mode -- for shortcuts and widgets that have 436 * a configuration step, this allows the proper animations to run after other transitions. 437 */ 438 private boolean completeAdd(PendingAddArguments args) { 439 boolean result = false; 440 switch (args.requestCode) { 441 case REQUEST_PICK_APPLICATION: 442 completeAddApplication(args.intent, args.container, args.screen, args.cellX, 443 args.cellY); 444 break; 445 case REQUEST_PICK_SHORTCUT: 446 processShortcut(args.intent); 447 break; 448 case REQUEST_CREATE_SHORTCUT: 449 completeAddShortcut(args.intent, args.container, args.screen, args.cellX, 450 args.cellY); 451 result = true; 452 break; 453 case REQUEST_PICK_APPWIDGET: 454 addAppWidgetFromPick(args.intent); 455 break; 456 case REQUEST_CREATE_APPWIDGET: 457 int appWidgetId = args.intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 458 completeAddAppWidget(appWidgetId, args.container, args.screen); 459 result = true; 460 break; 461 case REQUEST_PICK_WALLPAPER: 462 // We just wanted the activity result here so we can clear mWaitingForResult 463 break; 464 } 465 // In any situation where we have a multi-step drop, we should reset the add info only after 466 // we complete the drop 467 resetAddInfo(); 468 return result; 469 } 470 471 @Override 472 protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { 473 boolean delayExitSpringLoadedMode = false; 474 mWaitingForResult = false; 475 476 // The pattern used here is that a user PICKs a specific application, 477 // which, depending on the target, might need to CREATE the actual target. 478 479 // For example, the user would PICK_SHORTCUT for "Music playlist", and we 480 // launch over to the Music app to actually CREATE_SHORTCUT. 481 if (resultCode == RESULT_OK && mPendingAddInfo.container != ItemInfo.NO_ID && 482 mPendingAddInfo.screen > -1) { 483 final PendingAddArguments args = new PendingAddArguments(); 484 args.requestCode = requestCode; 485 args.intent = data; 486 args.container = mPendingAddInfo.container; 487 args.screen = mPendingAddInfo.screen; 488 args.cellX = mPendingAddInfo.cellX; 489 args.cellY = mPendingAddInfo.cellY; 490 491 // If the loader is still running, defer the add until it is done. 492 if (isWorkspaceLocked()) { 493 sPendingAddList.add(args); 494 } else { 495 delayExitSpringLoadedMode = completeAdd(args); 496 } 497 } else if ((requestCode == REQUEST_PICK_APPWIDGET || 498 requestCode == REQUEST_CREATE_APPWIDGET) && resultCode == RESULT_CANCELED) { 499 if (data != null) { 500 // Clean up the appWidgetId if we canceled 501 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 502 if (appWidgetId != -1) { 503 mAppWidgetHost.deleteAppWidgetId(appWidgetId); 504 } 505 } 506 } 507 508 // Exit spring loaded mode if necessary after cancelling the configuration of a widget 509 exitSpringLoadedDragModeDelayed((resultCode != RESULT_CANCELED), delayExitSpringLoadedMode); 510 } 511 512 @Override 513 protected void onResume() { 514 super.onResume(); 515 mPaused = false; 516 if (mRestoring || mOnResumeNeedsLoad) { 517 mWorkspaceLoading = true; 518 mModel.startLoader(this, true); 519 mRestoring = false; 520 mOnResumeNeedsLoad = false; 521 } 522 if (mWaitingForResume != null) { 523 mWaitingForResume.setStayPressed(false); 524 } 525 // When we resume Launcher, a different Activity might be responsible for the app 526 // market intent, so refresh the icon 527 updateAppMarketIcon(); 528 } 529 530 @Override 531 protected void onPause() { 532 super.onPause(); 533 mPaused = true; 534 mDragController.cancelDrag(); 535 } 536 537 @Override 538 public Object onRetainNonConfigurationInstance() { 539 // Flag the loader to stop early before switching 540 mModel.stopLoader(); 541 if (mAppsCustomizeContent != null) { 542 mAppsCustomizeContent.surrender(); 543 } 544 return Boolean.TRUE; 545 } 546 547 // We can't hide the IME if it was forced open. So don't bother 548 /* 549 @Override 550 public void onWindowFocusChanged(boolean hasFocus) { 551 super.onWindowFocusChanged(hasFocus); 552 553 if (hasFocus) { 554 final InputMethodManager inputManager = (InputMethodManager) 555 getSystemService(Context.INPUT_METHOD_SERVICE); 556 WindowManager.LayoutParams lp = getWindow().getAttributes(); 557 inputManager.hideSoftInputFromWindow(lp.token, 0, new android.os.ResultReceiver(new 558 android.os.Handler()) { 559 protected void onReceiveResult(int resultCode, Bundle resultData) { 560 Log.d(TAG, "ResultReceiver got resultCode=" + resultCode); 561 } 562 }); 563 Log.d(TAG, "called hideSoftInputFromWindow from onWindowFocusChanged"); 564 } 565 } 566 */ 567 568 private boolean acceptFilter() { 569 final InputMethodManager inputManager = (InputMethodManager) 570 getSystemService(Context.INPUT_METHOD_SERVICE); 571 return !inputManager.isFullscreenMode(); 572 } 573 574 @Override 575 public boolean onKeyDown(int keyCode, KeyEvent event) { 576 final int uniChar = event.getUnicodeChar(); 577 final boolean handled = super.onKeyDown(keyCode, event); 578 final boolean isKeyNotWhitespace = uniChar > 0 && !Character.isWhitespace(uniChar); 579 if (!handled && acceptFilter() && isKeyNotWhitespace) { 580 boolean gotKey = TextKeyListener.getInstance().onKeyDown(mWorkspace, mDefaultKeySsb, 581 keyCode, event); 582 if (gotKey && mDefaultKeySsb != null && mDefaultKeySsb.length() > 0) { 583 // something usable has been typed - start a search 584 // the typed text will be retrieved and cleared by 585 // showSearchDialog() 586 // If there are multiple keystrokes before the search dialog takes focus, 587 // onSearchRequested() will be called for every keystroke, 588 // but it is idempotent, so it's fine. 589 return onSearchRequested(); 590 } 591 } 592 593 // Eat the long press event so the keyboard doesn't come up. 594 if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress()) { 595 return true; 596 } 597 598 return handled; 599 } 600 601 private String getTypedText() { 602 return mDefaultKeySsb.toString(); 603 } 604 605 private void clearTypedText() { 606 mDefaultKeySsb.clear(); 607 mDefaultKeySsb.clearSpans(); 608 Selection.setSelection(mDefaultKeySsb, 0); 609 } 610 611 /** 612 * Given the integer (ordinal) value of a State enum instance, convert it to a variable of type 613 * State 614 */ 615 private static State intToState(int stateOrdinal) { 616 State state = State.WORKSPACE; 617 final State[] stateValues = State.values(); 618 for (int i = 0; i < stateValues.length; i++) { 619 if (stateValues[i].ordinal() == stateOrdinal) { 620 state = stateValues[i]; 621 break; 622 } 623 } 624 return state; 625 } 626 627 /** 628 * Restores the previous state, if it exists. 629 * 630 * @param savedState The previous state. 631 */ 632 private void restoreState(Bundle savedState) { 633 if (savedState == null) { 634 return; 635 } 636 637 State state = intToState(savedState.getInt(RUNTIME_STATE, State.WORKSPACE.ordinal())); 638 if (state == State.APPS_CUSTOMIZE) { 639 showAllApps(false); 640 } 641 642 final int currentScreen = savedState.getInt(RUNTIME_STATE_CURRENT_SCREEN, -1); 643 if (currentScreen > -1) { 644 mWorkspace.setCurrentPage(currentScreen); 645 } 646 647 final long pendingAddContainer = savedState.getLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, -1); 648 final int pendingAddScreen = savedState.getInt(RUNTIME_STATE_PENDING_ADD_SCREEN, -1); 649 650 if (pendingAddContainer != ItemInfo.NO_ID && pendingAddScreen > -1) { 651 mPendingAddInfo.container = pendingAddContainer; 652 mPendingAddInfo.screen = pendingAddScreen; 653 mPendingAddInfo.cellX = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_X); 654 mPendingAddInfo.cellY = savedState.getInt(RUNTIME_STATE_PENDING_ADD_CELL_Y); 655 mRestoring = true; 656 } 657 658 boolean renameFolder = savedState.getBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, false); 659 if (renameFolder) { 660 long id = savedState.getLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID); 661 mFolderInfo = mModel.getFolderById(this, sFolders, id); 662 mRestoring = true; 663 } 664 665 666 // Restore the AppsCustomize tab 667 if (mAppsCustomizeTabHost != null) { 668 String curTab = savedState.getString("apps_customize_currentTab"); 669 if (curTab != null) { 670 // We set this directly so that there is no delay before the tab is set 671 mAppsCustomizeContent.setContentType( 672 mAppsCustomizeTabHost.getContentTypeForTabTag(curTab)); 673 mAppsCustomizeTabHost.setCurrentTabByTag(curTab); 674 } 675 676 // Note: currently we do not restore the page for the AppsCustomize pane because the 677 // change in layout can drastically affect the saved page index 678 } 679 } 680 681 /** 682 * Finds all the views we need and configure them properly. 683 */ 684 private void setupViews() { 685 final DragController dragController = mDragController; 686 687 mDragLayer = (DragLayer) findViewById(R.id.drag_layer); 688 mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace); 689 690 // Setup the drag layer 691 mDragLayer.setup(this, dragController); 692 693 // Setup the hotseat 694 mHotseat = (Hotseat) findViewById(R.id.hotseat); 695 if (mHotseat != null) { 696 mHotseat.setup(this); 697 } 698 699 // Setup the workspace 700 mWorkspace.setHapticFeedbackEnabled(false); 701 mWorkspace.setOnLongClickListener(this); 702 mWorkspace.setup(this, dragController); 703 dragController.addDragListener(mWorkspace); 704 705 // Get the search/delete bar 706 mSearchDeleteBar = (SearchDropTargetBar) mDragLayer.findViewById(R.id.qsb_bar); 707 708 // Setup AppsCustomize 709 mAppsCustomizeTabHost = (AppsCustomizeTabHost) 710 findViewById(R.id.apps_customize_pane); 711 mAppsCustomizeContent = (AppsCustomizePagedView) 712 mAppsCustomizeTabHost.findViewById(R.id.apps_customize_pane_content); 713 mAppsCustomizeContent.setup(this, dragController); 714 715 716 717 // Setup the drag controller (drop targets have to be added in reverse order in priority) 718 dragController.setDragScoller(mWorkspace); 719 dragController.setScrollView(mDragLayer); 720 dragController.setMoveTarget(mWorkspace); 721 dragController.addDropTarget(mWorkspace); 722 if (mSearchDeleteBar != null) { 723 mSearchDeleteBar.setup(this, dragController); 724 } 725 } 726 727 728 729 /** 730 * Creates a view representing a shortcut. 731 * 732 * @param info The data structure describing the shortcut. 733 * 734 * @return A View inflated from R.layout.application. 735 */ 736 View createShortcut(ShortcutInfo info) { 737 return createShortcut(R.layout.application, 738 (ViewGroup) mWorkspace.getChildAt(mWorkspace.getCurrentPage()), info); 739 } 740 741 /** 742 * Creates a view representing a shortcut inflated from the specified resource. 743 * 744 * @param layoutResId The id of the XML layout used to create the shortcut. 745 * @param parent The group the shortcut belongs to. 746 * @param info The data structure describing the shortcut. 747 * 748 * @return A View inflated from layoutResId. 749 */ 750 View createShortcut(int layoutResId, ViewGroup parent, ShortcutInfo info) { 751 BubbleTextView favorite = (BubbleTextView) mInflater.inflate(layoutResId, parent, false); 752 favorite.applyFromShortcutInfo(info, mIconCache); 753 favorite.setOnClickListener(this); 754 return favorite; 755 } 756 757 /** 758 * Add an application shortcut to the workspace. 759 * 760 * @param data The intent describing the application. 761 * @param cellInfo The position on screen where to create the shortcut. 762 */ 763 void completeAddApplication(Intent data, long container, int screen, int cellX, int cellY) { 764 final int[] cellXY = mTmpAddItemCellCoordinates; 765 final CellLayout layout = getCellLayout(container, screen); 766 767 // First we check if we already know the exact location where we want to add this item. 768 if (cellX >= 0 && cellY >= 0) { 769 cellXY[0] = cellX; 770 cellXY[1] = cellY; 771 } else if (!layout.findCellForSpan(cellXY, 1, 1)) { 772 showOutOfSpaceMessage(); 773 return; 774 } 775 776 final ShortcutInfo info = mModel.getShortcutInfo(getPackageManager(), data, this); 777 778 if (info != null) { 779 info.setActivity(data.getComponent(), Intent.FLAG_ACTIVITY_NEW_TASK | 780 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 781 info.container = ItemInfo.NO_ID; 782 mWorkspace.addApplicationShortcut(info, layout, container, screen, cellXY[0], cellXY[1], 783 isWorkspaceLocked(), cellX, cellY); 784 } else { 785 Log.e(TAG, "Couldn't find ActivityInfo for selected application: " + data); 786 } 787 } 788 789 /** 790 * Add a shortcut to the workspace. 791 * 792 * @param data The intent describing the shortcut. 793 * @param cellInfo The position on screen where to create the shortcut. 794 */ 795 private void completeAddShortcut(Intent data, long container, int screen, int cellX, 796 int cellY) { 797 int[] cellXY = mTmpAddItemCellCoordinates; 798 int[] touchXY = mPendingAddInfo.dropPos; 799 CellLayout layout = getCellLayout(container, screen); 800 801 boolean foundCellSpan = false; 802 803 // First we check if we already know the exact location where we want to add this item. 804 if (cellX >= 0 && cellY >= 0) { 805 cellXY[0] = cellX; 806 cellXY[1] = cellY; 807 foundCellSpan = true; 808 } else if (touchXY != null) { 809 // when dragging and dropping, just find the closest free spot 810 int[] result = layout.findNearestVacantArea(touchXY[0], touchXY[1], 1, 1, cellXY); 811 foundCellSpan = (result != null); 812 } else { 813 foundCellSpan = layout.findCellForSpan(cellXY, 1, 1); 814 } 815 816 if (!foundCellSpan) { 817 showOutOfSpaceMessage(); 818 return; 819 } 820 821 final ShortcutInfo info = mModel.addShortcut( 822 this, data, container, screen, cellXY[0], cellXY[1], false); 823 824 if (!mRestoring) { 825 final View view = createShortcut(info); 826 mWorkspace.addInScreen(view, container, screen, cellXY[0], cellXY[1], 1, 1, 827 isWorkspaceLocked()); 828 } 829 } 830 831 /** 832 * Add a widget to the workspace. 833 * 834 * @param appWidgetId The app widget id 835 * @param cellInfo The position on screen where to create the widget. 836 */ 837 private void completeAddAppWidget(final int appWidgetId, long container, int screen) { 838 AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 839 840 // Calculate the grid spans needed to fit this widget 841 CellLayout layout = getCellLayout(container, screen); 842 843 // We want to account for the extra amount of padding that we are adding to the widget 844 // to ensure that it gets the full amount of space that it has requested 845 Resources r = getResources(); 846 int requiredWidth = appWidgetInfo.minWidth + 847 r.getDimensionPixelSize(R.dimen.app_widget_padding_left) + 848 r.getDimensionPixelSize(R.dimen.app_widget_padding_right); 849 int requiredHeight = appWidgetInfo.minHeight + 850 r.getDimensionPixelSize(R.dimen.app_widget_padding_top) + 851 r.getDimensionPixelSize(R.dimen.app_widget_padding_bottom); 852 int[] spanXY = layout.rectToCell(requiredWidth, requiredHeight, null); 853 854 // Try finding open space on Launcher screen 855 // We have saved the position to which the widget was dragged-- this really only matters 856 // if we are placing widgets on a "spring-loaded" screen 857 int[] cellXY = mTmpAddItemCellCoordinates; 858 int[] touchXY = mPendingAddInfo.dropPos; 859 boolean foundCellSpan = false; 860 if (mPendingAddInfo.cellX >= 0 && mPendingAddInfo.cellY >= 0) { 861 cellXY[0] = mPendingAddInfo.cellX; 862 cellXY[1] = mPendingAddInfo.cellY; 863 foundCellSpan = true; 864 } else if (touchXY != null) { 865 // when dragging and dropping, just find the closest free spot 866 int[] result = layout.findNearestVacantArea( 867 touchXY[0], touchXY[1], spanXY[0], spanXY[1], cellXY); 868 foundCellSpan = (result != null); 869 } else { 870 foundCellSpan = layout.findCellForSpan(cellXY, spanXY[0], spanXY[1]); 871 } 872 873 if (!foundCellSpan) { 874 if (appWidgetId != -1) { 875 // Deleting an app widget ID is a void call but writes to disk before returning 876 // to the caller... 877 new Thread("deleteAppWidgetId") { 878 public void run() { 879 mAppWidgetHost.deleteAppWidgetId(appWidgetId); 880 } 881 }.start(); 882 } 883 showOutOfSpaceMessage(); 884 return; 885 } 886 887 // Build Launcher-specific widget info and save to database 888 LauncherAppWidgetInfo launcherInfo = new LauncherAppWidgetInfo(appWidgetId); 889 launcherInfo.spanX = spanXY[0]; 890 launcherInfo.spanY = spanXY[1]; 891 892 LauncherModel.addItemToDatabase(this, launcherInfo, 893 container, screen, cellXY[0], cellXY[1], false); 894 895 if (!mRestoring) { 896 // Perform actual inflation because we're live 897 launcherInfo.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 898 899 launcherInfo.hostView.setAppWidget(appWidgetId, appWidgetInfo); 900 launcherInfo.hostView.setTag(launcherInfo); 901 902 mWorkspace.addInScreen(launcherInfo.hostView, container, screen, cellXY[0], cellXY[1], 903 launcherInfo.spanX, launcherInfo.spanY, isWorkspaceLocked()); 904 905 addWidgetToAutoAdvanceIfNeeded(launcherInfo.hostView, appWidgetInfo); 906 } 907 } 908 909 private final BroadcastReceiver mReceiver = new BroadcastReceiver() { 910 @Override 911 public void onReceive(Context context, Intent intent) { 912 final String action = intent.getAction(); 913 if (Intent.ACTION_SCREEN_OFF.equals(action)) { 914 mUserPresent = false; 915 mDragLayer.clearAllResizeFrames(); 916 updateRunning(); 917 918 // Reset AllApps to it's initial state only if we are not in the middle of 919 // processing a multi-step drop 920 if (mAppsCustomizeContent != null && mPendingAddInfo.container == ItemInfo.NO_ID) { 921 mAppsCustomizeContent.reset(); 922 } 923 } else if (Intent.ACTION_USER_PRESENT.equals(action)) { 924 mUserPresent = true; 925 updateRunning(); 926 } 927 } 928 }; 929 930 @Override 931 public void onAttachedToWindow() { 932 super.onAttachedToWindow(); 933 934 // Listen for broadcasts related to user-presence 935 final IntentFilter filter = new IntentFilter(); 936 filter.addAction(Intent.ACTION_SCREEN_OFF); 937 filter.addAction(Intent.ACTION_USER_PRESENT); 938 registerReceiver(mReceiver, filter); 939 940 mAttached = true; 941 mVisible = true; 942 } 943 944 @Override 945 public void onDetachedFromWindow() { 946 super.onDetachedFromWindow(); 947 mVisible = false; 948 mDragLayer.clearAllResizeFrames(); 949 950 if (mAttached) { 951 unregisterReceiver(mReceiver); 952 mAttached = false; 953 } 954 updateRunning(); 955 } 956 957 public void onWindowVisibilityChanged(int visibility) { 958 mVisible = visibility == View.VISIBLE; 959 updateRunning(); 960 } 961 962 private void sendAdvanceMessage(long delay) { 963 mHandler.removeMessages(ADVANCE_MSG); 964 Message msg = mHandler.obtainMessage(ADVANCE_MSG); 965 mHandler.sendMessageDelayed(msg, delay); 966 mAutoAdvanceSentTime = System.currentTimeMillis(); 967 } 968 969 private void updateRunning() { 970 boolean autoAdvanceRunning = mVisible && mUserPresent && !mWidgetsToAdvance.isEmpty(); 971 if (autoAdvanceRunning != mAutoAdvanceRunning) { 972 mAutoAdvanceRunning = autoAdvanceRunning; 973 if (autoAdvanceRunning) { 974 long delay = mAutoAdvanceTimeLeft == -1 ? mAdvanceInterval : mAutoAdvanceTimeLeft; 975 sendAdvanceMessage(delay); 976 } else { 977 if (!mWidgetsToAdvance.isEmpty()) { 978 mAutoAdvanceTimeLeft = Math.max(0, mAdvanceInterval - 979 (System.currentTimeMillis() - mAutoAdvanceSentTime)); 980 } 981 mHandler.removeMessages(ADVANCE_MSG); 982 mHandler.removeMessages(0); // Remove messages sent using postDelayed() 983 } 984 } 985 } 986 987 private final Handler mHandler = new Handler() { 988 @Override 989 public void handleMessage(Message msg) { 990 if (msg.what == ADVANCE_MSG) { 991 int i = 0; 992 for (View key: mWidgetsToAdvance.keySet()) { 993 final View v = key.findViewById(mWidgetsToAdvance.get(key).autoAdvanceViewId); 994 final int delay = mAdvanceStagger * i; 995 if (v instanceof Advanceable) { 996 postDelayed(new Runnable() { 997 public void run() { 998 ((Advanceable) v).advance(); 999 } 1000 }, delay); 1001 } 1002 i++; 1003 } 1004 sendAdvanceMessage(mAdvanceInterval); 1005 } 1006 } 1007 }; 1008 1009 void addWidgetToAutoAdvanceIfNeeded(View hostView, AppWidgetProviderInfo appWidgetInfo) { 1010 if (appWidgetInfo == null || appWidgetInfo.autoAdvanceViewId == -1) return; 1011 View v = hostView.findViewById(appWidgetInfo.autoAdvanceViewId); 1012 if (v instanceof Advanceable) { 1013 mWidgetsToAdvance.put(hostView, appWidgetInfo); 1014 ((Advanceable) v).fyiWillBeAdvancedByHostKThx(); 1015 updateRunning(); 1016 } 1017 } 1018 1019 void removeWidgetToAutoAdvance(View hostView) { 1020 if (mWidgetsToAdvance.containsKey(hostView)) { 1021 mWidgetsToAdvance.remove(hostView); 1022 updateRunning(); 1023 } 1024 } 1025 1026 public void removeAppWidget(LauncherAppWidgetInfo launcherInfo) { 1027 removeWidgetToAutoAdvance(launcherInfo.hostView); 1028 launcherInfo.hostView = null; 1029 } 1030 1031 void showOutOfSpaceMessage() { 1032 Toast.makeText(this, getString(R.string.out_of_space), Toast.LENGTH_SHORT).show(); 1033 } 1034 1035 public LauncherAppWidgetHost getAppWidgetHost() { 1036 return mAppWidgetHost; 1037 } 1038 1039 public LauncherModel getModel() { 1040 return mModel; 1041 } 1042 1043 void closeSystemDialogs() { 1044 getWindow().closeAllPanels(); 1045 1046 try { 1047 dismissDialog(DIALOG_CREATE_SHORTCUT); 1048 // Unlock the workspace if the dialog was showing 1049 } catch (Exception e) { 1050 // An exception is thrown if the dialog is not visible, which is fine 1051 } 1052 1053 try { 1054 dismissDialog(DIALOG_RENAME_FOLDER); 1055 // Unlock the workspace if the dialog was showing 1056 } catch (Exception e) { 1057 // An exception is thrown if the dialog is not visible, which is fine 1058 } 1059 1060 // Whatever we were doing is hereby canceled. 1061 mWaitingForResult = false; 1062 } 1063 1064 @Override 1065 protected void onNewIntent(Intent intent) { 1066 super.onNewIntent(intent); 1067 1068 // Close the menu 1069 if (Intent.ACTION_MAIN.equals(intent.getAction())) { 1070 // also will cancel mWaitingForResult. 1071 closeSystemDialogs(); 1072 1073 closeFolder(); 1074 1075 boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) 1076 != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); 1077 1078 // In all these cases, only animate if we're already on home 1079 mWorkspace.exitWidgetResizeMode(); 1080 if (alreadyOnHome && mState == State.WORKSPACE && !mWorkspace.isTouchActive()) { 1081 mWorkspace.moveToDefaultScreen(true); 1082 } 1083 exitSpringLoadedDragMode(); 1084 showWorkspace(alreadyOnHome); 1085 1086 final View v = getWindow().peekDecorView(); 1087 if (v != null && v.getWindowToken() != null) { 1088 InputMethodManager imm = (InputMethodManager)getSystemService( 1089 INPUT_METHOD_SERVICE); 1090 imm.hideSoftInputFromWindow(v.getWindowToken(), 0); 1091 } 1092 1093 // Reset AllApps to its initial state 1094 if (mAppsCustomizeContent != null) { 1095 mAppsCustomizeContent.reset(); 1096 } 1097 } 1098 } 1099 1100 @Override 1101 protected void onRestoreInstanceState(Bundle savedInstanceState) { 1102 // Do not call super here 1103 mSavedInstanceState = savedInstanceState; 1104 } 1105 1106 @Override 1107 protected void onSaveInstanceState(Bundle outState) { 1108 outState.putInt(RUNTIME_STATE_CURRENT_SCREEN, mWorkspace.getCurrentPage()); 1109 super.onSaveInstanceState(outState); 1110 1111 outState.putInt(RUNTIME_STATE, mState.ordinal()); 1112 // We close any open folder since it will not be re-opened, and we need to make sure 1113 // this state is reflected. 1114 closeFolder(); 1115 1116 if (mPendingAddInfo.container != ItemInfo.NO_ID && mPendingAddInfo.screen > -1 && 1117 mWaitingForResult) { 1118 outState.putLong(RUNTIME_STATE_PENDING_ADD_CONTAINER, mPendingAddInfo.container); 1119 outState.putInt(RUNTIME_STATE_PENDING_ADD_SCREEN, mPendingAddInfo.screen); 1120 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_X, mPendingAddInfo.cellX); 1121 outState.putInt(RUNTIME_STATE_PENDING_ADD_CELL_Y, mPendingAddInfo.cellY); 1122 } 1123 1124 if (mFolderInfo != null && mWaitingForResult) { 1125 outState.putBoolean(RUNTIME_STATE_PENDING_FOLDER_RENAME, true); 1126 outState.putLong(RUNTIME_STATE_PENDING_FOLDER_RENAME_ID, mFolderInfo.id); 1127 } 1128 1129 // Save the current AppsCustomize tab 1130 if (mAppsCustomizeTabHost != null) { 1131 String currentTabTag = mAppsCustomizeTabHost.getCurrentTabTag(); 1132 if (currentTabTag != null) { 1133 outState.putString("apps_customize_currentTab", currentTabTag); 1134 } 1135 } 1136 } 1137 1138 @Override 1139 public void onDestroy() { 1140 super.onDestroy(); 1141 1142 // Stop callbacks from LauncherModel 1143 LauncherApplication app = ((LauncherApplication) getApplication()); 1144 mModel.stopLoader(); 1145 app.setLauncher(null); 1146 1147 try { 1148 mAppWidgetHost.stopListening(); 1149 } catch (NullPointerException ex) { 1150 Log.w(TAG, "problem while stopping AppWidgetHost during Launcher destruction", ex); 1151 } 1152 mAppWidgetHost = null; 1153 1154 mWidgetsToAdvance.clear(); 1155 1156 TextKeyListener.getInstance().release(); 1157 1158 1159 unbindWorkspaceAndHotseatItems(); 1160 1161 getContentResolver().unregisterContentObserver(mWidgetObserver); 1162 unregisterReceiver(mCloseSystemDialogsReceiver); 1163 1164 ((ViewGroup) mWorkspace.getParent()).removeAllViews(); 1165 mWorkspace.removeAllViews(); 1166 mWorkspace = null; 1167 mDragController = null; 1168 1169 ValueAnimator.clearAllAnimations(); 1170 } 1171 1172 public DragController getDragController() { 1173 return mDragController; 1174 } 1175 1176 @Override 1177 public void startActivityForResult(Intent intent, int requestCode) { 1178 if (requestCode >= 0) mWaitingForResult = true; 1179 super.startActivityForResult(intent, requestCode); 1180 } 1181 1182 @Override 1183 public void startSearch(String initialQuery, boolean selectInitialQuery, 1184 Bundle appSearchData, boolean globalSearch) { 1185 1186 showWorkspace(true); 1187 1188 if (initialQuery == null) { 1189 // Use any text typed in the launcher as the initial query 1190 initialQuery = getTypedText(); 1191 clearTypedText(); 1192 } 1193 if (appSearchData == null) { 1194 appSearchData = new Bundle(); 1195 appSearchData.putString(Search.SOURCE, "launcher-search"); 1196 } 1197 1198 final SearchManager searchManager = 1199 (SearchManager) getSystemService(Context.SEARCH_SERVICE); 1200 searchManager.startSearch(initialQuery, selectInitialQuery, getComponentName(), 1201 appSearchData, globalSearch); 1202 } 1203 1204 /** 1205 * Indicates that we want global search for this activity by setting the globalSearch 1206 * argument for {@link #startSearch} to true. 1207 */ 1208 1209 @Override 1210 public boolean onSearchRequested() { 1211 startSearch(null, false, null, true); 1212 return true; 1213 } 1214 1215 public boolean isWorkspaceLocked() { 1216 return mWorkspaceLoading || mWaitingForResult; 1217 } 1218 1219 private void addItems() { 1220 showWorkspace(true); 1221 showAddDialog(); 1222 } 1223 1224 private void resetAddInfo() { 1225 mPendingAddInfo.container = ItemInfo.NO_ID; 1226 mPendingAddInfo.screen = -1; 1227 mPendingAddInfo.cellX = mPendingAddInfo.cellY = -1; 1228 mPendingAddInfo.spanX = mPendingAddInfo.spanY = -1; 1229 mPendingAddInfo.dropPos = null; 1230 } 1231 1232 private void manageApps() { 1233 startActivity(new Intent(android.provider.Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS)); 1234 } 1235 1236 void addAppWidgetFromPick(Intent data) { 1237 // TODO: catch bad widget exception when sent 1238 int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); 1239 // TODO: Is this log message meaningful? 1240 if (LOGD) Log.d(TAG, "dumping extras content=" + data.getExtras()); 1241 addAppWidgetImpl(appWidgetId, null); 1242 } 1243 1244 void addAppWidgetImpl(int appWidgetId, PendingAddWidgetInfo info) { 1245 AppWidgetProviderInfo appWidget = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 1246 1247 if (appWidget.configure != null) { 1248 // Launch over to configure widget, if needed 1249 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); 1250 intent.setComponent(appWidget.configure); 1251 intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 1252 if (info != null) { 1253 if (info.mimeType != null && !info.mimeType.isEmpty()) { 1254 intent.putExtra( 1255 InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA_MIME_TYPE, 1256 info.mimeType); 1257 1258 final String mimeType = info.mimeType; 1259 final ClipData clipData = (ClipData) info.configurationData; 1260 final ClipDescription clipDesc = clipData.getDescription(); 1261 for (int i = 0; i < clipDesc.getMimeTypeCount(); ++i) { 1262 if (clipDesc.getMimeType(i).equals(mimeType)) { 1263 final ClipData.Item item = clipData.getItemAt(i); 1264 final CharSequence stringData = item.getText(); 1265 final Uri uriData = item.getUri(); 1266 final Intent intentData = item.getIntent(); 1267 final String key = 1268 InstallWidgetReceiver.EXTRA_APPWIDGET_CONFIGURATION_DATA; 1269 if (uriData != null) { 1270 intent.putExtra(key, uriData); 1271 } else if (intentData != null) { 1272 intent.putExtra(key, intentData); 1273 } else if (stringData != null) { 1274 intent.putExtra(key, stringData); 1275 } 1276 break; 1277 } 1278 } 1279 } 1280 } 1281 1282 startActivityForResultSafely(intent, REQUEST_CREATE_APPWIDGET); 1283 } else { 1284 // Otherwise just add it 1285 completeAddAppWidget(appWidgetId, info.container, info.screen); 1286 1287 // Exit spring loaded mode if necessary after adding the widget 1288 exitSpringLoadedDragModeDelayed(true, false); 1289 } 1290 } 1291 1292 /** 1293 * Process a shortcut drop. 1294 * 1295 * @param componentName The name of the component 1296 * @param screen The screen where it should be added 1297 * @param cell The cell it should be added to, optional 1298 * @param position The location on the screen where it was dropped, optional 1299 */ 1300 void processShortcutFromDrop(ComponentName componentName, long container, int screen, 1301 int[] cell, int[] loc) { 1302 resetAddInfo(); 1303 mPendingAddInfo.container = container; 1304 mPendingAddInfo.screen = screen; 1305 mPendingAddInfo.dropPos = loc; 1306 1307 if (cell != null) { 1308 mPendingAddInfo.cellX = cell[0]; 1309 mPendingAddInfo.cellY = cell[1]; 1310 } 1311 1312 Intent createShortcutIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); 1313 createShortcutIntent.setComponent(componentName); 1314 processShortcut(createShortcutIntent); 1315 } 1316 1317 /** 1318 * Process a widget drop. 1319 * 1320 * @param info The PendingAppWidgetInfo of the widget being added. 1321 * @param screen The screen where it should be added 1322 * @param cell The cell it should be added to, optional 1323 * @param position The location on the screen where it was dropped, optional 1324 */ 1325 void addAppWidgetFromDrop(PendingAddWidgetInfo info, long container, int screen, 1326 int[] cell, int[] loc) { 1327 resetAddInfo(); 1328 mPendingAddInfo.container = info.container = container; 1329 mPendingAddInfo.screen = info.screen = screen; 1330 mPendingAddInfo.dropPos = loc; 1331 if (cell != null) { 1332 mPendingAddInfo.cellX = cell[0]; 1333 mPendingAddInfo.cellY = cell[1]; 1334 } 1335 1336 int appWidgetId = getAppWidgetHost().allocateAppWidgetId(); 1337 AppWidgetManager.getInstance(this).bindAppWidgetId(appWidgetId, info.componentName); 1338 addAppWidgetImpl(appWidgetId, info); 1339 } 1340 1341 void processShortcut(Intent intent) { 1342 // Handle case where user selected "Applications" 1343 String applicationName = getResources().getString(R.string.group_applications); 1344 String shortcutName = intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); 1345 1346 if (applicationName != null && applicationName.equals(shortcutName)) { 1347 Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); 1348 mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); 1349 1350 Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY); 1351 pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent); 1352 pickIntent.putExtra(Intent.EXTRA_TITLE, getText(R.string.title_select_application)); 1353 startActivityForResultSafely(pickIntent, REQUEST_PICK_APPLICATION); 1354 } else { 1355 startActivityForResultSafely(intent, REQUEST_CREATE_SHORTCUT); 1356 } 1357 } 1358 1359 void processWallpaper(Intent intent) { 1360 startActivityForResult(intent, REQUEST_PICK_WALLPAPER); 1361 } 1362 1363 FolderIcon addFolder(CellLayout layout, long container, final int screen, int cellX, 1364 int cellY) { 1365 final FolderInfo folderInfo = new FolderInfo(); 1366 folderInfo.title = getText(R.string.folder_name); 1367 1368 // Update the model 1369 LauncherModel.addItemToDatabase(Launcher.this, folderInfo, container, screen, cellX, cellY, 1370 false); 1371 sFolders.put(folderInfo.id, folderInfo); 1372 1373 // Create the view 1374 FolderIcon newFolder = 1375 FolderIcon.fromXml(R.layout.folder_icon, this, layout, folderInfo, mIconCache); 1376 mWorkspace.addInScreen(newFolder, container, screen, cellX, cellY, 1, 1, 1377 isWorkspaceLocked()); 1378 return newFolder; 1379 } 1380 1381 void removeFolder(FolderInfo folder) { 1382 sFolders.remove(folder.id); 1383 } 1384 1385 private void showNotifications() { 1386 final StatusBarManager statusBar = (StatusBarManager) getSystemService(STATUS_BAR_SERVICE); 1387 if (statusBar != null) { 1388 statusBar.expand(); 1389 } 1390 } 1391 1392 private void startWallpaper() { 1393 showWorkspace(true); 1394 final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER); 1395 Intent chooser = Intent.createChooser(pickWallpaper, 1396 getText(R.string.chooser_wallpaper)); 1397 // NOTE: Adds a configure option to the chooser if the wallpaper supports it 1398 // Removed in Eclair MR1 1399// WallpaperManager wm = (WallpaperManager) 1400// getSystemService(Context.WALLPAPER_SERVICE); 1401// WallpaperInfo wi = wm.getWallpaperInfo(); 1402// if (wi != null && wi.getSettingsActivity() != null) { 1403// LabeledIntent li = new LabeledIntent(getPackageName(), 1404// R.string.configure_wallpaper, 0); 1405// li.setClassName(wi.getPackageName(), wi.getSettingsActivity()); 1406// chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li }); 1407// } 1408 startActivityForResult(chooser, REQUEST_PICK_WALLPAPER); 1409 } 1410 1411 /** 1412 * Registers various content observers. The current implementation registers 1413 * only a favorites observer to keep track of the favorites applications. 1414 */ 1415 private void registerContentObservers() { 1416 ContentResolver resolver = getContentResolver(); 1417 resolver.registerContentObserver(LauncherProvider.CONTENT_APPWIDGET_RESET_URI, 1418 true, mWidgetObserver); 1419 } 1420 1421 @Override 1422 public boolean dispatchKeyEvent(KeyEvent event) { 1423 if (event.getAction() == KeyEvent.ACTION_DOWN) { 1424 switch (event.getKeyCode()) { 1425 case KeyEvent.KEYCODE_HOME: 1426 return true; 1427 case KeyEvent.KEYCODE_VOLUME_DOWN: 1428 if (SystemProperties.getInt("debug.launcher2.dumpstate", 0) != 0) { 1429 dumpState(); 1430 return true; 1431 } 1432 break; 1433 } 1434 } else if (event.getAction() == KeyEvent.ACTION_UP) { 1435 switch (event.getKeyCode()) { 1436 case KeyEvent.KEYCODE_HOME: 1437 return true; 1438 } 1439 } 1440 1441 return super.dispatchKeyEvent(event); 1442 } 1443 1444 @Override 1445 public void onBackPressed() { 1446 if (mState == State.APPS_CUSTOMIZE) { 1447 showWorkspace(true); 1448 } else if (mWorkspace.getOpenFolder() != null) { 1449 Folder openFolder = mWorkspace.getOpenFolder(); 1450 if (openFolder.isEditingName()) { 1451 openFolder.dismissEditingName(); 1452 } else { 1453 closeFolder(); 1454 } 1455 } else { 1456 mWorkspace.exitWidgetResizeMode(); 1457 1458 // Back button is a no-op here, but give at least some feedback for the button press 1459 mWorkspace.showOutlinesTemporarily(); 1460 } 1461 } 1462 1463 /** 1464 * Re-listen when widgets are reset. 1465 */ 1466 private void onAppWidgetReset() { 1467 if (mAppWidgetHost != null) { 1468 mAppWidgetHost.startListening(); 1469 } 1470 } 1471 1472 /** 1473 * Go through the and disconnect any of the callbacks in the drawables and the views or we 1474 * leak the previous Home screen on orientation change. 1475 */ 1476 private void unbindWorkspaceAndHotseatItems() { 1477 LauncherModel.unbindWorkspaceItems(); 1478 } 1479 1480 /** 1481 * Launches the intent referred by the clicked shortcut. 1482 * 1483 * @param v The view representing the clicked shortcut. 1484 */ 1485 public void onClick(View v) { 1486 // Make sure that rogue clicks don't get through while allapps is launching, or after the 1487 // view has detached (it's possible for this to happen if the view is removed mid touch). 1488 if (v.getWindowToken() == null) { 1489 return; 1490 } 1491 1492 if (mWorkspace.isSwitchingState()) { 1493 return; 1494 } 1495 1496 Object tag = v.getTag(); 1497 if (tag instanceof ShortcutInfo) { 1498 // Open shortcut 1499 final Intent intent = ((ShortcutInfo) tag).intent; 1500 int[] pos = new int[2]; 1501 v.getLocationOnScreen(pos); 1502 intent.setSourceBounds(new Rect(pos[0], pos[1], 1503 pos[0] + v.getWidth(), pos[1] + v.getHeight())); 1504 boolean success = startActivitySafely(intent, tag); 1505 1506 if (success && v instanceof BubbleTextView) { 1507 mWaitingForResume = (BubbleTextView) v; 1508 mWaitingForResume.setStayPressed(true); 1509 } 1510 } else if (tag instanceof FolderInfo) { 1511 if (v instanceof FolderIcon) { 1512 FolderIcon fi = (FolderIcon) v; 1513 handleFolderClick(fi); 1514 } 1515 } else if (v == mAllAppsButton) { 1516 if (mState == State.APPS_CUSTOMIZE) { 1517 showWorkspace(true); 1518 } else { 1519 showAllApps(true); 1520 } 1521 } 1522 } 1523 1524 public boolean onTouch(View v, MotionEvent event) { 1525 // this is an intercepted event being forwarded from mWorkspace; 1526 // clicking anywhere on the workspace causes the customization drawer to slide down 1527 showWorkspace(true); 1528 return false; 1529 } 1530 1531 /** 1532 * Event handler for the search button 1533 * 1534 * @param v The view that was clicked. 1535 */ 1536 public void onClickSearchButton(View v) { 1537 startSearch(null, false, null, true); 1538 // Use a custom animation for launching search 1539 overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast); 1540 } 1541 1542 /** 1543 * Event handler for the voice button 1544 * 1545 * @param v The view that was clicked. 1546 */ 1547 public void onClickVoiceButton(View v) { 1548 startVoiceSearch(); 1549 } 1550 1551 private void startVoiceSearch() { 1552 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); 1553 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1554 startActivity(intent); 1555 } 1556 1557 /** 1558 * Event handler for the "grid" button that appears on the home screen, which 1559 * enters all apps mode. 1560 * 1561 * @param v The view that was clicked. 1562 */ 1563 public void onClickAllAppsButton(View v) { 1564 showAllApps(true); 1565 } 1566 1567 public void onClickAppMarketButton(View v) { 1568 if (mAppMarketIntent != null) { 1569 startActivitySafely(mAppMarketIntent, "app market"); 1570 } 1571 } 1572 1573 void startApplicationDetailsActivity(ComponentName componentName) { 1574 String packageName = componentName.getPackageName(); 1575 Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, 1576 Uri.fromParts("package", packageName, null)); 1577 startActivity(intent); 1578 } 1579 1580 void startApplicationUninstallActivity(ApplicationInfo appInfo) { 1581 if ((appInfo.flags & ApplicationInfo.DOWNLOADED_FLAG) == 0) { 1582 // System applications cannot be installed. For now, show a toast explaining that. 1583 // We may give them the option of disabling apps this way. 1584 int messageId = R.string.uninstall_system_app_text; 1585 Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); 1586 } else { 1587 String packageName = appInfo.componentName.getPackageName(); 1588 String className = appInfo.componentName.getClassName(); 1589 Intent intent = new Intent( 1590 Intent.ACTION_DELETE, Uri.fromParts("package", packageName, className)); 1591 startActivity(intent); 1592 } 1593 } 1594 1595 boolean startActivitySafely(Intent intent, Object tag) { 1596 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 1597 try { 1598 startActivity(intent); 1599 return true; 1600 } catch (ActivityNotFoundException e) { 1601 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1602 Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e); 1603 } catch (SecurityException e) { 1604 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1605 Log.e(TAG, "Launcher does not have the permission to launch " + intent + 1606 ". Make sure to create a MAIN intent-filter for the corresponding activity " + 1607 "or use the exported attribute for this activity. " 1608 + "tag="+ tag + " intent=" + intent, e); 1609 } 1610 return false; 1611 } 1612 1613 void startActivityForResultSafely(Intent intent, int requestCode) { 1614 try { 1615 startActivityForResult(intent, requestCode); 1616 } catch (ActivityNotFoundException e) { 1617 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1618 } catch (SecurityException e) { 1619 Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); 1620 Log.e(TAG, "Launcher does not have the permission to launch " + intent + 1621 ". Make sure to create a MAIN intent-filter for the corresponding activity " + 1622 "or use the exported attribute for this activity.", e); 1623 } 1624 } 1625 1626 private void handleFolderClick(FolderIcon folderIcon) { 1627 final FolderInfo info = folderIcon.mInfo; 1628 if (!info.opened) { 1629 // Close any open folder 1630 closeFolder(); 1631 // Open the requested folder 1632 openFolder(folderIcon); 1633 } else { 1634 // Find the open folder... 1635 Folder openFolder = mWorkspace.getFolderForTag(info); 1636 int folderScreen; 1637 if (openFolder != null) { 1638 folderScreen = mWorkspace.getPageForView(openFolder); 1639 // .. and close it 1640 closeFolder(openFolder); 1641 if (folderScreen != mWorkspace.getCurrentPage()) { 1642 // Close any folder open on the current screen 1643 closeFolder(); 1644 // Pull the folder onto this screen 1645 openFolder(folderIcon); 1646 } 1647 } 1648 } 1649 } 1650 1651 private void growAndFadeOutFolderIcon(FolderIcon fi) { 1652 if (fi == null) return; 1653 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 0); 1654 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.5f); 1655 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.5f); 1656 1657 FolderInfo info = (FolderInfo) fi.getTag(); 1658 if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1659 CellLayout cl = (CellLayout) fi.getParent().getParent(); 1660 cl.setFolderLeaveBehindCell(info.cellX, info.cellY); 1661 } 1662 1663 ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY); 1664 oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); 1665 oa.start(); 1666 } 1667 1668 private void shrinkAndFadeInFolderIcon(FolderIcon fi) { 1669 if (fi == null) return; 1670 PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f); 1671 PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f); 1672 PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f); 1673 1674 FolderInfo info = (FolderInfo) fi.getTag(); 1675 CellLayout cl = null; 1676 if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1677 cl = (CellLayout) fi.getParent().getParent(); 1678 } 1679 1680 final CellLayout layout = cl; 1681 ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(fi, alpha, scaleX, scaleY); 1682 oa.setDuration(getResources().getInteger(R.integer.config_folderAnimDuration)); 1683 oa.addListener(new AnimatorListenerAdapter() { 1684 @Override 1685 public void onAnimationEnd(Animator animation) { 1686 if (layout != null) { 1687 layout.clearFolderLeaveBehind(); 1688 } 1689 } 1690 }); 1691 oa.start(); 1692 } 1693 1694 /** 1695 * Opens the user folder described by the specified tag. The opening of the folder 1696 * is animated relative to the specified View. If the View is null, no animation 1697 * is played. 1698 * 1699 * @param folderInfo The FolderInfo describing the folder to open. 1700 */ 1701 public void openFolder(FolderIcon folderIcon) { 1702 Folder folder = folderIcon.mFolder; 1703 FolderInfo info = folder.mInfo; 1704 1705 growAndFadeOutFolderIcon(folderIcon); 1706 info.opened = true; 1707 1708 // Just verify that the folder hasn't already been added to the DragLayer. 1709 // There was a one-off crash where the folder had a parent already. 1710 if (folder.getParent() == null) { 1711 mDragLayer.addView(folder); 1712 mDragController.addDropTarget((DropTarget) folder); 1713 } else { 1714 Log.w(TAG, "Opening folder (" + folder + ") which already has a parent (" + 1715 folder.getParent() + ")."); 1716 } 1717 folder.animateOpen(); 1718 } 1719 1720 public void closeFolder() { 1721 Folder folder = mWorkspace.getOpenFolder(); 1722 if (folder != null) { 1723 closeFolder(folder); 1724 } 1725 } 1726 1727 void closeFolder(Folder folder) { 1728 folder.getInfo().opened = false; 1729 1730 ViewGroup parent = (ViewGroup) folder.getParent().getParent(); 1731 if (parent != null) { 1732 FolderIcon fi = (FolderIcon) mWorkspace.getViewForTag(folder.mInfo); 1733 shrinkAndFadeInFolderIcon(fi); 1734 } 1735 folder.animateClosed(); 1736 } 1737 1738 public boolean onLongClick(View v) { 1739 if (mState != State.WORKSPACE) { 1740 return false; 1741 } 1742 1743 if (isWorkspaceLocked()) { 1744 return false; 1745 } 1746 1747 if (!(v instanceof CellLayout)) { 1748 v = (View) v.getParent().getParent(); 1749 } 1750 1751 resetAddInfo(); 1752 CellLayout.CellInfo longClickCellInfo = (CellLayout.CellInfo) v.getTag(); 1753 // This happens when long clicking an item with the dpad/trackball 1754 if (longClickCellInfo == null) { 1755 return true; 1756 } 1757 1758 // The hotseat touch handling does not go through Workspace, and we always allow long press 1759 // on hotseat items. 1760 final View itemUnderLongClick = longClickCellInfo.cell; 1761 boolean allowLongPress = isHotseatLayout(v) || mWorkspace.allowLongPress(); 1762 if (allowLongPress && !mDragController.isDragging()) { 1763 if (itemUnderLongClick == null) { 1764 // User long pressed on empty space 1765 mWorkspace.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, 1766 HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING); 1767 startWallpaper(); 1768 } else { 1769 if (!(itemUnderLongClick instanceof Folder)) { 1770 // User long pressed on an item 1771 mWorkspace.startDrag(longClickCellInfo); 1772 } 1773 } 1774 } 1775 return true; 1776 } 1777 1778 boolean isHotseatLayout(View layout) { 1779 return mHotseat != null && layout != null && 1780 (layout instanceof CellLayout) && (layout == mHotseat.getLayout()); 1781 } 1782 Hotseat getHotseat() { 1783 return mHotseat; 1784 } 1785 1786 /** 1787 * Returns the CellLayout of the specified container at the specified screen. 1788 */ 1789 CellLayout getCellLayout(long container, int screen) { 1790 if (container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { 1791 if (mHotseat != null) { 1792 return mHotseat.getLayout(); 1793 } else { 1794 return null; 1795 } 1796 } else { 1797 return (CellLayout) mWorkspace.getChildAt(screen); 1798 } 1799 } 1800 1801 Workspace getWorkspace() { 1802 return mWorkspace; 1803 } 1804 1805 @Override 1806 protected Dialog onCreateDialog(int id) { 1807 switch (id) { 1808 case DIALOG_CREATE_SHORTCUT: 1809 return new CreateShortcut().createDialog(); 1810 case DIALOG_RENAME_FOLDER: 1811 return new RenameFolder().createDialog(); 1812 } 1813 1814 return super.onCreateDialog(id); 1815 } 1816 1817 @Override 1818 protected void onPrepareDialog(int id, Dialog dialog) { 1819 switch (id) { 1820 case DIALOG_CREATE_SHORTCUT: 1821 break; 1822 case DIALOG_RENAME_FOLDER: 1823 if (mFolderInfo != null) { 1824 EditText input = (EditText) dialog.findViewById(R.id.folder_name); 1825 final CharSequence text = mFolderInfo.title; 1826 input.setText(text); 1827 input.setSelection(0, text.length()); 1828 } 1829 break; 1830 } 1831 } 1832 1833 void showRenameDialog(FolderInfo info) { 1834 mFolderInfo = info; 1835 mWaitingForResult = true; 1836 showDialog(DIALOG_RENAME_FOLDER); 1837 } 1838 1839 private void showAddDialog() { 1840 resetAddInfo(); 1841 mPendingAddInfo.container = LauncherSettings.Favorites.CONTAINER_DESKTOP; 1842 mPendingAddInfo.screen = mWorkspace.getCurrentPage(); 1843 mWaitingForResult = true; 1844 showDialog(DIALOG_CREATE_SHORTCUT); 1845 } 1846 1847 private class RenameFolder { 1848 private EditText mInput; 1849 1850 Dialog createDialog() { 1851 final View layout = View.inflate(Launcher.this, R.layout.rename_folder, null); 1852 mInput = (EditText) layout.findViewById(R.id.folder_name); 1853 1854 AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this); 1855 builder.setIcon(0); 1856 builder.setTitle(getString(R.string.rename_folder_title)); 1857 builder.setCancelable(true); 1858 builder.setOnCancelListener(new Dialog.OnCancelListener() { 1859 public void onCancel(DialogInterface dialog) { 1860 cleanup(); 1861 } 1862 }); 1863 builder.setNegativeButton(getString(R.string.cancel_action), 1864 new Dialog.OnClickListener() { 1865 public void onClick(DialogInterface dialog, int which) { 1866 cleanup(); 1867 } 1868 } 1869 ); 1870 builder.setPositiveButton(getString(R.string.rename_action), 1871 new Dialog.OnClickListener() { 1872 public void onClick(DialogInterface dialog, int which) { 1873 changeFolderName(); 1874 } 1875 } 1876 ); 1877 builder.setView(layout); 1878 1879 final AlertDialog dialog = builder.create(); 1880 dialog.setOnShowListener(new DialogInterface.OnShowListener() { 1881 public void onShow(DialogInterface dialog) { 1882 mWaitingForResult = true; 1883 mInput.requestFocus(); 1884 InputMethodManager inputManager = (InputMethodManager) 1885 getSystemService(Context.INPUT_METHOD_SERVICE); 1886 inputManager.showSoftInput(mInput, 0); 1887 } 1888 }); 1889 1890 return dialog; 1891 } 1892 1893 private void changeFolderName() { 1894 final String name = mInput.getText().toString(); 1895 if (!TextUtils.isEmpty(name)) { 1896 // Make sure we have the right folder info 1897 mFolderInfo = sFolders.get(mFolderInfo.id); 1898 mFolderInfo.title = name; 1899 LauncherModel.updateItemInDatabase(Launcher.this, mFolderInfo); 1900 1901 if (mWorkspaceLoading) { 1902 lockAllApps(); 1903 mModel.startLoader(Launcher.this, false); 1904 } else { 1905 final FolderIcon folderIcon = (FolderIcon) 1906 mWorkspace.getViewForTag(mFolderInfo); 1907 if (folderIcon != null) { 1908 // TODO: At some point we'll probably want some version of setting 1909 // the text for a folder icon. 1910 //folderIcon.setText(name); 1911 getWorkspace().requestLayout(); 1912 } else { 1913 lockAllApps(); 1914 mWorkspaceLoading = true; 1915 mModel.startLoader(Launcher.this, false); 1916 } 1917 } 1918 } 1919 cleanup(); 1920 } 1921 1922 private void cleanup() { 1923 dismissDialog(DIALOG_RENAME_FOLDER); 1924 mWaitingForResult = false; 1925 mFolderInfo = null; 1926 } 1927 } 1928 1929 // Now a part of LauncherModel.Callbacks. Used to reorder loading steps. 1930 public boolean isAllAppsVisible() { 1931 return (mState == State.APPS_CUSTOMIZE); 1932 } 1933 1934 // AllAppsView.Watcher 1935 public void zoomed(float zoom) { 1936 if (zoom == 1.0f) { 1937 mWorkspace.setVisibility(View.GONE); 1938 } 1939 } 1940 1941 /** 1942 * Helper method for the cameraZoomIn/cameraZoomOut animations 1943 * @param view The view being animated 1944 * @param state The state that we are moving in or out of (eg. APPS_CUSTOMIZE) 1945 * @param scaleFactor The scale factor used for the zoom 1946 */ 1947 private void setPivotsForZoom(View view, State state, float scaleFactor) { 1948 final int height = view.getHeight(); 1949 1950 view.setPivotX(view.getWidth() / 2.0f); 1951 // Set pivotY so that at the starting zoom factor, the view is partially 1952 // visible. Modifying initialHeightFactor changes how much of the view is 1953 // initially showing, and hence the perceived angle from which the view enters. 1954 if (state == State.APPS_CUSTOMIZE) { 1955 final float initialHeightFactor = 0.175f; 1956 view.setPivotY((1 - initialHeightFactor) * height); 1957 } else { 1958 final float initialHeightFactor = 0.2f; 1959 view.setPivotY(-initialHeightFactor * height); 1960 } 1961 } 1962 1963 /** 1964 * Zoom the camera out from the workspace to reveal 'toView'. 1965 * Assumes that the view to show is anchored at either the very top or very bottom 1966 * of the screen. 1967 * @param toState The state to zoom out to. Must be APPS_CUSTOMIZE. 1968 */ 1969 private void cameraZoomOut(State toState, boolean animated, final boolean springLoaded) { 1970 final Resources res = getResources(); 1971 1972 final int duration = res.getInteger(R.integer.config_appsCustomizeZoomInTime); 1973 final int fadeDuration = res.getInteger(R.integer.config_appsCustomizeFadeInTime); 1974 final float scale = (float) res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); 1975 final View toView = mAppsCustomizeTabHost; 1976 1977 setPivotsForZoom(toView, toState, scale); 1978 1979 // Shrink workspaces away if going to AppsCustomize from workspace 1980 mWorkspace.shrink(Workspace.State.SMALL, animated); 1981 hideHotseat(animated); 1982 1983 if (animated) { 1984 final ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 1985 scaleAnim.setInterpolator(new Workspace.ZoomOutInterpolator()); 1986 scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1987 public void onAnimationUpdate(float a, float b) { 1988 ((View) toView.getParent()).fastInvalidate(); 1989 toView.setFastScaleX(a * scale + b * 1f); 1990 toView.setFastScaleY(a * scale + b * 1f); 1991 } 1992 }); 1993 1994 toView.setVisibility(View.VISIBLE); 1995 toView.setFastAlpha(0f); 1996 ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(fadeDuration); 1997 alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); 1998 alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 1999 public void onAnimationUpdate(float a, float b) { 2000 // don't need to invalidate because we do so above 2001 toView.setFastAlpha(a * 0f + b * 1f); 2002 } 2003 }); 2004 alphaAnim.start(); 2005 2006 if (toView instanceof LauncherTransitionable) { 2007 ((LauncherTransitionable) toView).onLauncherTransitionStart(scaleAnim, false); 2008 } 2009 scaleAnim.addListener(new AnimatorListenerAdapter() { 2010 @Override 2011 public void onAnimationStart(Animator animation) { 2012 // Prepare the position 2013 toView.setTranslationX(0.0f); 2014 toView.setTranslationY(0.0f); 2015 toView.setVisibility(View.VISIBLE); 2016 toView.bringToFront(); 2017 } 2018 @Override 2019 public void onAnimationEnd(Animator animation) { 2020 // If we don't set the final scale values here, if this animation is cancelled 2021 // it will have the wrong scale value and subsequent cameraPan animations will 2022 // not fix that 2023 toView.setScaleX(1.0f); 2024 toView.setScaleY(1.0f); 2025 if (toView instanceof LauncherTransitionable) { 2026 ((LauncherTransitionable) toView).onLauncherTransitionEnd(scaleAnim, false); 2027 } 2028 2029 if (!springLoaded && !LauncherApplication.isScreenLarge()) { 2030 // Hide the workspace scrollbar 2031 mWorkspace.hideScrollingIndicator(true); 2032 mWorkspace.hideDockDivider(true); 2033 } 2034 } 2035 }); 2036 2037 // toView should appear right at the end of the workspace shrink animation 2038 final int startDelay = 0; 2039 2040 if (mStateAnimation != null) mStateAnimation.cancel(); 2041 mStateAnimation = new AnimatorSet(); 2042 mStateAnimation.play(scaleAnim).after(startDelay); 2043 mStateAnimation.start(); 2044 } else { 2045 toView.setTranslationX(0.0f); 2046 toView.setTranslationY(0.0f); 2047 toView.setScaleX(1.0f); 2048 toView.setScaleY(1.0f); 2049 toView.setVisibility(View.VISIBLE); 2050 toView.bringToFront(); 2051 if (toView instanceof LauncherTransitionable) { 2052 ((LauncherTransitionable) toView).onLauncherTransitionStart(null, false); 2053 ((LauncherTransitionable) toView).onLauncherTransitionEnd(null, false); 2054 2055 if (!springLoaded && !LauncherApplication.isScreenLarge()) { 2056 // Hide the workspace scrollbar 2057 mWorkspace.hideScrollingIndicator(true); 2058 mWorkspace.hideDockDivider(true); 2059 } 2060 } 2061 } 2062 } 2063 2064 /** 2065 * Zoom the camera back into the workspace, hiding 'fromView'. 2066 * This is the opposite of cameraZoomOut. 2067 * @param fromState The current state (must be APPS_CUSTOMIZE). 2068 * @param animated If true, the transition will be animated. 2069 */ 2070 private void cameraZoomIn(State fromState, boolean animated, final boolean springLoaded) { 2071 Resources res = getResources(); 2072 2073 final int duration = res.getInteger(R.integer.config_appsCustomizeZoomOutTime); 2074 final float scaleFactor = (float) 2075 res.getInteger(R.integer.config_appsCustomizeZoomScaleFactor); 2076 final View fromView = mAppsCustomizeTabHost; 2077 2078 setPivotsForZoom(fromView, fromState, scaleFactor); 2079 2080 if (!springLoaded) { 2081 mWorkspace.unshrink(animated); 2082 } 2083 showHotseat(animated); 2084 if (animated) { 2085 if (mStateAnimation != null) mStateAnimation.cancel(); 2086 mStateAnimation = new AnimatorSet(); 2087 2088 final float oldScaleX = fromView.getScaleX(); 2089 final float oldScaleY = fromView.getScaleY(); 2090 2091 ValueAnimator scaleAnim = ValueAnimator.ofFloat(0f, 1f).setDuration(duration); 2092 scaleAnim.setInterpolator(new Workspace.ZoomInInterpolator()); 2093 scaleAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 2094 public void onAnimationUpdate(float a, float b) { 2095 ((View)fromView.getParent()).fastInvalidate(); 2096 fromView.setFastScaleX(a * oldScaleX + b * scaleFactor); 2097 fromView.setFastScaleY(a * oldScaleY + b * scaleFactor); 2098 } 2099 }); 2100 final ValueAnimator alphaAnim = ValueAnimator.ofFloat(0f, 1f); 2101 alphaAnim.setDuration(res.getInteger(R.integer.config_appsCustomizeFadeOutTime)); 2102 alphaAnim.setInterpolator(new DecelerateInterpolator(1.5f)); 2103 alphaAnim.addUpdateListener(new LauncherAnimatorUpdateListener() { 2104 public void onAnimationUpdate(float a, float b) { 2105 // don't need to invalidate because we do so above 2106 fromView.setFastAlpha(a * 1f + b * 0f); 2107 } 2108 }); 2109 if (fromView instanceof LauncherTransitionable) { 2110 ((LauncherTransitionable) fromView).onLauncherTransitionStart(alphaAnim, true); 2111 } 2112 alphaAnim.addListener(new AnimatorListenerAdapter() { 2113 @Override 2114 public void onAnimationStart(android.animation.Animator animation) { 2115 if (!springLoaded) { 2116 mWorkspace.showDockDivider(false); 2117 } 2118 } 2119 @Override 2120 public void onAnimationEnd(Animator animation) { 2121 fromView.setVisibility(View.GONE); 2122 if (fromView instanceof LauncherTransitionable) { 2123 ((LauncherTransitionable) fromView).onLauncherTransitionEnd(alphaAnim,true); 2124 } 2125 mWorkspace.flashScrollingIndicator(); 2126 } 2127 }); 2128 2129 mStateAnimation.playTogether(scaleAnim, alphaAnim); 2130 mStateAnimation.start(); 2131 } else { 2132 fromView.setVisibility(View.GONE); 2133 if (fromView instanceof LauncherTransitionable) { 2134 ((LauncherTransitionable) fromView).onLauncherTransitionStart(null, true); 2135 ((LauncherTransitionable) fromView).onLauncherTransitionEnd(null, true); 2136 2137 if (!springLoaded && !LauncherApplication.isScreenLarge()) { 2138 // Flash the workspace scrollbar 2139 mWorkspace.showDockDivider(true); 2140 mWorkspace.flashScrollingIndicator(); 2141 } 2142 } 2143 } 2144 } 2145 2146 void showWorkspace(boolean animated) { 2147 showWorkspace(animated, null); 2148 } 2149 2150 void showWorkspace(boolean animated, CellLayout layout) { 2151 if (layout != null) { 2152 // always animated, but that's ok since we never specify a layout and 2153 // want no animation 2154 mWorkspace.unshrink(layout); 2155 } else { 2156 mWorkspace.unshrink(animated); 2157 } 2158 if (mState == State.APPS_CUSTOMIZE) { 2159 closeAllApps(animated); 2160 } 2161 2162 // Change the state *after* we've called all the transition code 2163 mState = State.WORKSPACE; 2164 2165 // Resume the auto-advance of widgets 2166 mUserPresent = true; 2167 updateRunning(); 2168 2169 // send an accessibility event to announce the context change 2170 getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 2171 } 2172 2173 void enterSpringLoadedDragMode(CellLayout layout) { 2174 if (mState == State.APPS_CUSTOMIZE) { 2175 mWorkspace.enterSpringLoadedDragMode(layout); 2176 cameraZoomIn(State.APPS_CUSTOMIZE, true, true); 2177 mState = State.APPS_CUSTOMIZE_SPRING_LOADED; 2178 } 2179 // Otherwise, we are not in spring loaded mode, so don't do anything. 2180 } 2181 void exitSpringLoadedDragModeDelayed(final boolean successfulDrop, boolean extendedDelay) { 2182 mWorkspace.postDelayed(new Runnable() { 2183 @Override 2184 public void run() { 2185 exitSpringLoadedDragMode(); 2186 2187 if (successfulDrop) { 2188 // Before we show workspace, hide all apps again because 2189 // exitSpringLoadedDragMode made it visible. This is a bit hacky; we should 2190 // clean up our state transition functions 2191 mAppsCustomizeTabHost.setVisibility(View.GONE); 2192 showWorkspace(true); 2193 } 2194 } 2195 }, (extendedDelay ? 2196 EXIT_SPRINGLOADED_MODE_LONG_TIMEOUT : 2197 EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT)); 2198 } 2199 void exitSpringLoadedDragMode() { 2200 if (mState == State.APPS_CUSTOMIZE_SPRING_LOADED) { 2201 mWorkspace.exitSpringLoadedDragMode(Workspace.State.SMALL); 2202 cameraZoomOut(State.APPS_CUSTOMIZE, true, true); 2203 mState = State.APPS_CUSTOMIZE; 2204 } 2205 // Otherwise, we are not in spring loaded mode, so don't do anything. 2206 } 2207 2208 public boolean isAllAppsCustomizeOpen() { 2209 return mState == State.APPS_CUSTOMIZE; 2210 } 2211 2212 /** 2213 * Shows the hotseat area. 2214 */ 2215 void showHotseat(boolean animated) { 2216 if (!LauncherApplication.isScreenLarge()) { 2217 if (animated) { 2218 int duration = mSearchDeleteBar.getTransitionInDuration(); 2219 mHotseat.animate().alpha(1f).setDuration(duration); 2220 } else { 2221 mHotseat.setAlpha(1f); 2222 } 2223 } 2224 } 2225 2226 /** 2227 * Hides the hotseat area. 2228 */ 2229 void hideHotseat(boolean animated) { 2230 if (!LauncherApplication.isScreenLarge()) { 2231 if (animated) { 2232 int duration = mSearchDeleteBar.getTransitionOutDuration(); 2233 mHotseat.animate().alpha(0f).setDuration(duration); 2234 } else { 2235 mHotseat.setAlpha(0f); 2236 } 2237 } 2238 } 2239 2240 void showAllApps(boolean animated) { 2241 if (mState != State.WORKSPACE) return; 2242 2243 cameraZoomOut(State.APPS_CUSTOMIZE, animated, false); 2244 mAppsCustomizeTabHost.requestFocus(); 2245 2246 // Hide the search bar and hotseat 2247 mSearchDeleteBar.hideSearchBar(animated); 2248 2249 // Change the state *after* we've called all the transition code 2250 mState = State.APPS_CUSTOMIZE; 2251 2252 // Pause the auto-advance of widgets until we are out of AllApps 2253 mUserPresent = false; 2254 updateRunning(); 2255 closeFolder(); 2256 2257 // Send an accessibility event to announce the context change 2258 getWindow().getDecorView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); 2259 } 2260 2261 /** 2262 * Things to test when changing this code. 2263 * - Home from workspace 2264 * - from center screen 2265 * - from other screens 2266 * - Home from all apps 2267 * - from center screen 2268 * - from other screens 2269 * - Back from all apps 2270 * - from center screen 2271 * - from other screens 2272 * - Launch app from workspace and quit 2273 * - with back 2274 * - with home 2275 * - Launch app from all apps and quit 2276 * - with back 2277 * - with home 2278 * - Go to a screen that's not the default, then all 2279 * apps, and launch and app, and go back 2280 * - with back 2281 * -with home 2282 * - On workspace, long press power and go back 2283 * - with back 2284 * - with home 2285 * - On all apps, long press power and go back 2286 * - with back 2287 * - with home 2288 * - On workspace, power off 2289 * - On all apps, power off 2290 * - Launch an app and turn off the screen while in that app 2291 * - Go back with home key 2292 * - Go back with back key TODO: make this not go to workspace 2293 * - From all apps 2294 * - From workspace 2295 * - Enter and exit car mode (becuase it causes an extra configuration changed) 2296 * - From all apps 2297 * - From the center workspace 2298 * - From another workspace 2299 */ 2300 void closeAllApps(boolean animated) { 2301 if (mState == State.APPS_CUSTOMIZE || mState == State.APPS_CUSTOMIZE_SPRING_LOADED) { 2302 mWorkspace.setVisibility(View.VISIBLE); 2303 cameraZoomIn(State.APPS_CUSTOMIZE, animated, false); 2304 2305 // Show the search bar and hotseat 2306 mSearchDeleteBar.showSearchBar(animated); 2307 2308 // Set focus to the AppsCustomize button 2309 if (mAllAppsButton != null) { 2310 mAllAppsButton.requestFocus(); 2311 } 2312 } 2313 } 2314 2315 void lockAllApps() { 2316 // TODO 2317 } 2318 2319 void unlockAllApps() { 2320 // TODO 2321 } 2322 2323 /** 2324 * Add an item from all apps or customize onto the given workspace screen. 2325 * If layout is null, add to the current screen. 2326 */ 2327 void addExternalItemToScreen(ItemInfo itemInfo, final CellLayout layout) { 2328 if (!mWorkspace.addExternalItemToScreen(itemInfo, layout)) { 2329 showOutOfSpaceMessage(); 2330 } else { 2331 layout.animateDrop(); 2332 } 2333 } 2334 2335 private Drawable getExternalPackageToolbarIcon(ComponentName activityName) { 2336 try { 2337 PackageManager packageManager = getPackageManager(); 2338 // Look for the toolbar icon specified in the activity meta-data 2339 Bundle metaData = packageManager.getActivityInfo( 2340 activityName, PackageManager.GET_META_DATA).metaData; 2341 if (metaData != null) { 2342 int iconResId = metaData.getInt(TOOLBAR_ICON_METADATA_NAME); 2343 if (iconResId != 0) { 2344 Resources res = packageManager.getResourcesForActivity(activityName); 2345 return res.getDrawable(iconResId); 2346 } 2347 } 2348 } catch (NameNotFoundException e) { 2349 // This can happen if the activity defines an invalid drawable 2350 Log.w(TAG, "Failed to load toolbar icon; " + activityName.flattenToShortString() + 2351 " not found", e); 2352 } catch (Resources.NotFoundException nfe) { 2353 // This can happen if the activity defines an invalid drawable 2354 Log.w(TAG, "Failed to load toolbar icon from " + activityName.flattenToShortString(), 2355 nfe); 2356 } 2357 return null; 2358 } 2359 2360 // if successful in getting icon, return it; otherwise, set button to use default drawable 2361 private Drawable.ConstantState updateTextButtonWithIconFromExternalActivity( 2362 int buttonId, ComponentName activityName, int fallbackDrawableId) { 2363 TextView button = (TextView) findViewById(buttonId); 2364 Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName); 2365 2366 // If we were unable to find the icon via the meta-data, use a generic one 2367 if (toolbarIcon == null) { 2368 button.setCompoundDrawablesWithIntrinsicBounds(fallbackDrawableId, 0, 0, 0); 2369 return null; 2370 } else { 2371 button.setCompoundDrawablesWithIntrinsicBounds(toolbarIcon, null, null, null); 2372 return toolbarIcon.getConstantState(); 2373 } 2374 } 2375 2376 // if successful in getting icon, return it; otherwise, set button to use default drawable 2377 private Drawable.ConstantState updateButtonWithIconFromExternalActivity( 2378 int buttonId, ComponentName activityName, int fallbackDrawableId) { 2379 ImageView button = (ImageView) findViewById(buttonId); 2380 Drawable toolbarIcon = getExternalPackageToolbarIcon(activityName); 2381 2382 if (button != null) { 2383 // If we were unable to find the icon via the meta-data, use a 2384 // generic one 2385 if (toolbarIcon == null) { 2386 button.setImageResource(fallbackDrawableId); 2387 } else { 2388 button.setImageDrawable(toolbarIcon); 2389 } 2390 } 2391 2392 return toolbarIcon != null ? toolbarIcon.getConstantState() : null; 2393 2394 } 2395 2396 private void updateTextButtonWithDrawable(int buttonId, Drawable.ConstantState d) { 2397 TextView button = (TextView) findViewById(buttonId); 2398 button.setCompoundDrawables(d.newDrawable(getResources()), null, null, null); 2399 } 2400 2401 private void updateButtonWithDrawable(int buttonId, Drawable.ConstantState d) { 2402 ImageView button = (ImageView) findViewById(buttonId); 2403 button.setImageDrawable(d.newDrawable(getResources())); 2404 } 2405 2406 private void updateGlobalSearchIcon() { 2407 final ImageView searchButton = (ImageView) findViewById(R.id.search_button); 2408 final View searchDivider = findViewById(R.id.search_divider); 2409 2410 final SearchManager searchManager = 2411 (SearchManager) getSystemService(Context.SEARCH_SERVICE); 2412 ComponentName activityName = searchManager.getGlobalSearchActivity(); 2413 if (activityName != null) { 2414 sGlobalSearchIcon = updateButtonWithIconFromExternalActivity( 2415 R.id.search_button, activityName, R.drawable.ic_search_normal_holo); 2416 searchButton.setVisibility(View.VISIBLE); 2417 if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE); 2418 } else { 2419 searchButton.setVisibility(View.GONE); 2420 if (searchDivider != null) searchDivider.setVisibility(View.GONE); 2421 } 2422 } 2423 2424 private void updateGlobalSearchIcon(Drawable.ConstantState d) { 2425 updateButtonWithDrawable(R.id.search_button, d); 2426 } 2427 2428 private void updateVoiceSearchIcon() { 2429 final View searchDivider = findViewById(R.id.search_divider); 2430 final View voiceButton = findViewById(R.id.voice_button); 2431 2432 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); 2433 ComponentName activityName = intent.resolveActivity(getPackageManager()); 2434 if (activityName != null) { 2435 sVoiceSearchIcon = updateButtonWithIconFromExternalActivity( 2436 R.id.voice_button, activityName, R.drawable.ic_voice_search_holo); 2437 if (searchDivider != null) searchDivider.setVisibility(View.VISIBLE); 2438 voiceButton.setVisibility(View.VISIBLE); 2439 } else { 2440 if (searchDivider != null) searchDivider.setVisibility(View.GONE); 2441 voiceButton.setVisibility(View.GONE); 2442 } 2443 } 2444 2445 private void updateVoiceSearchIcon(Drawable.ConstantState d) { 2446 updateButtonWithDrawable(R.id.voice_button, d); 2447 } 2448 2449 /** 2450 * Sets the app market icon 2451 */ 2452 private void updateAppMarketIcon() { 2453 final View marketButton = findViewById(R.id.market_button); 2454 Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_APP_MARKET); 2455 // Find the app market activity by resolving an intent. 2456 // (If multiple app markets are installed, it will return the ResolverActivity.) 2457 ComponentName activityName = intent.resolveActivity(getPackageManager()); 2458 if (activityName != null) { 2459 mAppMarketIntent = intent; 2460 sAppMarketIcon = updateTextButtonWithIconFromExternalActivity( 2461 R.id.market_button, activityName, R.drawable.ic_launcher_market_holo); 2462 marketButton.setVisibility(View.VISIBLE); 2463 2464 // Remove the shop icon text in the Phone UI 2465 if (!LauncherApplication.isScreenLarge()) { 2466 ((TextView) marketButton).setText(""); 2467 } 2468 } else { 2469 // We should hide and disable the view so that we don't try and restore the visibility 2470 // of it when we swap between drag & normal states from IconDropTarget subclasses. 2471 marketButton.setVisibility(View.GONE); 2472 marketButton.setEnabled(false); 2473 } 2474 } 2475 2476 private void updateAppMarketIcon(Drawable.ConstantState d) { 2477 updateTextButtonWithDrawable(R.id.market_button, d); 2478 } 2479 2480 /** 2481 * Displays the shortcut creation dialog and launches, if necessary, the 2482 * appropriate activity. 2483 */ 2484 private class CreateShortcut implements DialogInterface.OnClickListener, 2485 DialogInterface.OnCancelListener, DialogInterface.OnDismissListener, 2486 DialogInterface.OnShowListener { 2487 2488 private AddAdapter mAdapter; 2489 2490 Dialog createDialog() { 2491 mAdapter = new AddAdapter(Launcher.this); 2492 2493 final AlertDialog.Builder builder = new AlertDialog.Builder(Launcher.this, 2494 AlertDialog.THEME_HOLO_DARK); 2495 builder.setAdapter(mAdapter, this); 2496 2497 AlertDialog dialog = builder.create(); 2498 dialog.setOnCancelListener(this); 2499 dialog.setOnDismissListener(this); 2500 dialog.setOnShowListener(this); 2501 2502 return dialog; 2503 } 2504 2505 public void onCancel(DialogInterface dialog) { 2506 mWaitingForResult = false; 2507 cleanup(); 2508 } 2509 2510 public void onDismiss(DialogInterface dialog) { 2511 mWaitingForResult = false; 2512 cleanup(); 2513 } 2514 2515 private void cleanup() { 2516 try { 2517 dismissDialog(DIALOG_CREATE_SHORTCUT); 2518 } catch (Exception e) { 2519 // An exception is thrown if the dialog is not visible, which is fine 2520 } 2521 } 2522 2523 /** 2524 * Handle the action clicked in the "Add to home" dialog. 2525 */ 2526 public void onClick(DialogInterface dialog, int which) { 2527 cleanup(); 2528 2529 AddAdapter.ListItem item = (AddAdapter.ListItem) mAdapter.getItem(which); 2530 switch (item.actionTag) { 2531 case AddAdapter.ITEM_APPLICATION: { 2532 if (mAppsCustomizeTabHost != null) { 2533 mAppsCustomizeTabHost.selectAppsTab(); 2534 } 2535 showAllApps(true); 2536 break; 2537 } 2538 case AddAdapter.ITEM_APPWIDGET: { 2539 if (mAppsCustomizeTabHost != null) { 2540 mAppsCustomizeTabHost.selectWidgetsTab(); 2541 } 2542 showAllApps(true); 2543 break; 2544 } 2545 case AddAdapter.ITEM_WALLPAPER: { 2546 startWallpaper(); 2547 break; 2548 } 2549 } 2550 } 2551 2552 public void onShow(DialogInterface dialog) { 2553 mWaitingForResult = true; 2554 } 2555 } 2556 2557 /** 2558 * Receives notifications when system dialogs are to be closed. 2559 */ 2560 private class CloseSystemDialogsIntentReceiver extends BroadcastReceiver { 2561 @Override 2562 public void onReceive(Context context, Intent intent) { 2563 closeSystemDialogs(); 2564 } 2565 } 2566 2567 /** 2568 * Receives notifications whenever the appwidgets are reset. 2569 */ 2570 private class AppWidgetResetObserver extends ContentObserver { 2571 public AppWidgetResetObserver() { 2572 super(new Handler()); 2573 } 2574 2575 @Override 2576 public void onChange(boolean selfChange) { 2577 onAppWidgetReset(); 2578 } 2579 } 2580 2581 /** 2582 * If the activity is currently paused, signal that we need to re-run the loader 2583 * in onResume. 2584 * 2585 * This needs to be called from incoming places where resources might have been loaded 2586 * while we are paused. That is becaues the Configuration might be wrong 2587 * when we're not running, and if it comes back to what it was when we 2588 * were paused, we are not restarted. 2589 * 2590 * Implementation of the method from LauncherModel.Callbacks. 2591 * 2592 * @return true if we are currently paused. The caller might be able to 2593 * skip some work in that case since we will come back again. 2594 */ 2595 public boolean setLoadOnResume() { 2596 if (mPaused) { 2597 Log.i(TAG, "setLoadOnResume"); 2598 mOnResumeNeedsLoad = true; 2599 return true; 2600 } else { 2601 return false; 2602 } 2603 } 2604 2605 /** 2606 * Implementation of the method from LauncherModel.Callbacks. 2607 */ 2608 public int getCurrentWorkspaceScreen() { 2609 if (mWorkspace != null) { 2610 return mWorkspace.getCurrentPage(); 2611 } else { 2612 return SCREEN_COUNT / 2; 2613 } 2614 } 2615 2616 2617 /** 2618 * Refreshes the shortcuts shown on the workspace. 2619 * 2620 * Implementation of the method from LauncherModel.Callbacks. 2621 */ 2622 public void startBinding() { 2623 final Workspace workspace = mWorkspace; 2624 2625 mWorkspace.clearDropTargets(); 2626 int count = workspace.getChildCount(); 2627 for (int i = 0; i < count; i++) { 2628 // Use removeAllViewsInLayout() to avoid an extra requestLayout() and invalidate(). 2629 final CellLayout layoutParent = (CellLayout) workspace.getChildAt(i); 2630 layoutParent.removeAllViewsInLayout(); 2631 } 2632 if (mHotseat != null) { 2633 mHotseat.resetLayout(); 2634 } 2635 2636 // This wasn't being called before which resulted in a leak of AppWidgetHostViews 2637 unbindWorkspaceAndHotseatItems(); 2638 } 2639 2640 /** 2641 * Bind the items start-end from the list. 2642 * 2643 * Implementation of the method from LauncherModel.Callbacks. 2644 */ 2645 public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end) { 2646 setLoadOnResume(); 2647 2648 final Workspace workspace = mWorkspace; 2649 for (int i=start; i<end; i++) { 2650 final ItemInfo item = shortcuts.get(i); 2651 2652 // Short circuit if we are loading dock items for a configuration which has no dock 2653 if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT && 2654 mHotseat == null) { 2655 continue; 2656 } 2657 2658 switch (item.itemType) { 2659 case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: 2660 case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: 2661 View shortcut = createShortcut((ShortcutInfo)item); 2662 workspace.addInScreen(shortcut, item.container, item.screen, item.cellX, 2663 item.cellY, 1, 1, false); 2664 break; 2665 case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: 2666 FolderIcon newFolder = FolderIcon.fromXml(R.layout.folder_icon, this, 2667 (ViewGroup) workspace.getChildAt(workspace.getCurrentPage()), 2668 (FolderInfo) item, mIconCache); 2669 workspace.addInScreen(newFolder, item.container, item.screen, item.cellX, 2670 item.cellY, 1, 1, false); 2671 break; 2672 } 2673 } 2674 workspace.requestLayout(); 2675 } 2676 2677 /** 2678 * Implementation of the method from LauncherModel.Callbacks. 2679 */ 2680 public void bindFolders(HashMap<Long, FolderInfo> folders) { 2681 setLoadOnResume(); 2682 sFolders.clear(); 2683 sFolders.putAll(folders); 2684 } 2685 2686 /** 2687 * Add the views for a widget to the workspace. 2688 * 2689 * Implementation of the method from LauncherModel.Callbacks. 2690 */ 2691 public void bindAppWidget(LauncherAppWidgetInfo item) { 2692 setLoadOnResume(); 2693 2694 final long start = DEBUG_WIDGETS ? SystemClock.uptimeMillis() : 0; 2695 if (DEBUG_WIDGETS) { 2696 Log.d(TAG, "bindAppWidget: " + item); 2697 } 2698 final Workspace workspace = mWorkspace; 2699 2700 final int appWidgetId = item.appWidgetId; 2701 final AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); 2702 if (DEBUG_WIDGETS) { 2703 Log.d(TAG, "bindAppWidget: id=" + item.appWidgetId + " belongs to component " + appWidgetInfo.provider); 2704 } 2705 2706 item.hostView = mAppWidgetHost.createView(this, appWidgetId, appWidgetInfo); 2707 2708 item.hostView.setAppWidget(appWidgetId, appWidgetInfo); 2709 item.hostView.setTag(item); 2710 2711 workspace.addInScreen(item.hostView, item.container, item.screen, item.cellX, 2712 item.cellY, item.spanX, item.spanY, false); 2713 2714 addWidgetToAutoAdvanceIfNeeded(item.hostView, appWidgetInfo); 2715 2716 workspace.requestLayout(); 2717 2718 if (DEBUG_WIDGETS) { 2719 Log.d(TAG, "bound widget id="+item.appWidgetId+" in " 2720 + (SystemClock.uptimeMillis()-start) + "ms"); 2721 } 2722 } 2723 2724 /** 2725 * Callback saying that there aren't any more items to bind. 2726 * 2727 * Implementation of the method from LauncherModel.Callbacks. 2728 */ 2729 public void finishBindingItems() { 2730 setLoadOnResume(); 2731 2732 if (mSavedState != null) { 2733 if (!mWorkspace.hasFocus()) { 2734 mWorkspace.getChildAt(mWorkspace.getCurrentPage()).requestFocus(); 2735 } 2736 mSavedState = null; 2737 } 2738 2739 if (mSavedInstanceState != null) { 2740 super.onRestoreInstanceState(mSavedInstanceState); 2741 mSavedInstanceState = null; 2742 } 2743 2744 mWorkspaceLoading = false; 2745 2746 // If we received the result of any pending adds while the loader was running (e.g. the 2747 // widget configuration forced an orientation change), process them now. 2748 for (int i = 0; i < sPendingAddList.size(); i++) { 2749 completeAdd(sPendingAddList.get(i)); 2750 } 2751 sPendingAddList.clear(); 2752 } 2753 2754 /** 2755 * Updates the icons on the launcher that are affected by changes to the package list 2756 * on the device. 2757 */ 2758 private void updateIconsAffectedByPackageManagerChanges() { 2759 updateAppMarketIcon(); 2760 updateVoiceSearchIcon(); 2761 } 2762 2763 @Override 2764 public void bindSearchablesChanged() { 2765 updateGlobalSearchIcon(); 2766 } 2767 2768 /** 2769 * Add the icons for all apps. 2770 * 2771 * Implementation of the method from LauncherModel.Callbacks. 2772 */ 2773 public void bindAllApplications(ArrayList<ApplicationInfo> apps) { 2774 if (mAppsCustomizeContent != null) { 2775 mAppsCustomizeContent.setApps(apps); 2776 } 2777 updateIconsAffectedByPackageManagerChanges(); 2778 updateGlobalSearchIcon(); 2779 } 2780 2781 /** 2782 * A package was installed. 2783 * 2784 * Implementation of the method from LauncherModel.Callbacks. 2785 */ 2786 public void bindAppsAdded(ArrayList<ApplicationInfo> apps) { 2787 setLoadOnResume(); 2788 removeDialog(DIALOG_CREATE_SHORTCUT); 2789 2790 if (mAppsCustomizeContent != null) { 2791 mAppsCustomizeContent.addApps(apps); 2792 } 2793 updateIconsAffectedByPackageManagerChanges(); 2794 } 2795 2796 /** 2797 * A package was updated. 2798 * 2799 * Implementation of the method from LauncherModel.Callbacks. 2800 */ 2801 public void bindAppsUpdated(ArrayList<ApplicationInfo> apps) { 2802 setLoadOnResume(); 2803 removeDialog(DIALOG_CREATE_SHORTCUT); 2804 if (mWorkspace != null) { 2805 mWorkspace.updateShortcuts(apps); 2806 } 2807 2808 if (mAppsCustomizeContent != null) { 2809 mAppsCustomizeContent.updateApps(apps); 2810 } 2811 updateIconsAffectedByPackageManagerChanges(); 2812 } 2813 2814 /** 2815 * A package was uninstalled. 2816 * 2817 * Implementation of the method from LauncherModel.Callbacks. 2818 */ 2819 public void bindAppsRemoved(ArrayList<ApplicationInfo> apps, boolean permanent) { 2820 removeDialog(DIALOG_CREATE_SHORTCUT); 2821 if (permanent) { 2822 mWorkspace.removeItems(apps); 2823 } 2824 2825 if (mAppsCustomizeContent != null) { 2826 mAppsCustomizeContent.removeApps(apps); 2827 } 2828 updateIconsAffectedByPackageManagerChanges(); 2829 } 2830 2831 /** 2832 * A number of packages were updated. 2833 */ 2834 public void bindPackagesUpdated() { 2835 2836 if (mAppsCustomizeContent != null) { 2837 mAppsCustomizeContent.onPackagesUpdated(); 2838 } 2839 } 2840 2841 private int mapConfigurationOriActivityInfoOri(int configOri) { 2842 final Display d = getWindowManager().getDefaultDisplay(); 2843 int naturalOri = Configuration.ORIENTATION_LANDSCAPE; 2844 switch (d.getRotation()) { 2845 case Surface.ROTATION_0: 2846 case Surface.ROTATION_180: 2847 // We are currently in the same basic orientation as the natural orientation 2848 naturalOri = configOri; 2849 break; 2850 case Surface.ROTATION_90: 2851 case Surface.ROTATION_270: 2852 // We are currently in the other basic orientation to the natural orientation 2853 naturalOri = (configOri == Configuration.ORIENTATION_LANDSCAPE) ? 2854 Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE; 2855 break; 2856 } 2857 2858 int[] oriMap = { 2859 ActivityInfo.SCREEN_ORIENTATION_PORTRAIT, 2860 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE, 2861 ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT, 2862 ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE 2863 }; 2864 // Since the map starts at portrait, we need to offset if this device's natural orientation 2865 // is landscape. 2866 int indexOffset = 0; 2867 if (naturalOri == Configuration.ORIENTATION_LANDSCAPE) { 2868 indexOffset = 1; 2869 } 2870 return oriMap[(d.getRotation() + indexOffset) % 4]; 2871 } 2872 public void lockScreenOrientation() { 2873 setRequestedOrientation(mapConfigurationOriActivityInfoOri(getResources() 2874 .getConfiguration().orientation)); 2875 } 2876 public void unlockScreenOrientation() { 2877 mHandler.postDelayed(new Runnable() { 2878 public void run() { 2879 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 2880 } 2881 }, mRestoreScreenOrientationDelay); 2882 } 2883 2884 /** 2885 * Prints out out state for debugging. 2886 */ 2887 public void dumpState() { 2888 Log.d(TAG, "BEGIN launcher2 dump state for launcher " + this); 2889 Log.d(TAG, "mSavedState=" + mSavedState); 2890 Log.d(TAG, "mWorkspaceLoading=" + mWorkspaceLoading); 2891 Log.d(TAG, "mRestoring=" + mRestoring); 2892 Log.d(TAG, "mWaitingForResult=" + mWaitingForResult); 2893 Log.d(TAG, "mSavedInstanceState=" + mSavedInstanceState); 2894 Log.d(TAG, "sFolders.size=" + sFolders.size()); 2895 mModel.dumpState(); 2896 2897 if (mAppsCustomizeContent != null) { 2898 mAppsCustomizeContent.dumpState(); 2899 } 2900 Log.d(TAG, "END launcher2 dump state"); 2901 } 2902} 2903 2904interface LauncherTransitionable { 2905 void onLauncherTransitionStart(Animator animation, boolean toWorkspace); 2906 void onLauncherTransitionEnd(Animator animation, boolean toWorkspace); 2907} 2908