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