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