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