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