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