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