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