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