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