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