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