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