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