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