PhoneWindow.java revision 0b2be42a07fcb66ca0a5f70624c8871245b4f6fd
1/* 2 * 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16package com.android.internal.policy.impl; 17 18import static android.view.View.MeasureSpec.AT_MOST; 19import static android.view.View.MeasureSpec.EXACTLY; 20import static android.view.View.MeasureSpec.getMode; 21import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; 22import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; 23import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN; 24import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR; 25import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; 26import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER; 27import static android.view.WindowManager.LayoutParams.FLAG_SPLIT_TOUCH; 28 29import com.android.internal.view.RootViewSurfaceTaker; 30import com.android.internal.view.StandaloneActionMode; 31import com.android.internal.view.menu.ContextMenuBuilder; 32import com.android.internal.view.menu.IconMenuPresenter; 33import com.android.internal.view.menu.ListMenuPresenter; 34import com.android.internal.view.menu.MenuBuilder; 35import com.android.internal.view.menu.MenuDialogHelper; 36import com.android.internal.view.menu.MenuPresenter; 37import com.android.internal.view.menu.MenuView; 38import com.android.internal.view.menu.SubMenuBuilder; 39import com.android.internal.widget.ActionBarContainer; 40import com.android.internal.widget.ActionBarContextView; 41import com.android.internal.widget.ActionBarView; 42 43import android.app.KeyguardManager; 44import android.content.Context; 45import android.content.res.Configuration; 46import android.content.res.TypedArray; 47import android.graphics.Canvas; 48import android.graphics.PixelFormat; 49import android.graphics.Rect; 50import android.graphics.drawable.Drawable; 51import android.media.AudioManager; 52import android.net.Uri; 53import android.os.Bundle; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.util.AndroidRuntimeException; 57import android.util.DisplayMetrics; 58import android.util.EventLog; 59import android.util.Log; 60import android.util.SparseArray; 61import android.util.TypedValue; 62import android.view.ActionMode; 63import android.view.Gravity; 64import android.view.InputQueue; 65import android.view.KeyCharacterMap; 66import android.view.KeyEvent; 67import android.view.LayoutInflater; 68import android.view.Menu; 69import android.view.MenuItem; 70import android.view.MotionEvent; 71import android.view.SurfaceHolder; 72import android.view.View; 73import android.view.ViewGroup; 74import android.view.ViewManager; 75import android.view.ViewStub; 76import android.view.Window; 77import android.view.WindowManager; 78import android.view.accessibility.AccessibilityEvent; 79import android.view.accessibility.AccessibilityManager; 80import android.view.animation.Animation; 81import android.view.animation.AnimationUtils; 82import android.widget.FrameLayout; 83import android.widget.ImageView; 84import android.widget.PopupWindow; 85import android.widget.ProgressBar; 86import android.widget.TextView; 87 88/** 89 * Android-specific Window. 90 * <p> 91 * todo: need to pull the generic functionality out into a base class 92 * in android.widget. 93 */ 94public class PhoneWindow extends Window implements MenuBuilder.Callback { 95 96 private final static String TAG = "PhoneWindow"; 97 98 private final static boolean SWEEP_OPEN_MENU = false; 99 100 /** 101 * Simple callback used by the context menu and its submenus. The options 102 * menu submenus do not use this (their behavior is more complex). 103 */ 104 final DialogMenuCallback mContextMenuCallback = new DialogMenuCallback(FEATURE_CONTEXT_MENU); 105 106 final TypedValue mMinWidthMajor = new TypedValue(); 107 final TypedValue mMinWidthMinor = new TypedValue(); 108 109 // This is the top-level view of the window, containing the window decor. 110 private DecorView mDecor; 111 112 // This is the view in which the window contents are placed. It is either 113 // mDecor itself, or a child of mDecor where the contents go. 114 private ViewGroup mContentParent; 115 116 SurfaceHolder.Callback2 mTakeSurfaceCallback; 117 118 InputQueue.Callback mTakeInputQueueCallback; 119 120 private boolean mIsFloating; 121 122 private LayoutInflater mLayoutInflater; 123 124 private TextView mTitleView; 125 126 private ActionBarView mActionBar; 127 private ActionMenuPresenterCallback mActionMenuPresenterCallback; 128 private PanelMenuPresenterCallback mPanelMenuPresenterCallback; 129 130 private DrawableFeatureState[] mDrawables; 131 132 private PanelFeatureState[] mPanels; 133 134 /** 135 * The panel that is prepared or opened (the most recent one if there are 136 * multiple panels). Shortcuts will go to this panel. It gets set in 137 * {@link #preparePanel} and cleared in {@link #closePanel}. 138 */ 139 private PanelFeatureState mPreparedPanel; 140 141 /** 142 * The keycode that is currently held down (as a modifier) for chording. If 143 * this is 0, there is no key held down. 144 */ 145 private int mPanelChordingKey; 146 147 private ImageView mLeftIconView; 148 149 private ImageView mRightIconView; 150 151 private ProgressBar mCircularProgressBar; 152 153 private ProgressBar mHorizontalProgressBar; 154 155 private int mBackgroundResource = 0; 156 157 private Drawable mBackgroundDrawable; 158 159 private int mFrameResource = 0; 160 161 private int mTextColor = 0; 162 163 private CharSequence mTitle = null; 164 165 private int mTitleColor = 0; 166 167 private boolean mAlwaysReadCloseOnTouchAttr = false; 168 169 private ContextMenuBuilder mContextMenu; 170 private MenuDialogHelper mContextMenuHelper; 171 private boolean mClosingActionMenu; 172 173 private int mVolumeControlStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE; 174 175 private AudioManager mAudioManager; 176 private KeyguardManager mKeyguardManager; 177 178 public PhoneWindow(Context context) { 179 super(context); 180 mLayoutInflater = LayoutInflater.from(context); 181 } 182 183 @Override 184 public final void setContainer(Window container) { 185 super.setContainer(container); 186 } 187 188 @Override 189 public boolean requestFeature(int featureId) { 190 if (mContentParent != null) { 191 throw new AndroidRuntimeException("requestFeature() must be called before adding content"); 192 } 193 final int features = getFeatures(); 194 if ((features != DEFAULT_FEATURES) && (featureId == FEATURE_CUSTOM_TITLE)) { 195 196 /* Another feature is enabled and the user is trying to enable the custom title feature */ 197 throw new AndroidRuntimeException("You cannot combine custom titles with other title features"); 198 } 199 if (((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) && 200 (featureId != FEATURE_CUSTOM_TITLE) && (featureId != FEATURE_ACTION_MODE_OVERLAY)) { 201 202 /* Custom title feature is enabled and the user is trying to enable another feature */ 203 throw new AndroidRuntimeException("You cannot combine custom titles with other title features"); 204 } 205 if ((features & (1 << FEATURE_NO_TITLE)) != 0 && featureId == FEATURE_ACTION_BAR) { 206 return false; // Ignore. No title dominates. 207 } 208 if ((features & (1 << FEATURE_ACTION_BAR)) != 0 && featureId == FEATURE_NO_TITLE) { 209 // Remove the action bar feature if we have no title. No title dominates. 210 removeFeature(FEATURE_ACTION_BAR); 211 } 212 return super.requestFeature(featureId); 213 } 214 215 @Override 216 public void setContentView(int layoutResID) { 217 if (mContentParent == null) { 218 installDecor(); 219 } else { 220 mContentParent.removeAllViews(); 221 } 222 mLayoutInflater.inflate(layoutResID, mContentParent); 223 final Callback cb = getCallback(); 224 if (cb != null && !isDestroyed()) { 225 cb.onContentChanged(); 226 } 227 } 228 229 @Override 230 public void setContentView(View view) { 231 setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 232 } 233 234 @Override 235 public void setContentView(View view, ViewGroup.LayoutParams params) { 236 if (mContentParent == null) { 237 installDecor(); 238 } else { 239 mContentParent.removeAllViews(); 240 } 241 mContentParent.addView(view, params); 242 final Callback cb = getCallback(); 243 if (cb != null && !isDestroyed()) { 244 cb.onContentChanged(); 245 } 246 } 247 248 @Override 249 public void addContentView(View view, ViewGroup.LayoutParams params) { 250 if (mContentParent == null) { 251 installDecor(); 252 } 253 mContentParent.addView(view, params); 254 final Callback cb = getCallback(); 255 if (cb != null && !isDestroyed()) { 256 cb.onContentChanged(); 257 } 258 } 259 260 @Override 261 public View getCurrentFocus() { 262 return mDecor != null ? mDecor.findFocus() : null; 263 } 264 265 @Override 266 public void takeSurface(SurfaceHolder.Callback2 callback) { 267 mTakeSurfaceCallback = callback; 268 } 269 270 public void takeInputQueue(InputQueue.Callback callback) { 271 mTakeInputQueueCallback = callback; 272 } 273 274 @Override 275 public boolean isFloating() { 276 return mIsFloating; 277 } 278 279 /** 280 * Return a LayoutInflater instance that can be used to inflate XML view layout 281 * resources for use in this Window. 282 * 283 * @return LayoutInflater The shared LayoutInflater. 284 */ 285 @Override 286 public LayoutInflater getLayoutInflater() { 287 return mLayoutInflater; 288 } 289 290 @Override 291 public void setTitle(CharSequence title) { 292 if (mTitleView != null) { 293 mTitleView.setText(title); 294 } else if (mActionBar != null) { 295 mActionBar.setWindowTitle(title); 296 } 297 mTitle = title; 298 } 299 300 @Override 301 public void setTitleColor(int textColor) { 302 if (mTitleView != null) { 303 mTitleView.setTextColor(textColor); 304 } 305 mTitleColor = textColor; 306 } 307 308 /** 309 * Prepares the panel to either be opened or chorded. This creates the Menu 310 * instance for the panel and populates it via the Activity callbacks. 311 * 312 * @param st The panel state to prepare. 313 * @param event The event that triggered the preparing of the panel. 314 * @return Whether the panel was prepared. If the panel should not be shown, 315 * returns false. 316 */ 317 public final boolean preparePanel(PanelFeatureState st, KeyEvent event) { 318 if (isDestroyed()) { 319 return false; 320 } 321 322 // Already prepared (isPrepared will be reset to false later) 323 if (st.isPrepared) 324 return true; 325 326 if ((mPreparedPanel != null) && (mPreparedPanel != st)) { 327 // Another Panel is prepared and possibly open, so close it 328 closePanel(mPreparedPanel, false); 329 } 330 331 final Callback cb = getCallback(); 332 333 if (cb != null) { 334 st.createdPanelView = cb.onCreatePanelView(st.featureId); 335 } 336 337 if (st.createdPanelView == null) { 338 // Init the panel state's menu--return false if init failed 339 if (st.menu == null || st.refreshMenuContent) { 340 if (st.menu == null) { 341 if (!initializePanelMenu(st) || (st.menu == null)) { 342 return false; 343 } 344 } 345 346 // Call callback, and return if it doesn't want to display menu. 347 348 // Creating the panel menu will involve a lot of manipulation; 349 // don't dispatch change events to presenters until we're done. 350 st.menu.stopDispatchingItemsChanged(); 351 if ((cb == null) || !cb.onCreatePanelMenu(st.featureId, st.menu)) { 352 // Ditch the menu created above 353 st.menu = null; 354 355 return false; 356 } 357 358 st.refreshMenuContent = false; 359 360 if (mActionBar != null) { 361 if (mActionMenuPresenterCallback == null) { 362 mActionMenuPresenterCallback = new ActionMenuPresenterCallback(); 363 } 364 mActionBar.setMenu(st.menu, mActionMenuPresenterCallback); 365 } 366 } 367 368 // Callback and return if the callback does not want to show the menu 369 370 // Preparing the panel menu can involve a lot of manipulation; 371 // don't dispatch change events to presenters until we're done. 372 st.menu.stopDispatchingItemsChanged(); 373 if (!cb.onPreparePanel(st.featureId, st.createdPanelView, st.menu)) { 374 st.menu.startDispatchingItemsChanged(); 375 return false; 376 } 377 st.menu.startDispatchingItemsChanged(); 378 379 // Set the proper keymap 380 KeyCharacterMap kmap = KeyCharacterMap.load( 381 event != null ? event.getDeviceId() : KeyCharacterMap.VIRTUAL_KEYBOARD); 382 st.qwertyMode = kmap.getKeyboardType() != KeyCharacterMap.NUMERIC; 383 st.menu.setQwertyMode(st.qwertyMode); 384 } 385 386 // Set other state 387 st.isPrepared = true; 388 st.isHandled = false; 389 mPreparedPanel = st; 390 391 return true; 392 } 393 394 @Override 395 public void onConfigurationChanged(Configuration newConfig) { 396 // Action bars handle their own menu state 397 if (mActionBar == null) { 398 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false); 399 if ((st != null) && (st.menu != null)) { 400 if (st.isOpen) { 401 // Freeze state 402 final Bundle state = new Bundle(); 403 if (st.iconMenuPresenter != null) { 404 st.iconMenuPresenter.saveHierarchyState(state); 405 } 406 if (st.expandedMenuPresenter != null) { 407 st.expandedMenuPresenter.saveHierarchyState(state); 408 } 409 410 // Remove the menu views since they need to be recreated 411 // according to the new configuration 412 clearMenuViews(st); 413 414 // Re-open the same menu 415 reopenMenu(false); 416 417 // Restore state 418 if (st.iconMenuPresenter != null) { 419 st.iconMenuPresenter.restoreHierarchyState(state); 420 } 421 if (st.expandedMenuPresenter != null) { 422 st.expandedMenuPresenter.restoreHierarchyState(state); 423 } 424 425 } else { 426 // Clear menu views so on next menu opening, it will use 427 // the proper layout 428 clearMenuViews(st); 429 } 430 } 431 } 432 } 433 434 private static void clearMenuViews(PanelFeatureState st) { 435 // This can be called on config changes, so we should make sure 436 // the views will be reconstructed based on the new orientation, etc. 437 438 // Allow the callback to create a new panel view 439 st.createdPanelView = null; 440 441 // Causes the decor view to be recreated 442 st.refreshDecorView = true; 443 444 st.clearMenuPresenters(); 445 } 446 447 @Override 448 public final void openPanel(int featureId, KeyEvent event) { 449 if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null && 450 mActionBar.isOverflowReserved()) { 451 if (mActionBar.getVisibility() == View.VISIBLE) { 452 // Invalidate the options menu, we want a prepare event that the app can respond to. 453 invalidatePanelMenu(FEATURE_OPTIONS_PANEL); 454 mActionBar.showOverflowMenu(); 455 } 456 } else { 457 openPanel(getPanelState(featureId, true), event); 458 } 459 } 460 461 private void openPanel(PanelFeatureState st, KeyEvent event) { 462 // System.out.println("Open panel: isOpen=" + st.isOpen); 463 464 // Already open, return 465 if (st.isOpen || isDestroyed()) { 466 return; 467 } 468 469 // Don't open an options panel for honeycomb apps on xlarge devices. 470 // (The app should be using an action bar for menu items.) 471 if (st.featureId == FEATURE_OPTIONS_PANEL) { 472 Context context = getContext(); 473 Configuration config = context.getResources().getConfiguration(); 474 boolean isXLarge = (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 475 Configuration.SCREENLAYOUT_SIZE_XLARGE; 476 boolean isHoneycombApp = context.getApplicationInfo().targetSdkVersion >= 477 android.os.Build.VERSION_CODES.HONEYCOMB; 478 479 if (isXLarge && isHoneycombApp) { 480 return; 481 } 482 } 483 484 Callback cb = getCallback(); 485 if ((cb != null) && (!cb.onMenuOpened(st.featureId, st.menu))) { 486 // Callback doesn't want the menu to open, reset any state 487 closePanel(st, true); 488 return; 489 } 490 491 final WindowManager wm = getWindowManager(); 492 if (wm == null) { 493 return; 494 } 495 496 // Prepare panel (should have been done before, but just in case) 497 if (!preparePanel(st, event)) { 498 return; 499 } 500 501 int width = WRAP_CONTENT; 502 if (st.decorView == null || st.refreshDecorView) { 503 if (st.decorView == null) { 504 // Initialize the panel decor, this will populate st.decorView 505 if (!initializePanelDecor(st) || (st.decorView == null)) 506 return; 507 } else if (st.refreshDecorView && (st.decorView.getChildCount() > 0)) { 508 // Decor needs refreshing, so remove its views 509 st.decorView.removeAllViews(); 510 } 511 512 // This will populate st.shownPanelView 513 if (!initializePanelContent(st) || !st.hasPanelItems()) { 514 return; 515 } 516 517 ViewGroup.LayoutParams lp = st.shownPanelView.getLayoutParams(); 518 if (lp == null) { 519 lp = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); 520 } 521 522 int backgroundResId; 523 if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT) { 524 // If the contents is fill parent for the width, set the 525 // corresponding background 526 backgroundResId = st.fullBackground; 527 width = MATCH_PARENT; 528 } else { 529 // Otherwise, set the normal panel background 530 backgroundResId = st.background; 531 } 532 st.decorView.setWindowBackground(getContext().getResources().getDrawable( 533 backgroundResId)); 534 535 536 st.decorView.addView(st.shownPanelView, lp); 537 538 /* 539 * Give focus to the view, if it or one of its children does not 540 * already have it. 541 */ 542 if (!st.shownPanelView.hasFocus()) { 543 st.shownPanelView.requestFocus(); 544 } 545 } 546 547 st.isOpen = true; 548 st.isHandled = false; 549 550 WindowManager.LayoutParams lp = new WindowManager.LayoutParams( 551 width, WRAP_CONTENT, 552 st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG, 553 WindowManager.LayoutParams.FLAG_DITHER 554 | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM 555 | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH, 556 st.decorView.mDefaultOpacity); 557 558 lp.gravity = st.gravity; 559 lp.windowAnimations = st.windowAnimations; 560 561 wm.addView(st.decorView, lp); 562 // Log.v(TAG, "Adding main menu to window manager."); 563 } 564 565 @Override 566 public final void closePanel(int featureId) { 567 if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null && 568 mActionBar.isOverflowReserved()) { 569 mActionBar.hideOverflowMenu(); 570 } else if (featureId == FEATURE_CONTEXT_MENU) { 571 closeContextMenu(); 572 } else { 573 closePanel(getPanelState(featureId, true), true); 574 } 575 } 576 577 /** 578 * Closes the given panel. 579 * 580 * @param st The panel to be closed. 581 * @param doCallback Whether to notify the callback that the panel was 582 * closed. If the panel is in the process of re-opening or 583 * opening another panel (e.g., menu opening a sub menu), the 584 * callback should not happen and this variable should be false. 585 * In addition, this method internally will only perform the 586 * callback if the panel is open. 587 */ 588 public final void closePanel(PanelFeatureState st, boolean doCallback) { 589 // System.out.println("Close panel: isOpen=" + st.isOpen); 590 if (doCallback && st.featureId == FEATURE_OPTIONS_PANEL && 591 mActionBar != null && mActionBar.isOverflowMenuShowing()) { 592 checkCloseActionMenu(st.menu); 593 return; 594 } 595 596 final ViewManager wm = getWindowManager(); 597 if ((wm != null) && st.isOpen) { 598 if (st.decorView != null) { 599 wm.removeView(st.decorView); 600 // Log.v(TAG, "Removing main menu from window manager."); 601 } 602 603 if (doCallback) { 604 callOnPanelClosed(st.featureId, st, null); 605 } 606 } 607 608 st.isPrepared = false; 609 st.isHandled = false; 610 st.isOpen = false; 611 612 // This view is no longer shown, so null it out 613 st.shownPanelView = null; 614 615 if (st.isInExpandedMode) { 616 // Next time the menu opens, it should not be in expanded mode, so 617 // force a refresh of the decor 618 st.refreshDecorView = true; 619 st.isInExpandedMode = false; 620 } 621 622 if (mPreparedPanel == st) { 623 mPreparedPanel = null; 624 mPanelChordingKey = 0; 625 } 626 } 627 628 void checkCloseActionMenu(Menu menu) { 629 if (mClosingActionMenu) { 630 return; 631 } 632 633 mClosingActionMenu = true; 634 mActionBar.dismissPopupMenus(); 635 Callback cb = getCallback(); 636 if (cb != null && !isDestroyed()) { 637 cb.onPanelClosed(FEATURE_ACTION_BAR, menu); 638 } 639 mClosingActionMenu = false; 640 } 641 642 @Override 643 public final void togglePanel(int featureId, KeyEvent event) { 644 PanelFeatureState st = getPanelState(featureId, true); 645 if (st.isOpen) { 646 closePanel(st, true); 647 } else { 648 openPanel(st, event); 649 } 650 } 651 652 @Override 653 public void invalidatePanelMenu(int featureId) { 654 PanelFeatureState st = getPanelState(featureId, true); 655 if (st.menu != null) { 656 st.menu.clear(); 657 } 658 st.refreshMenuContent = true; 659 st.refreshDecorView = true; 660 661 // Prepare the options panel if we have an action bar 662 if ((featureId == FEATURE_ACTION_BAR || featureId == FEATURE_OPTIONS_PANEL) 663 && mActionBar != null) { 664 st = getPanelState(Window.FEATURE_OPTIONS_PANEL, false); 665 if (st != null) { 666 st.isPrepared = false; 667 preparePanel(st, null); 668 } 669 } 670 } 671 672 /** 673 * Called when the panel key is pushed down. 674 * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}. 675 * @param event The key event. 676 * @return Whether the key was handled. 677 */ 678 public final boolean onKeyDownPanel(int featureId, KeyEvent event) { 679 final int keyCode = event.getKeyCode(); 680 681 if (event.getRepeatCount() == 0) { 682 // The panel key was pushed, so set the chording key 683 mPanelChordingKey = keyCode; 684 685 PanelFeatureState st = getPanelState(featureId, true); 686 if (!st.isOpen) { 687 return preparePanel(st, event); 688 } 689 } 690 691 return false; 692 } 693 694 /** 695 * Called when the panel key is released. 696 * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}. 697 * @param event The key event. 698 */ 699 public final void onKeyUpPanel(int featureId, KeyEvent event) { 700 // The panel key was released, so clear the chording key 701 if (mPanelChordingKey != 0) { 702 mPanelChordingKey = 0; 703 704 if (event.isCanceled()) { 705 return; 706 } 707 708 boolean playSoundEffect = false; 709 final PanelFeatureState st = getPanelState(featureId, true); 710 if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null && 711 mActionBar.isOverflowReserved()) { 712 if (mActionBar.getVisibility() == View.VISIBLE) { 713 if (!mActionBar.isOverflowMenuShowing()) { 714 if (!isDestroyed() && preparePanel(st, event)) { 715 playSoundEffect = mActionBar.showOverflowMenu(); 716 } 717 } else { 718 playSoundEffect = mActionBar.hideOverflowMenu(); 719 } 720 } 721 } else { 722 if (st.isOpen || st.isHandled) { 723 724 // Play the sound effect if the user closed an open menu (and not if 725 // they just released a menu shortcut) 726 playSoundEffect = st.isOpen; 727 728 // Close menu 729 closePanel(st, true); 730 731 } else if (st.isPrepared) { 732 733 // Write 'menu opened' to event log 734 EventLog.writeEvent(50001, 0); 735 736 // Show menu 737 openPanel(st, event); 738 739 playSoundEffect = true; 740 } 741 } 742 743 if (playSoundEffect) { 744 AudioManager audioManager = (AudioManager) getContext().getSystemService( 745 Context.AUDIO_SERVICE); 746 if (audioManager != null) { 747 audioManager.playSoundEffect(AudioManager.FX_KEY_CLICK); 748 } else { 749 Log.w(TAG, "Couldn't get audio manager"); 750 } 751 } 752 } 753 } 754 755 @Override 756 public final void closeAllPanels() { 757 final ViewManager wm = getWindowManager(); 758 if (wm == null) { 759 return; 760 } 761 762 final PanelFeatureState[] panels = mPanels; 763 final int N = panels != null ? panels.length : 0; 764 for (int i = 0; i < N; i++) { 765 final PanelFeatureState panel = panels[i]; 766 if (panel != null) { 767 closePanel(panel, true); 768 } 769 } 770 771 closeContextMenu(); 772 } 773 774 /** 775 * Closes the context menu. This notifies the menu logic of the close, along 776 * with dismissing it from the UI. 777 */ 778 private synchronized void closeContextMenu() { 779 if (mContextMenu != null) { 780 mContextMenu.close(); 781 dismissContextMenu(); 782 } 783 } 784 785 /** 786 * Dismisses just the context menu UI. To close the context menu, use 787 * {@link #closeContextMenu()}. 788 */ 789 private synchronized void dismissContextMenu() { 790 mContextMenu = null; 791 792 if (mContextMenuHelper != null) { 793 mContextMenuHelper.dismiss(); 794 mContextMenuHelper = null; 795 } 796 } 797 798 @Override 799 public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) { 800 return performPanelShortcut(getPanelState(featureId, true), keyCode, event, flags); 801 } 802 803 private boolean performPanelShortcut(PanelFeatureState st, int keyCode, KeyEvent event, 804 int flags) { 805 if (event.isSystem() || (st == null)) { 806 return false; 807 } 808 809 boolean handled = false; 810 811 // Only try to perform menu shortcuts if preparePanel returned true (possible false 812 // return value from application not wanting to show the menu). 813 if ((st.isPrepared || preparePanel(st, event)) && st.menu != null) { 814 // The menu is prepared now, perform the shortcut on it 815 handled = st.menu.performShortcut(keyCode, event, flags); 816 } 817 818 if (handled) { 819 // Mark as handled 820 st.isHandled = true; 821 822 if ((flags & Menu.FLAG_PERFORM_NO_CLOSE) == 0) { 823 closePanel(st, true); 824 } 825 } 826 827 return handled; 828 } 829 830 @Override 831 public boolean performPanelIdentifierAction(int featureId, int id, int flags) { 832 833 PanelFeatureState st = getPanelState(featureId, true); 834 if (!preparePanel(st, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU))) { 835 return false; 836 } 837 if (st.menu == null) { 838 return false; 839 } 840 841 boolean res = st.menu.performIdentifierAction(id, flags); 842 843 closePanel(st, true); 844 845 return res; 846 } 847 848 public PanelFeatureState findMenuPanel(Menu menu) { 849 final PanelFeatureState[] panels = mPanels; 850 final int N = panels != null ? panels.length : 0; 851 for (int i = 0; i < N; i++) { 852 final PanelFeatureState panel = panels[i]; 853 if (panel != null && panel.menu == menu) { 854 return panel; 855 } 856 } 857 return null; 858 } 859 860 public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { 861 final Callback cb = getCallback(); 862 if (cb != null && !isDestroyed()) { 863 final PanelFeatureState panel = findMenuPanel(menu.getRootMenu()); 864 if (panel != null) { 865 return cb.onMenuItemSelected(panel.featureId, item); 866 } 867 } 868 return false; 869 } 870 871 public void onMenuModeChange(MenuBuilder menu) { 872 reopenMenu(true); 873 } 874 875 private void reopenMenu(boolean toggleMenuMode) { 876 if (mActionBar != null && mActionBar.isOverflowReserved()) { 877 final Callback cb = getCallback(); 878 if (!mActionBar.isOverflowMenuShowing() || !toggleMenuMode) { 879 if (cb != null && !isDestroyed() && mActionBar.getVisibility() == View.VISIBLE) { 880 final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 881 if (cb.onPreparePanel(FEATURE_OPTIONS_PANEL, st.createdPanelView, st.menu)) { 882 cb.onMenuOpened(FEATURE_ACTION_BAR, st.menu); 883 mActionBar.showOverflowMenu(); 884 } 885 } 886 } else { 887 mActionBar.hideOverflowMenu(); 888 if (cb != null && !isDestroyed()) { 889 final PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 890 cb.onPanelClosed(FEATURE_ACTION_BAR, st.menu); 891 } 892 } 893 return; 894 } 895 896 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 897 898 // Save the future expanded mode state since closePanel will reset it 899 boolean newExpandedMode = toggleMenuMode ? !st.isInExpandedMode : st.isInExpandedMode; 900 901 st.refreshDecorView = true; 902 closePanel(st, false); 903 904 // Set the expanded mode state 905 st.isInExpandedMode = newExpandedMode; 906 907 openPanel(st, null); 908 } 909 910 /** 911 * Initializes the menu associated with the given panel feature state. You 912 * must at the very least set PanelFeatureState.menu to the Menu to be 913 * associated with the given panel state. The default implementation creates 914 * a new menu for the panel state. 915 * 916 * @param st The panel whose menu is being initialized. 917 * @return Whether the initialization was successful. 918 */ 919 protected boolean initializePanelMenu(final PanelFeatureState st) { 920 final MenuBuilder menu = new MenuBuilder(getContext()); 921 922 menu.setCallback(this); 923 st.setMenu(menu); 924 925 return true; 926 } 927 928 /** 929 * Perform initial setup of a panel. This should at the very least set the 930 * style information in the PanelFeatureState and must set 931 * PanelFeatureState.decor to the panel's window decor view. 932 * 933 * @param st The panel being initialized. 934 */ 935 protected boolean initializePanelDecor(PanelFeatureState st) { 936 st.decorView = new DecorView(getContext(), st.featureId); 937 st.gravity = Gravity.CENTER | Gravity.BOTTOM; 938 st.setStyle(getContext()); 939 940 return true; 941 } 942 943 /** 944 * Initializes the panel associated with the panel feature state. You must 945 * at the very least set PanelFeatureState.panel to the View implementing 946 * its contents. The default implementation gets the panel from the menu. 947 * 948 * @param st The panel state being initialized. 949 * @return Whether the initialization was successful. 950 */ 951 protected boolean initializePanelContent(PanelFeatureState st) { 952 if (st.createdPanelView != null) { 953 st.shownPanelView = st.createdPanelView; 954 return true; 955 } 956 957 if (st.menu == null) { 958 return false; 959 } 960 961 if (mPanelMenuPresenterCallback == null) { 962 mPanelMenuPresenterCallback = new PanelMenuPresenterCallback(); 963 } 964 965 MenuView menuView = st.isInExpandedMode 966 ? st.getExpandedMenuView(mPanelMenuPresenterCallback) 967 : st.getIconMenuView(mPanelMenuPresenterCallback); 968 969 st.shownPanelView = (View) menuView; 970 971 if (st.shownPanelView != null) { 972 // Use the menu View's default animations if it has any 973 final int defaultAnimations = menuView.getWindowAnimations(); 974 if (defaultAnimations != 0) { 975 st.windowAnimations = defaultAnimations; 976 } 977 return true; 978 } else { 979 return false; 980 } 981 } 982 983 @Override 984 public boolean performContextMenuIdentifierAction(int id, int flags) { 985 return (mContextMenu != null) ? mContextMenu.performIdentifierAction(id, flags) : false; 986 } 987 988 @Override 989 public final void setBackgroundDrawable(Drawable drawable) { 990 if (drawable != mBackgroundDrawable || mBackgroundResource != 0) { 991 mBackgroundResource = 0; 992 mBackgroundDrawable = drawable; 993 if (mDecor != null) { 994 mDecor.setWindowBackground(drawable); 995 } 996 } 997 } 998 999 @Override 1000 public final void setFeatureDrawableResource(int featureId, int resId) { 1001 if (resId != 0) { 1002 DrawableFeatureState st = getDrawableState(featureId, true); 1003 if (st.resid != resId) { 1004 st.resid = resId; 1005 st.uri = null; 1006 st.local = getContext().getResources().getDrawable(resId); 1007 updateDrawable(featureId, st, false); 1008 } 1009 } else { 1010 setFeatureDrawable(featureId, null); 1011 } 1012 } 1013 1014 @Override 1015 public final void setFeatureDrawableUri(int featureId, Uri uri) { 1016 if (uri != null) { 1017 DrawableFeatureState st = getDrawableState(featureId, true); 1018 if (st.uri == null || !st.uri.equals(uri)) { 1019 st.resid = 0; 1020 st.uri = uri; 1021 st.local = loadImageURI(uri); 1022 updateDrawable(featureId, st, false); 1023 } 1024 } else { 1025 setFeatureDrawable(featureId, null); 1026 } 1027 } 1028 1029 @Override 1030 public final void setFeatureDrawable(int featureId, Drawable drawable) { 1031 DrawableFeatureState st = getDrawableState(featureId, true); 1032 st.resid = 0; 1033 st.uri = null; 1034 if (st.local != drawable) { 1035 st.local = drawable; 1036 updateDrawable(featureId, st, false); 1037 } 1038 } 1039 1040 @Override 1041 public void setFeatureDrawableAlpha(int featureId, int alpha) { 1042 DrawableFeatureState st = getDrawableState(featureId, true); 1043 if (st.alpha != alpha) { 1044 st.alpha = alpha; 1045 updateDrawable(featureId, st, false); 1046 } 1047 } 1048 1049 protected final void setFeatureDefaultDrawable(int featureId, Drawable drawable) { 1050 DrawableFeatureState st = getDrawableState(featureId, true); 1051 if (st.def != drawable) { 1052 st.def = drawable; 1053 updateDrawable(featureId, st, false); 1054 } 1055 } 1056 1057 @Override 1058 public final void setFeatureInt(int featureId, int value) { 1059 // XXX Should do more management (as with drawable features) to 1060 // deal with interactions between multiple window policies. 1061 updateInt(featureId, value, false); 1062 } 1063 1064 /** 1065 * Update the state of a drawable feature. This should be called, for every 1066 * drawable feature supported, as part of onActive(), to make sure that the 1067 * contents of a containing window is properly updated. 1068 * 1069 * @see #onActive 1070 * @param featureId The desired drawable feature to change. 1071 * @param fromActive Always true when called from onActive(). 1072 */ 1073 protected final void updateDrawable(int featureId, boolean fromActive) { 1074 final DrawableFeatureState st = getDrawableState(featureId, false); 1075 if (st != null) { 1076 updateDrawable(featureId, st, fromActive); 1077 } 1078 } 1079 1080 /** 1081 * Called when a Drawable feature changes, for the window to update its 1082 * graphics. 1083 * 1084 * @param featureId The feature being changed. 1085 * @param drawable The new Drawable to show, or null if none. 1086 * @param alpha The new alpha blending of the Drawable. 1087 */ 1088 protected void onDrawableChanged(int featureId, Drawable drawable, int alpha) { 1089 ImageView view; 1090 if (featureId == FEATURE_LEFT_ICON) { 1091 view = getLeftIconView(); 1092 } else if (featureId == FEATURE_RIGHT_ICON) { 1093 view = getRightIconView(); 1094 } else { 1095 return; 1096 } 1097 1098 if (drawable != null) { 1099 drawable.setAlpha(alpha); 1100 view.setImageDrawable(drawable); 1101 view.setVisibility(View.VISIBLE); 1102 } else { 1103 view.setVisibility(View.GONE); 1104 } 1105 } 1106 1107 /** 1108 * Called when an int feature changes, for the window to update its 1109 * graphics. 1110 * 1111 * @param featureId The feature being changed. 1112 * @param value The new integer value. 1113 */ 1114 protected void onIntChanged(int featureId, int value) { 1115 if (featureId == FEATURE_PROGRESS || featureId == FEATURE_INDETERMINATE_PROGRESS) { 1116 updateProgressBars(value); 1117 } else if (featureId == FEATURE_CUSTOM_TITLE) { 1118 FrameLayout titleContainer = (FrameLayout) findViewById(com.android.internal.R.id.title_container); 1119 if (titleContainer != null) { 1120 mLayoutInflater.inflate(value, titleContainer); 1121 } 1122 } 1123 } 1124 1125 /** 1126 * Updates the progress bars that are shown in the title bar. 1127 * 1128 * @param value Can be one of {@link Window#PROGRESS_VISIBILITY_ON}, 1129 * {@link Window#PROGRESS_VISIBILITY_OFF}, 1130 * {@link Window#PROGRESS_INDETERMINATE_ON}, 1131 * {@link Window#PROGRESS_INDETERMINATE_OFF}, or a value 1132 * starting at {@link Window#PROGRESS_START} through 1133 * {@link Window#PROGRESS_END} for setting the default 1134 * progress (if {@link Window#PROGRESS_END} is given, 1135 * the progress bar widgets in the title will be hidden after an 1136 * animation), a value between 1137 * {@link Window#PROGRESS_SECONDARY_START} - 1138 * {@link Window#PROGRESS_SECONDARY_END} for the 1139 * secondary progress (if 1140 * {@link Window#PROGRESS_SECONDARY_END} is given, the 1141 * progress bar widgets will still be shown with the secondary 1142 * progress bar will be completely filled in.) 1143 */ 1144 private void updateProgressBars(int value) { 1145 ProgressBar circularProgressBar = getCircularProgressBar(true); 1146 ProgressBar horizontalProgressBar = getHorizontalProgressBar(true); 1147 1148 final int features = getLocalFeatures(); 1149 if (value == PROGRESS_VISIBILITY_ON) { 1150 if ((features & (1 << FEATURE_PROGRESS)) != 0) { 1151 int level = horizontalProgressBar.getProgress(); 1152 int visibility = (horizontalProgressBar.isIndeterminate() || level < 10000) ? 1153 View.VISIBLE : View.INVISIBLE; 1154 horizontalProgressBar.setVisibility(visibility); 1155 } 1156 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 1157 circularProgressBar.setVisibility(View.VISIBLE); 1158 } 1159 } else if (value == PROGRESS_VISIBILITY_OFF) { 1160 if ((features & (1 << FEATURE_PROGRESS)) != 0) { 1161 horizontalProgressBar.setVisibility(View.GONE); 1162 } 1163 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 1164 circularProgressBar.setVisibility(View.GONE); 1165 } 1166 } else if (value == PROGRESS_INDETERMINATE_ON) { 1167 horizontalProgressBar.setIndeterminate(true); 1168 } else if (value == PROGRESS_INDETERMINATE_OFF) { 1169 horizontalProgressBar.setIndeterminate(false); 1170 } else if (PROGRESS_START <= value && value <= PROGRESS_END) { 1171 // We want to set the progress value before testing for visibility 1172 // so that when the progress bar becomes visible again, it has the 1173 // correct level. 1174 horizontalProgressBar.setProgress(value - PROGRESS_START); 1175 1176 if (value < PROGRESS_END) { 1177 showProgressBars(horizontalProgressBar, circularProgressBar); 1178 } else { 1179 hideProgressBars(horizontalProgressBar, circularProgressBar); 1180 } 1181 } else if (PROGRESS_SECONDARY_START <= value && value <= PROGRESS_SECONDARY_END) { 1182 horizontalProgressBar.setSecondaryProgress(value - PROGRESS_SECONDARY_START); 1183 1184 showProgressBars(horizontalProgressBar, circularProgressBar); 1185 } 1186 1187 } 1188 1189 private void showProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) { 1190 final int features = getLocalFeatures(); 1191 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 && 1192 spinnyProgressBar.getVisibility() == View.INVISIBLE) { 1193 spinnyProgressBar.setVisibility(View.VISIBLE); 1194 } 1195 // Only show the progress bars if the primary progress is not complete 1196 if ((features & (1 << FEATURE_PROGRESS)) != 0 && 1197 horizontalProgressBar.getProgress() < 10000) { 1198 horizontalProgressBar.setVisibility(View.VISIBLE); 1199 } 1200 } 1201 1202 private void hideProgressBars(ProgressBar horizontalProgressBar, ProgressBar spinnyProgressBar) { 1203 final int features = getLocalFeatures(); 1204 Animation anim = AnimationUtils.loadAnimation(getContext(), com.android.internal.R.anim.fade_out); 1205 anim.setDuration(1000); 1206 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0 && 1207 spinnyProgressBar.getVisibility() == View.VISIBLE) { 1208 spinnyProgressBar.startAnimation(anim); 1209 spinnyProgressBar.setVisibility(View.INVISIBLE); 1210 } 1211 if ((features & (1 << FEATURE_PROGRESS)) != 0 && 1212 horizontalProgressBar.getVisibility() == View.VISIBLE) { 1213 horizontalProgressBar.startAnimation(anim); 1214 horizontalProgressBar.setVisibility(View.INVISIBLE); 1215 } 1216 } 1217 1218 /** 1219 * Request that key events come to this activity. Use this if your activity 1220 * has no views with focus, but the activity still wants a chance to process 1221 * key events. 1222 */ 1223 @Override 1224 public void takeKeyEvents(boolean get) { 1225 mDecor.setFocusable(get); 1226 } 1227 1228 @Override 1229 public boolean superDispatchKeyEvent(KeyEvent event) { 1230 return mDecor.superDispatchKeyEvent(event); 1231 } 1232 1233 @Override 1234 public boolean superDispatchKeyShortcutEvent(KeyEvent event) { 1235 return mDecor.superDispatchKeyShortcutEvent(event); 1236 } 1237 1238 @Override 1239 public boolean superDispatchTouchEvent(MotionEvent event) { 1240 return mDecor.superDispatchTouchEvent(event); 1241 } 1242 1243 @Override 1244 public boolean superDispatchTrackballEvent(MotionEvent event) { 1245 return mDecor.superDispatchTrackballEvent(event); 1246 } 1247 1248 @Override 1249 public boolean superDispatchGenericMotionEvent(MotionEvent event) { 1250 return mDecor.superDispatchGenericMotionEvent(event); 1251 } 1252 1253 /** 1254 * A key was pressed down and not handled by anything else in the window. 1255 * 1256 * @see #onKeyUp 1257 * @see android.view.KeyEvent 1258 */ 1259 protected boolean onKeyDown(int featureId, int keyCode, KeyEvent event) { 1260 /* **************************************************************************** 1261 * HOW TO DECIDE WHERE YOUR KEY HANDLING GOES. 1262 * 1263 * If your key handling must happen before the app gets a crack at the event, 1264 * it goes in PhoneWindowManager. 1265 * 1266 * If your key handling should happen in all windows, and does not depend on 1267 * the state of the current application, other than that the current 1268 * application can override the behavior by handling the event itself, it 1269 * should go in PhoneFallbackEventHandler. 1270 * 1271 * Only if your handling depends on the window, and the fact that it has 1272 * a DecorView, should it go here. 1273 * ****************************************************************************/ 1274 1275 final KeyEvent.DispatcherState dispatcher = 1276 mDecor != null ? mDecor.getKeyDispatcherState() : null; 1277 //Log.i(TAG, "Key down: repeat=" + event.getRepeatCount() 1278 // + " flags=0x" + Integer.toHexString(event.getFlags())); 1279 1280 switch (keyCode) { 1281 case KeyEvent.KEYCODE_VOLUME_UP: 1282 case KeyEvent.KEYCODE_VOLUME_DOWN: 1283 case KeyEvent.KEYCODE_VOLUME_MUTE: { 1284 // Similar code is in PhoneFallbackEventHandler in case the window 1285 // doesn't have one of these. In this case, we execute it here and 1286 // eat the event instead, because we have mVolumeControlStreamType 1287 // and they don't. 1288 getAudioManager().handleKeyDown(keyCode, mVolumeControlStreamType); 1289 return true; 1290 } 1291 1292 case KeyEvent.KEYCODE_MENU: { 1293 onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event); 1294 return true; 1295 } 1296 1297 case KeyEvent.KEYCODE_BACK: { 1298 if (event.getRepeatCount() > 0) break; 1299 if (featureId < 0) break; 1300 // Currently don't do anything with long press. 1301 dispatcher.startTracking(event, this); 1302 return true; 1303 } 1304 1305 } 1306 1307 return false; 1308 } 1309 1310 private KeyguardManager getKeyguardManager() { 1311 if (mKeyguardManager == null) { 1312 mKeyguardManager = (KeyguardManager) getContext().getSystemService( 1313 Context.KEYGUARD_SERVICE); 1314 } 1315 return mKeyguardManager; 1316 } 1317 1318 AudioManager getAudioManager() { 1319 if (mAudioManager == null) { 1320 mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE); 1321 } 1322 return mAudioManager; 1323 } 1324 1325 /** 1326 * A key was released and not handled by anything else in the window. 1327 * 1328 * @see #onKeyDown 1329 * @see android.view.KeyEvent 1330 */ 1331 protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) { 1332 final KeyEvent.DispatcherState dispatcher = 1333 mDecor != null ? mDecor.getKeyDispatcherState() : null; 1334 if (dispatcher != null) { 1335 dispatcher.handleUpEvent(event); 1336 } 1337 //Log.i(TAG, "Key up: repeat=" + event.getRepeatCount() 1338 // + " flags=0x" + Integer.toHexString(event.getFlags())); 1339 1340 switch (keyCode) { 1341 case KeyEvent.KEYCODE_VOLUME_UP: 1342 case KeyEvent.KEYCODE_VOLUME_DOWN: 1343 case KeyEvent.KEYCODE_VOLUME_MUTE: { 1344 // Similar code is in PhoneFallbackEventHandler in case the window 1345 // doesn't have one of these. In this case, we execute it here and 1346 // eat the event instead, because we have mVolumeControlStreamType 1347 // and they don't. 1348 getAudioManager().handleKeyUp(keyCode, mVolumeControlStreamType); 1349 return true; 1350 } 1351 1352 case KeyEvent.KEYCODE_MENU: { 1353 onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId, 1354 event); 1355 return true; 1356 } 1357 1358 case KeyEvent.KEYCODE_BACK: { 1359 if (featureId < 0) break; 1360 if (event.isTracking() && !event.isCanceled()) { 1361 if (featureId == FEATURE_OPTIONS_PANEL) { 1362 PanelFeatureState st = getPanelState(featureId, false); 1363 if (st != null && st.isInExpandedMode) { 1364 // If the user is in an expanded menu and hits back, it 1365 // should go back to the icon menu 1366 reopenMenu(true); 1367 return true; 1368 } 1369 } 1370 closePanel(featureId); 1371 return true; 1372 } 1373 break; 1374 } 1375 1376 case KeyEvent.KEYCODE_SEARCH: { 1377 /* 1378 * Do this in onKeyUp since the Search key is also used for 1379 * chording quick launch shortcuts. 1380 */ 1381 if (getKeyguardManager().inKeyguardRestrictedInputMode()) { 1382 break; 1383 } 1384 if (event.isTracking() && !event.isCanceled()) { 1385 launchDefaultSearch(); 1386 } 1387 return true; 1388 } 1389 } 1390 1391 return false; 1392 } 1393 1394 @Override 1395 protected void onActive() { 1396 } 1397 1398 @Override 1399 public final View getDecorView() { 1400 if (mDecor == null) { 1401 installDecor(); 1402 } 1403 return mDecor; 1404 } 1405 1406 @Override 1407 public final View peekDecorView() { 1408 return mDecor; 1409 } 1410 1411 static private final String FOCUSED_ID_TAG = "android:focusedViewId"; 1412 static private final String VIEWS_TAG = "android:views"; 1413 static private final String PANELS_TAG = "android:Panels"; 1414 static private final String ACTION_BAR_TAG = "android:ActionBar"; 1415 1416 /** {@inheritDoc} */ 1417 @Override 1418 public Bundle saveHierarchyState() { 1419 Bundle outState = new Bundle(); 1420 if (mContentParent == null) { 1421 return outState; 1422 } 1423 1424 SparseArray<Parcelable> states = new SparseArray<Parcelable>(); 1425 mContentParent.saveHierarchyState(states); 1426 outState.putSparseParcelableArray(VIEWS_TAG, states); 1427 1428 // save the focused view id 1429 View focusedView = mContentParent.findFocus(); 1430 if (focusedView != null) { 1431 if (focusedView.getId() != View.NO_ID) { 1432 outState.putInt(FOCUSED_ID_TAG, focusedView.getId()); 1433 } else { 1434 if (false) { 1435 Log.d(TAG, "couldn't save which view has focus because the focused view " 1436 + focusedView + " has no id."); 1437 } 1438 } 1439 } 1440 1441 // save the panels 1442 SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>(); 1443 savePanelState(panelStates); 1444 if (panelStates.size() > 0) { 1445 outState.putSparseParcelableArray(PANELS_TAG, panelStates); 1446 } 1447 1448 if (mActionBar != null) { 1449 SparseArray<Parcelable> actionBarStates = new SparseArray<Parcelable>(); 1450 mActionBar.saveHierarchyState(actionBarStates); 1451 outState.putSparseParcelableArray(ACTION_BAR_TAG, actionBarStates); 1452 } 1453 1454 return outState; 1455 } 1456 1457 /** {@inheritDoc} */ 1458 @Override 1459 public void restoreHierarchyState(Bundle savedInstanceState) { 1460 if (mContentParent == null) { 1461 return; 1462 } 1463 1464 SparseArray<Parcelable> savedStates 1465 = savedInstanceState.getSparseParcelableArray(VIEWS_TAG); 1466 if (savedStates != null) { 1467 mContentParent.restoreHierarchyState(savedStates); 1468 } 1469 1470 // restore the focused view 1471 int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID); 1472 if (focusedViewId != View.NO_ID) { 1473 View needsFocus = mContentParent.findViewById(focusedViewId); 1474 if (needsFocus != null) { 1475 needsFocus.requestFocus(); 1476 } else { 1477 Log.w(TAG, 1478 "Previously focused view reported id " + focusedViewId 1479 + " during save, but can't be found during restore."); 1480 } 1481 } 1482 1483 // restore the panels 1484 SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG); 1485 if (panelStates != null) { 1486 restorePanelState(panelStates); 1487 } 1488 1489 if (mActionBar != null) { 1490 SparseArray<Parcelable> actionBarStates = 1491 savedInstanceState.getSparseParcelableArray(ACTION_BAR_TAG); 1492 mActionBar.restoreHierarchyState(actionBarStates); 1493 } 1494 } 1495 1496 /** 1497 * Invoked when the panels should freeze their state. 1498 * 1499 * @param icicles Save state into this. This is usually indexed by the 1500 * featureId. This will be given to {@link #restorePanelState} in the 1501 * future. 1502 */ 1503 private void savePanelState(SparseArray<Parcelable> icicles) { 1504 PanelFeatureState[] panels = mPanels; 1505 if (panels == null) { 1506 return; 1507 } 1508 1509 for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) { 1510 if (panels[curFeatureId] != null) { 1511 icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState()); 1512 } 1513 } 1514 } 1515 1516 /** 1517 * Invoked when the panels should thaw their state from a previously frozen state. 1518 * 1519 * @param icicles The state saved by {@link #savePanelState} that needs to be thawed. 1520 */ 1521 private void restorePanelState(SparseArray<Parcelable> icicles) { 1522 PanelFeatureState st; 1523 for (int curFeatureId = icicles.size() - 1; curFeatureId >= 0; curFeatureId--) { 1524 st = getPanelState(curFeatureId, false /* required */); 1525 if (st == null) { 1526 // The panel must not have been required, and is currently not around, skip it 1527 continue; 1528 } 1529 1530 st.onRestoreInstanceState(icicles.get(curFeatureId)); 1531 invalidatePanelMenu(curFeatureId); 1532 } 1533 1534 /* 1535 * Implementation note: call openPanelsAfterRestore later to actually open the 1536 * restored panels. 1537 */ 1538 } 1539 1540 /** 1541 * Opens the panels that have had their state restored. This should be 1542 * called sometime after {@link #restorePanelState} when it is safe to add 1543 * to the window manager. 1544 */ 1545 private void openPanelsAfterRestore() { 1546 PanelFeatureState[] panels = mPanels; 1547 1548 if (panels == null) { 1549 return; 1550 } 1551 1552 PanelFeatureState st; 1553 for (int i = panels.length - 1; i >= 0; i--) { 1554 st = panels[i]; 1555 // We restore the panel if it was last open; we skip it if it 1556 // now is open, to avoid a race condition if the user immediately 1557 // opens it when we are resuming. 1558 if ((st != null) && !st.isOpen && st.wasLastOpen) { 1559 st.isInExpandedMode = st.wasLastExpanded; 1560 openPanel(st, null); 1561 } 1562 } 1563 } 1564 1565 private class PanelMenuPresenterCallback implements MenuPresenter.Callback { 1566 @Override 1567 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 1568 final Menu parentMenu = menu.getRootMenu(); 1569 final boolean isSubMenu = parentMenu != menu; 1570 final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu); 1571 if (panel != null) { 1572 if (isSubMenu) { 1573 callOnPanelClosed(panel.featureId, panel, parentMenu); 1574 closePanel(panel, true); 1575 } else { 1576 // Close the panel and only do the callback if the menu is being 1577 // closed completely, not if opening a sub menu 1578 closePanel(panel, allMenusAreClosing); 1579 } 1580 } 1581 } 1582 1583 @Override 1584 public boolean onOpenSubMenu(MenuBuilder subMenu) { 1585 if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) { 1586 Callback cb = getCallback(); 1587 if (cb != null && !isDestroyed()) { 1588 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 1589 } 1590 } 1591 1592 return true; 1593 } 1594 } 1595 1596 private final class ActionMenuPresenterCallback implements MenuPresenter.Callback { 1597 @Override 1598 public boolean onOpenSubMenu(MenuBuilder subMenu) { 1599 Callback cb = getCallback(); 1600 if (cb != null) { 1601 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 1602 return true; 1603 } 1604 return false; 1605 } 1606 1607 @Override 1608 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 1609 checkCloseActionMenu(menu); 1610 } 1611 } 1612 1613 private final class DecorView extends FrameLayout implements RootViewSurfaceTaker { 1614 /* package */int mDefaultOpacity = PixelFormat.OPAQUE; 1615 1616 /** The feature ID of the panel, or -1 if this is the application's DecorView */ 1617 private final int mFeatureId; 1618 1619 private final Rect mDrawingBounds = new Rect(); 1620 1621 private final Rect mBackgroundPadding = new Rect(); 1622 1623 private final Rect mFramePadding = new Rect(); 1624 1625 private final Rect mFrameOffsets = new Rect(); 1626 1627 private boolean mChanging; 1628 1629 private Drawable mMenuBackground; 1630 private boolean mWatchingForMenu; 1631 private int mDownY; 1632 1633 private ActionMode mActionMode; 1634 private ActionBarContextView mActionModeView; 1635 private PopupWindow mActionModePopup; 1636 private Runnable mShowActionModePopup; 1637 1638 public DecorView(Context context, int featureId) { 1639 super(context); 1640 mFeatureId = featureId; 1641 } 1642 1643 @Override 1644 public boolean dispatchKeyEvent(KeyEvent event) { 1645 final int keyCode = event.getKeyCode(); 1646 final int action = event.getAction(); 1647 final boolean isDown = action == KeyEvent.ACTION_DOWN; 1648 1649 if (isDown && (event.getRepeatCount() == 0)) { 1650 // First handle chording of panel key: if a panel key is held 1651 // but not released, try to execute a shortcut in it. 1652 if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) { 1653 boolean handled = dispatchKeyShortcutEvent(event); 1654 if (handled) { 1655 return true; 1656 } 1657 } 1658 1659 // If a panel is open, perform a shortcut on it without the 1660 // chorded panel key 1661 if ((mPreparedPanel != null) && mPreparedPanel.isOpen) { 1662 if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) { 1663 return true; 1664 } 1665 } 1666 } 1667 1668 // Back cancels action modes first. 1669 if (mActionMode != null && keyCode == KeyEvent.KEYCODE_BACK) { 1670 if (action == KeyEvent.ACTION_UP) { 1671 mActionMode.finish(); 1672 } 1673 return true; 1674 } 1675 1676 if (!isDestroyed()) { 1677 final Callback cb = getCallback(); 1678 final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event) 1679 : super.dispatchKeyEvent(event); 1680 if (handled) { 1681 return true; 1682 } 1683 } 1684 return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event) 1685 : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event); 1686 } 1687 1688 @Override 1689 public boolean dispatchKeyShortcutEvent(KeyEvent ev) { 1690 // Perform the shortcut (mPreparedPanel can be null since 1691 // global shortcuts (such as search) don't rely on a 1692 // prepared panel or menu). 1693 boolean handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev, 1694 Menu.FLAG_PERFORM_NO_CLOSE); 1695 if (handled) { 1696 if (mPreparedPanel != null) { 1697 mPreparedPanel.isHandled = true; 1698 } 1699 return true; 1700 } 1701 1702 // Shortcut not handled by the panel. Dispatch to the view hierarchy. 1703 final Callback cb = getCallback(); 1704 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchKeyShortcutEvent(ev) 1705 : super.dispatchKeyShortcutEvent(ev); 1706 } 1707 1708 @Override 1709 public boolean dispatchTouchEvent(MotionEvent ev) { 1710 final Callback cb = getCallback(); 1711 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) 1712 : super.dispatchTouchEvent(ev); 1713 } 1714 1715 @Override 1716 public boolean dispatchTrackballEvent(MotionEvent ev) { 1717 final Callback cb = getCallback(); 1718 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev) 1719 : super.dispatchTrackballEvent(ev); 1720 } 1721 1722 @Override 1723 public boolean dispatchGenericMotionEvent(MotionEvent ev) { 1724 final Callback cb = getCallback(); 1725 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev) 1726 : super.dispatchGenericMotionEvent(ev); 1727 } 1728 1729 public boolean superDispatchKeyEvent(KeyEvent event) { 1730 return super.dispatchKeyEvent(event); 1731 } 1732 1733 public boolean superDispatchKeyShortcutEvent(KeyEvent event) { 1734 return super.dispatchKeyShortcutEvent(event); 1735 } 1736 1737 public boolean superDispatchTouchEvent(MotionEvent event) { 1738 return super.dispatchTouchEvent(event); 1739 } 1740 1741 public boolean superDispatchTrackballEvent(MotionEvent event) { 1742 return super.dispatchTrackballEvent(event); 1743 } 1744 1745 public boolean superDispatchGenericMotionEvent(MotionEvent event) { 1746 return super.dispatchGenericMotionEvent(event); 1747 } 1748 1749 @Override 1750 public boolean onTouchEvent(MotionEvent event) { 1751 return onInterceptTouchEvent(event); 1752 } 1753 1754 private boolean isOutOfBounds(int x, int y) { 1755 return x < -5 || y < -5 || x > (getWidth() + 5) 1756 || y > (getHeight() + 5); 1757 } 1758 1759 @Override 1760 public boolean onInterceptTouchEvent(MotionEvent event) { 1761 int action = event.getAction(); 1762 if (mFeatureId >= 0) { 1763 if (action == MotionEvent.ACTION_DOWN) { 1764 int x = (int)event.getX(); 1765 int y = (int)event.getY(); 1766 if (isOutOfBounds(x, y)) { 1767 closePanel(mFeatureId); 1768 return true; 1769 } 1770 } 1771 } 1772 1773 if (!SWEEP_OPEN_MENU) { 1774 return false; 1775 } 1776 1777 if (mFeatureId >= 0) { 1778 if (action == MotionEvent.ACTION_DOWN) { 1779 Log.i(TAG, "Watchiing!"); 1780 mWatchingForMenu = true; 1781 mDownY = (int) event.getY(); 1782 return false; 1783 } 1784 1785 if (!mWatchingForMenu) { 1786 return false; 1787 } 1788 1789 int y = (int)event.getY(); 1790 if (action == MotionEvent.ACTION_MOVE) { 1791 if (y > (mDownY+30)) { 1792 Log.i(TAG, "Closing!"); 1793 closePanel(mFeatureId); 1794 mWatchingForMenu = false; 1795 return true; 1796 } 1797 } else if (action == MotionEvent.ACTION_UP) { 1798 mWatchingForMenu = false; 1799 } 1800 1801 return false; 1802 } 1803 1804 //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY() 1805 // + " (in " + getHeight() + ")"); 1806 1807 if (action == MotionEvent.ACTION_DOWN) { 1808 int y = (int)event.getY(); 1809 if (y >= (getHeight()-5) && !hasChildren()) { 1810 Log.i(TAG, "Watchiing!"); 1811 mWatchingForMenu = true; 1812 } 1813 return false; 1814 } 1815 1816 if (!mWatchingForMenu) { 1817 return false; 1818 } 1819 1820 int y = (int)event.getY(); 1821 if (action == MotionEvent.ACTION_MOVE) { 1822 if (y < (getHeight()-30)) { 1823 Log.i(TAG, "Opening!"); 1824 openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent( 1825 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)); 1826 mWatchingForMenu = false; 1827 return true; 1828 } 1829 } else if (action == MotionEvent.ACTION_UP) { 1830 mWatchingForMenu = false; 1831 } 1832 1833 return false; 1834 } 1835 1836 @Override 1837 public void sendAccessibilityEvent(int eventType) { 1838 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 1839 return; 1840 } 1841 1842 // if we are showing a feature that should be announced and one child 1843 // make this child the event source since this is the feature itself 1844 // otherwise the callback will take over and announce its client 1845 if ((mFeatureId == FEATURE_OPTIONS_PANEL || 1846 mFeatureId == FEATURE_CONTEXT_MENU || 1847 mFeatureId == FEATURE_PROGRESS || 1848 mFeatureId == FEATURE_INDETERMINATE_PROGRESS) 1849 && getChildCount() == 1) { 1850 getChildAt(0).sendAccessibilityEvent(eventType); 1851 } else { 1852 super.sendAccessibilityEvent(eventType); 1853 } 1854 } 1855 1856 @Override 1857 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 1858 final Callback cb = getCallback(); 1859 if (cb != null && !isDestroyed()) { 1860 if (cb.dispatchPopulateAccessibilityEvent(event)) { 1861 return true; 1862 } 1863 } 1864 return super.dispatchPopulateAccessibilityEvent(event); 1865 } 1866 1867 @Override 1868 protected boolean setFrame(int l, int t, int r, int b) { 1869 boolean changed = super.setFrame(l, t, r, b); 1870 if (changed) { 1871 final Rect drawingBounds = mDrawingBounds; 1872 getDrawingRect(drawingBounds); 1873 1874 Drawable fg = getForeground(); 1875 if (fg != null) { 1876 final Rect frameOffsets = mFrameOffsets; 1877 drawingBounds.left += frameOffsets.left; 1878 drawingBounds.top += frameOffsets.top; 1879 drawingBounds.right -= frameOffsets.right; 1880 drawingBounds.bottom -= frameOffsets.bottom; 1881 fg.setBounds(drawingBounds); 1882 final Rect framePadding = mFramePadding; 1883 drawingBounds.left += framePadding.left - frameOffsets.left; 1884 drawingBounds.top += framePadding.top - frameOffsets.top; 1885 drawingBounds.right -= framePadding.right - frameOffsets.right; 1886 drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom; 1887 } 1888 1889 Drawable bg = getBackground(); 1890 if (bg != null) { 1891 bg.setBounds(drawingBounds); 1892 } 1893 1894 if (SWEEP_OPEN_MENU) { 1895 if (mMenuBackground == null && mFeatureId < 0 1896 && getAttributes().height 1897 == WindowManager.LayoutParams.MATCH_PARENT) { 1898 mMenuBackground = getContext().getResources().getDrawable( 1899 com.android.internal.R.drawable.menu_background); 1900 } 1901 if (mMenuBackground != null) { 1902 mMenuBackground.setBounds(drawingBounds.left, 1903 drawingBounds.bottom-6, drawingBounds.right, 1904 drawingBounds.bottom+20); 1905 } 1906 } 1907 } 1908 return changed; 1909 } 1910 1911 @Override 1912 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1913 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); 1914 final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; 1915 1916 final int widthMode = getMode(widthMeasureSpec); 1917 1918 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1919 1920 int width = getMeasuredWidth(); 1921 boolean measure = false; 1922 1923 widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); 1924 1925 final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; 1926 1927 if (widthMode == AT_MOST && tv.type != TypedValue.TYPE_NULL) { 1928 final int min; 1929 if (tv.type == TypedValue.TYPE_DIMENSION) { 1930 min = (int)tv.getDimension(metrics); 1931 } else if (tv.type == TypedValue.TYPE_FRACTION) { 1932 min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); 1933 } else { 1934 min = 0; 1935 } 1936 1937 if (width < min) { 1938 widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); 1939 measure = true; 1940 } 1941 } 1942 1943 // TODO: Support height? 1944 1945 if (measure) { 1946 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1947 } 1948 } 1949 1950 @Override 1951 public void draw(Canvas canvas) { 1952 super.draw(canvas); 1953 1954 if (mMenuBackground != null) { 1955 mMenuBackground.draw(canvas); 1956 } 1957 } 1958 1959 1960 @Override 1961 public boolean showContextMenuForChild(View originalView) { 1962 // Reuse the context menu builder 1963 if (mContextMenu == null) { 1964 mContextMenu = new ContextMenuBuilder(getContext()); 1965 mContextMenu.setCallback(mContextMenuCallback); 1966 } else { 1967 mContextMenu.clearAll(); 1968 } 1969 1970 final MenuDialogHelper helper = mContextMenu.show(originalView, 1971 originalView.getWindowToken()); 1972 if (helper != null) { 1973 helper.setPresenterCallback(mContextMenuCallback); 1974 } 1975 mContextMenuHelper = helper; 1976 return helper != null; 1977 } 1978 1979 @Override 1980 public ActionMode startActionModeForChild(View originalView, 1981 ActionMode.Callback callback) { 1982 // originalView can be used here to be sure that we don't obscure 1983 // relevant content with the context mode UI. 1984 return startActionMode(callback); 1985 } 1986 1987 @Override 1988 public ActionMode startActionMode(ActionMode.Callback callback) { 1989 if (mActionMode != null) { 1990 mActionMode.finish(); 1991 } 1992 1993 final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback); 1994 ActionMode mode = null; 1995 if (getCallback() != null && !isDestroyed()) { 1996 try { 1997 mode = getCallback().onWindowStartingActionMode(wrappedCallback); 1998 } catch (AbstractMethodError ame) { 1999 // Older apps might not implement this callback method. 2000 } 2001 } 2002 if (mode != null) { 2003 mActionMode = mode; 2004 } else { 2005 if (mActionModeView == null) { 2006 if (hasFeature(FEATURE_ACTION_MODE_OVERLAY)) { 2007 mActionModeView = new ActionBarContextView(mContext); 2008 mActionModePopup = new PopupWindow(mContext, null, 2009 com.android.internal.R.attr.actionModePopupWindowStyle); 2010 mActionModePopup.setLayoutInScreenEnabled(true); 2011 mActionModePopup.setClippingEnabled(false); 2012 mActionModePopup.setContentView(mActionModeView); 2013 mActionModePopup.setWidth(MATCH_PARENT); 2014 2015 TypedValue heightValue = new TypedValue(); 2016 mContext.getTheme().resolveAttribute( 2017 com.android.internal.R.attr.actionBarSize, heightValue, false); 2018 final int height = TypedValue.complexToDimensionPixelSize(heightValue.data, 2019 mContext.getResources().getDisplayMetrics()); 2020 mActionModePopup.setHeight(height); 2021 mShowActionModePopup = new Runnable() { 2022 public void run() { 2023 mActionModePopup.showAtLocation(PhoneWindow.DecorView.this, 2024 Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0); 2025 } 2026 }; 2027 } else { 2028 ViewStub stub = (ViewStub) findViewById( 2029 com.android.internal.R.id.action_mode_bar_stub); 2030 if (stub != null) { 2031 mActionModeView = (ActionBarContextView) stub.inflate(); 2032 } 2033 } 2034 } 2035 2036 if (mActionModeView != null) { 2037 mActionModeView.killMode(); 2038 mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback); 2039 if (callback.onCreateActionMode(mode, mode.getMenu())) { 2040 mode.invalidate(); 2041 mActionModeView.initForMode(mode); 2042 mActionModeView.setVisibility(View.VISIBLE); 2043 mActionMode = mode; 2044 if (mActionModePopup != null) { 2045 post(mShowActionModePopup); 2046 } 2047 } else { 2048 mActionMode = null; 2049 } 2050 } 2051 } 2052 if (mActionMode != null && getCallback() != null && !isDestroyed()) { 2053 try { 2054 getCallback().onActionModeStarted(mActionMode); 2055 } catch (AbstractMethodError ame) { 2056 // Older apps might not implement this callback method. 2057 } 2058 } 2059 return mActionMode; 2060 } 2061 2062 public void startChanging() { 2063 mChanging = true; 2064 } 2065 2066 public void finishChanging() { 2067 mChanging = false; 2068 drawableChanged(); 2069 } 2070 2071 public void setWindowBackground(Drawable drawable) { 2072 if (getBackground() != drawable) { 2073 setBackgroundDrawable(drawable); 2074 if (drawable != null) { 2075 drawable.getPadding(mBackgroundPadding); 2076 } else { 2077 mBackgroundPadding.setEmpty(); 2078 } 2079 drawableChanged(); 2080 } 2081 } 2082 2083 @Override 2084 public void setBackgroundDrawable(Drawable d) { 2085 super.setBackgroundDrawable(d); 2086 if (getWindowToken() != null) { 2087 updateWindowResizeState(); 2088 } 2089 } 2090 2091 public void setWindowFrame(Drawable drawable) { 2092 if (getForeground() != drawable) { 2093 setForeground(drawable); 2094 if (drawable != null) { 2095 drawable.getPadding(mFramePadding); 2096 } else { 2097 mFramePadding.setEmpty(); 2098 } 2099 drawableChanged(); 2100 } 2101 } 2102 2103 @Override 2104 protected boolean fitSystemWindows(Rect insets) { 2105 mFrameOffsets.set(insets); 2106 if (getForeground() != null) { 2107 drawableChanged(); 2108 } 2109 return super.fitSystemWindows(insets); 2110 } 2111 2112 private void drawableChanged() { 2113 if (mChanging) { 2114 return; 2115 } 2116 2117 setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top 2118 + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right, 2119 mFramePadding.bottom + mBackgroundPadding.bottom); 2120 requestLayout(); 2121 invalidate(); 2122 2123 int opacity = PixelFormat.OPAQUE; 2124 2125 // Note: if there is no background, we will assume opaque. The 2126 // common case seems to be that an application sets there to be 2127 // no background so it can draw everything itself. For that, 2128 // we would like to assume OPAQUE and let the app force it to 2129 // the slower TRANSLUCENT mode if that is really what it wants. 2130 Drawable bg = getBackground(); 2131 Drawable fg = getForeground(); 2132 if (bg != null) { 2133 if (fg == null) { 2134 opacity = bg.getOpacity(); 2135 } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0 2136 && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) { 2137 // If the frame padding is zero, then we can be opaque 2138 // if either the frame -or- the background is opaque. 2139 int fop = fg.getOpacity(); 2140 int bop = bg.getOpacity(); 2141 if (false) 2142 Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop); 2143 if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) { 2144 opacity = PixelFormat.OPAQUE; 2145 } else if (fop == PixelFormat.UNKNOWN) { 2146 opacity = bop; 2147 } else if (bop == PixelFormat.UNKNOWN) { 2148 opacity = fop; 2149 } else { 2150 opacity = Drawable.resolveOpacity(fop, bop); 2151 } 2152 } else { 2153 // For now we have to assume translucent if there is a 2154 // frame with padding... there is no way to tell if the 2155 // frame and background together will draw all pixels. 2156 if (false) 2157 Log.v(TAG, "Padding: " + mFramePadding); 2158 opacity = PixelFormat.TRANSLUCENT; 2159 } 2160 } 2161 2162 if (false) 2163 Log.v(TAG, "Background: " + bg + ", Frame: " + fg); 2164 if (false) 2165 Log.v(TAG, "Selected default opacity: " + opacity); 2166 2167 mDefaultOpacity = opacity; 2168 if (mFeatureId < 0) { 2169 setDefaultWindowFormat(opacity); 2170 } 2171 } 2172 2173 @Override 2174 public void onWindowFocusChanged(boolean hasWindowFocus) { 2175 super.onWindowFocusChanged(hasWindowFocus); 2176 2177 // If the user is chording a menu shortcut, release the chord since 2178 // this window lost focus 2179 if (!hasWindowFocus && mPanelChordingKey != 0) { 2180 closePanel(FEATURE_OPTIONS_PANEL); 2181 } 2182 2183 final Callback cb = getCallback(); 2184 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2185 cb.onWindowFocusChanged(hasWindowFocus); 2186 } 2187 } 2188 2189 void updateWindowResizeState() { 2190 Drawable bg = getBackground(); 2191 hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity() 2192 != PixelFormat.OPAQUE); 2193 } 2194 2195 @Override 2196 protected void onAttachedToWindow() { 2197 super.onAttachedToWindow(); 2198 2199 updateWindowResizeState(); 2200 2201 final Callback cb = getCallback(); 2202 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2203 cb.onAttachedToWindow(); 2204 } 2205 2206 if (mFeatureId == -1) { 2207 /* 2208 * The main window has been attached, try to restore any panels 2209 * that may have been open before. This is called in cases where 2210 * an activity is being killed for configuration change and the 2211 * menu was open. When the activity is recreated, the menu 2212 * should be shown again. 2213 */ 2214 openPanelsAfterRestore(); 2215 } 2216 } 2217 2218 @Override 2219 protected void onDetachedFromWindow() { 2220 super.onDetachedFromWindow(); 2221 2222 final Callback cb = getCallback(); 2223 if (cb != null && mFeatureId < 0) { 2224 cb.onDetachedFromWindow(); 2225 } 2226 2227 if (mActionBar != null) { 2228 mActionBar.dismissPopupMenus(); 2229 } 2230 2231 if (mActionModePopup != null) { 2232 removeCallbacks(mShowActionModePopup); 2233 if (mActionModePopup.isShowing()) { 2234 mActionModePopup.dismiss(); 2235 } 2236 mActionModePopup = null; 2237 } 2238 } 2239 2240 @Override 2241 public void onCloseSystemDialogs(String reason) { 2242 if (mFeatureId >= 0) { 2243 closeAllPanels(); 2244 } 2245 } 2246 2247 public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() { 2248 return mFeatureId < 0 ? mTakeSurfaceCallback : null; 2249 } 2250 2251 public InputQueue.Callback willYouTakeTheInputQueue() { 2252 return mFeatureId < 0 ? mTakeInputQueueCallback : null; 2253 } 2254 2255 public void setSurfaceType(int type) { 2256 PhoneWindow.this.setType(type); 2257 } 2258 2259 public void setSurfaceFormat(int format) { 2260 PhoneWindow.this.setFormat(format); 2261 } 2262 2263 public void setSurfaceKeepScreenOn(boolean keepOn) { 2264 if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2265 else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2266 } 2267 2268 /** 2269 * Clears out internal reference when the action mode is destroyed. 2270 */ 2271 private class ActionModeCallbackWrapper implements ActionMode.Callback { 2272 private ActionMode.Callback mWrapped; 2273 2274 public ActionModeCallbackWrapper(ActionMode.Callback wrapped) { 2275 mWrapped = wrapped; 2276 } 2277 2278 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 2279 return mWrapped.onCreateActionMode(mode, menu); 2280 } 2281 2282 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 2283 return mWrapped.onPrepareActionMode(mode, menu); 2284 } 2285 2286 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 2287 return mWrapped.onActionItemClicked(mode, item); 2288 } 2289 2290 public void onDestroyActionMode(ActionMode mode) { 2291 mWrapped.onDestroyActionMode(mode); 2292 if (mActionModePopup != null) { 2293 removeCallbacks(mShowActionModePopup); 2294 mActionModePopup.dismiss(); 2295 } else if (mActionModeView != null) { 2296 mActionModeView.setVisibility(GONE); 2297 } 2298 if (mActionModeView != null) { 2299 mActionModeView.removeAllViews(); 2300 } 2301 if (getCallback() != null && !isDestroyed()) { 2302 try { 2303 getCallback().onActionModeFinished(mActionMode); 2304 } catch (AbstractMethodError ame) { 2305 // Older apps might not implement this callback method. 2306 } 2307 } 2308 mActionMode = null; 2309 } 2310 } 2311 } 2312 2313 protected DecorView generateDecor() { 2314 return new DecorView(getContext(), -1); 2315 } 2316 2317 protected void setFeatureFromAttrs(int featureId, TypedArray attrs, 2318 int drawableAttr, int alphaAttr) { 2319 Drawable d = attrs.getDrawable(drawableAttr); 2320 if (d != null) { 2321 requestFeature(featureId); 2322 setFeatureDefaultDrawable(featureId, d); 2323 } 2324 if ((getFeatures() & (1 << featureId)) != 0) { 2325 int alpha = attrs.getInt(alphaAttr, -1); 2326 if (alpha >= 0) { 2327 setFeatureDrawableAlpha(featureId, alpha); 2328 } 2329 } 2330 } 2331 2332 protected ViewGroup generateLayout(DecorView decor) { 2333 // Apply data from current theme. 2334 2335 TypedArray a = getWindowStyle(); 2336 2337 if (false) { 2338 System.out.println("From style:"); 2339 String s = "Attrs:"; 2340 for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) { 2341 s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "=" 2342 + a.getString(i); 2343 } 2344 System.out.println(s); 2345 } 2346 2347 mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false); 2348 int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR) 2349 & (~getForcedWindowFlags()); 2350 if (mIsFloating) { 2351 setLayout(WRAP_CONTENT, WRAP_CONTENT); 2352 setFlags(0, flagsToUpdate); 2353 } else { 2354 setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate); 2355 } 2356 2357 if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) { 2358 requestFeature(FEATURE_NO_TITLE); 2359 } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) { 2360 // Don't allow an action bar if there is no title. 2361 requestFeature(FEATURE_ACTION_BAR); 2362 } 2363 2364 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) { 2365 requestFeature(FEATURE_ACTION_BAR_OVERLAY); 2366 } 2367 2368 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) { 2369 requestFeature(FEATURE_ACTION_MODE_OVERLAY); 2370 } 2371 2372 if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) { 2373 setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags())); 2374 } 2375 2376 if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) { 2377 setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags())); 2378 } 2379 2380 if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch, 2381 getContext().getApplicationInfo().targetSdkVersion 2382 >= android.os.Build.VERSION_CODES.HONEYCOMB)) { 2383 setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags())); 2384 } 2385 2386 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor); 2387 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor); 2388 2389 if (getContext().getApplicationInfo().targetSdkVersion 2390 < android.os.Build.VERSION_CODES.HONEYCOMB) { 2391 addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY); 2392 } 2393 2394 if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion 2395 >= android.os.Build.VERSION_CODES.HONEYCOMB) { 2396 if (a.getBoolean( 2397 com.android.internal.R.styleable.Window_windowCloseOnTouchOutside, 2398 false)) { 2399 setCloseOnTouchOutsideIfNotSet(true); 2400 } 2401 } 2402 2403 WindowManager.LayoutParams params = getAttributes(); 2404 2405 if (!hasSoftInputMode()) { 2406 params.softInputMode = a.getInt( 2407 com.android.internal.R.styleable.Window_windowSoftInputMode, 2408 params.softInputMode); 2409 } 2410 2411 if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled, 2412 mIsFloating)) { 2413 /* All dialogs should have the window dimmed */ 2414 if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) { 2415 params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; 2416 } 2417 params.dimAmount = a.getFloat( 2418 android.R.styleable.Window_backgroundDimAmount, 0.5f); 2419 } 2420 2421 if (params.windowAnimations == 0) { 2422 params.windowAnimations = a.getResourceId( 2423 com.android.internal.R.styleable.Window_windowAnimationStyle, 0); 2424 } 2425 2426 // The rest are only done if this window is not embedded; otherwise, 2427 // the values are inherited from our container. 2428 if (getContainer() == null) { 2429 if (mBackgroundDrawable == null) { 2430 if (mBackgroundResource == 0) { 2431 mBackgroundResource = a.getResourceId( 2432 com.android.internal.R.styleable.Window_windowBackground, 0); 2433 } 2434 if (mFrameResource == 0) { 2435 mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0); 2436 } 2437 if (false) { 2438 System.out.println("Background: " 2439 + Integer.toHexString(mBackgroundResource) + " Frame: " 2440 + Integer.toHexString(mFrameResource)); 2441 } 2442 } 2443 mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000); 2444 } 2445 2446 // Inflate the window decor. 2447 2448 int layoutResource; 2449 int features = getLocalFeatures(); 2450 // System.out.println("Features: 0x" + Integer.toHexString(features)); 2451 if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) { 2452 if (mIsFloating) { 2453 TypedValue res = new TypedValue(); 2454 getContext().getTheme().resolveAttribute( 2455 com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true); 2456 layoutResource = res.resourceId; 2457 } else { 2458 layoutResource = com.android.internal.R.layout.screen_title_icons; 2459 } 2460 // XXX Remove this once action bar supports these features. 2461 removeFeature(FEATURE_ACTION_BAR); 2462 // System.out.println("Title Icons!"); 2463 } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0 2464 && (features & (1 << FEATURE_ACTION_BAR)) == 0) { 2465 // Special case for a window with only a progress bar (and title). 2466 // XXX Need to have a no-title version of embedded windows. 2467 layoutResource = com.android.internal.R.layout.screen_progress; 2468 // System.out.println("Progress!"); 2469 } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) { 2470 // Special case for a window with a custom title. 2471 // If the window is floating, we need a dialog layout 2472 if (mIsFloating) { 2473 TypedValue res = new TypedValue(); 2474 getContext().getTheme().resolveAttribute( 2475 com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true); 2476 layoutResource = res.resourceId; 2477 } else { 2478 layoutResource = com.android.internal.R.layout.screen_custom_title; 2479 } 2480 // XXX Remove this once action bar supports these features. 2481 removeFeature(FEATURE_ACTION_BAR); 2482 } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) { 2483 // If no other features and not embedded, only need a title. 2484 // If the window is floating, we need a dialog layout 2485 if (mIsFloating) { 2486 TypedValue res = new TypedValue(); 2487 getContext().getTheme().resolveAttribute( 2488 com.android.internal.R.attr.dialogTitleDecorLayout, res, true); 2489 layoutResource = res.resourceId; 2490 } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) { 2491 if ((features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0) { 2492 layoutResource = com.android.internal.R.layout.screen_action_bar_overlay; 2493 } else { 2494 layoutResource = com.android.internal.R.layout.screen_action_bar; 2495 } 2496 } else { 2497 layoutResource = com.android.internal.R.layout.screen_title; 2498 } 2499 // System.out.println("Title!"); 2500 } else { 2501 // Embedded, so no decoration is needed. 2502 layoutResource = com.android.internal.R.layout.screen_simple; 2503 // System.out.println("Simple!"); 2504 } 2505 2506 mDecor.startChanging(); 2507 2508 View in = mLayoutInflater.inflate(layoutResource, null); 2509 decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 2510 2511 ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); 2512 if (contentParent == null) { 2513 throw new RuntimeException("Window couldn't find content container view"); 2514 } 2515 2516 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 2517 ProgressBar progress = getCircularProgressBar(false); 2518 if (progress != null) { 2519 progress.setIndeterminate(true); 2520 } 2521 } 2522 2523 // Remaining setup -- of background and title -- that only applies 2524 // to top-level windows. 2525 if (getContainer() == null) { 2526 Drawable drawable = mBackgroundDrawable; 2527 if (mBackgroundResource != 0) { 2528 drawable = getContext().getResources().getDrawable(mBackgroundResource); 2529 } 2530 mDecor.setWindowBackground(drawable); 2531 drawable = null; 2532 if (mFrameResource != 0) { 2533 drawable = getContext().getResources().getDrawable(mFrameResource); 2534 } 2535 mDecor.setWindowFrame(drawable); 2536 2537 // System.out.println("Text=" + Integer.toHexString(mTextColor) + 2538 // " Sel=" + Integer.toHexString(mTextSelectedColor) + 2539 // " Title=" + Integer.toHexString(mTitleColor)); 2540 2541 if (mTitleColor == 0) { 2542 mTitleColor = mTextColor; 2543 } 2544 2545 if (mTitle != null) { 2546 setTitle(mTitle); 2547 } 2548 setTitleColor(mTitleColor); 2549 } 2550 2551 mDecor.finishChanging(); 2552 2553 return contentParent; 2554 } 2555 2556 /** @hide */ 2557 public void alwaysReadCloseOnTouchAttr() { 2558 mAlwaysReadCloseOnTouchAttr = true; 2559 } 2560 2561 private void installDecor() { 2562 if (mDecor == null) { 2563 mDecor = generateDecor(); 2564 mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); 2565 mDecor.setIsRootNamespace(true); 2566 } 2567 if (mContentParent == null) { 2568 mContentParent = generateLayout(mDecor); 2569 2570 mTitleView = (TextView)findViewById(com.android.internal.R.id.title); 2571 if (mTitleView != null) { 2572 if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) { 2573 View titleContainer = findViewById(com.android.internal.R.id.title_container); 2574 if (titleContainer != null) { 2575 titleContainer.setVisibility(View.GONE); 2576 } else { 2577 mTitleView.setVisibility(View.GONE); 2578 } 2579 if (mContentParent instanceof FrameLayout) { 2580 ((FrameLayout)mContentParent).setForeground(null); 2581 } 2582 } else { 2583 mTitleView.setText(mTitle); 2584 } 2585 } else { 2586 mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar); 2587 if (mActionBar != null) { 2588 if (mActionBar.getTitle() == null) { 2589 mActionBar.setWindowTitle(mTitle); 2590 } 2591 final int localFeatures = getLocalFeatures(); 2592 if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) { 2593 mActionBar.initProgress(); 2594 } 2595 if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 2596 mActionBar.initIndeterminateProgress(); 2597 } 2598 2599 final boolean splitActionBar = getWindowStyle().getBoolean( 2600 com.android.internal.R.styleable.Window_windowSplitActionBar, false); 2601 if (splitActionBar) { 2602 final ActionBarContainer splitView = (ActionBarContainer) findViewById( 2603 com.android.internal.R.id.split_action_bar); 2604 if (splitView != null) { 2605 splitView.setVisibility(View.VISIBLE); 2606 mActionBar.setSplitActionBar(splitActionBar); 2607 mActionBar.setSplitView(splitView); 2608 2609 final ActionBarContextView cab = (ActionBarContextView) findViewById( 2610 com.android.internal.R.id.action_context_bar); 2611 cab.setSplitView(splitView); 2612 } else { 2613 Log.e(TAG, "Window style requested split action bar with " + 2614 "incompatible window decor! Ignoring request."); 2615 } 2616 } 2617 2618 // Post the panel invalidate for later; avoid application onCreateOptionsMenu 2619 // being called in the middle of onCreate or similar. 2620 mDecor.post(new Runnable() { 2621 public void run() { 2622 if (!isDestroyed()) { 2623 invalidatePanelMenu(FEATURE_ACTION_BAR); 2624 } 2625 } 2626 }); 2627 } 2628 } 2629 } 2630 } 2631 2632 private Drawable loadImageURI(Uri uri) { 2633 try { 2634 return Drawable.createFromStream( 2635 getContext().getContentResolver().openInputStream(uri), null); 2636 } catch (Exception e) { 2637 Log.w(TAG, "Unable to open content: " + uri); 2638 } 2639 return null; 2640 } 2641 2642 private DrawableFeatureState getDrawableState(int featureId, boolean required) { 2643 if ((getFeatures() & (1 << featureId)) == 0) { 2644 if (!required) { 2645 return null; 2646 } 2647 throw new RuntimeException("The feature has not been requested"); 2648 } 2649 2650 DrawableFeatureState[] ar; 2651 if ((ar = mDrawables) == null || ar.length <= featureId) { 2652 DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1]; 2653 if (ar != null) { 2654 System.arraycopy(ar, 0, nar, 0, ar.length); 2655 } 2656 mDrawables = ar = nar; 2657 } 2658 2659 DrawableFeatureState st = ar[featureId]; 2660 if (st == null) { 2661 ar[featureId] = st = new DrawableFeatureState(featureId); 2662 } 2663 return st; 2664 } 2665 2666 /** 2667 * Gets a panel's state based on its feature ID. 2668 * 2669 * @param featureId The feature ID of the panel. 2670 * @param required Whether the panel is required (if it is required and it 2671 * isn't in our features, this throws an exception). 2672 * @return The panel state. 2673 */ 2674 private PanelFeatureState getPanelState(int featureId, boolean required) { 2675 return getPanelState(featureId, required, null); 2676 } 2677 2678 /** 2679 * Gets a panel's state based on its feature ID. 2680 * 2681 * @param featureId The feature ID of the panel. 2682 * @param required Whether the panel is required (if it is required and it 2683 * isn't in our features, this throws an exception). 2684 * @param convertPanelState Optional: If the panel state does not exist, use 2685 * this as the panel state. 2686 * @return The panel state. 2687 */ 2688 private PanelFeatureState getPanelState(int featureId, boolean required, 2689 PanelFeatureState convertPanelState) { 2690 if ((getFeatures() & (1 << featureId)) == 0) { 2691 if (!required) { 2692 return null; 2693 } 2694 throw new RuntimeException("The feature has not been requested"); 2695 } 2696 2697 PanelFeatureState[] ar; 2698 if ((ar = mPanels) == null || ar.length <= featureId) { 2699 PanelFeatureState[] nar = new PanelFeatureState[featureId + 1]; 2700 if (ar != null) { 2701 System.arraycopy(ar, 0, nar, 0, ar.length); 2702 } 2703 mPanels = ar = nar; 2704 } 2705 2706 PanelFeatureState st = ar[featureId]; 2707 if (st == null) { 2708 ar[featureId] = st = (convertPanelState != null) 2709 ? convertPanelState 2710 : new PanelFeatureState(featureId); 2711 } 2712 return st; 2713 } 2714 2715 @Override 2716 public final void setChildDrawable(int featureId, Drawable drawable) { 2717 DrawableFeatureState st = getDrawableState(featureId, true); 2718 st.child = drawable; 2719 updateDrawable(featureId, st, false); 2720 } 2721 2722 @Override 2723 public final void setChildInt(int featureId, int value) { 2724 updateInt(featureId, value, false); 2725 } 2726 2727 @Override 2728 public boolean isShortcutKey(int keyCode, KeyEvent event) { 2729 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 2730 return st.menu != null && st.menu.isShortcutKey(keyCode, event); 2731 } 2732 2733 private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) { 2734 // Do nothing if the decor is not yet installed... an update will 2735 // need to be forced when we eventually become active. 2736 if (mContentParent == null) { 2737 return; 2738 } 2739 2740 final int featureMask = 1 << featureId; 2741 2742 if ((getFeatures() & featureMask) == 0 && !fromResume) { 2743 return; 2744 } 2745 2746 Drawable drawable = null; 2747 if (st != null) { 2748 drawable = st.child; 2749 if (drawable == null) 2750 drawable = st.local; 2751 if (drawable == null) 2752 drawable = st.def; 2753 } 2754 if ((getLocalFeatures() & featureMask) == 0) { 2755 if (getContainer() != null) { 2756 if (isActive() || fromResume) { 2757 getContainer().setChildDrawable(featureId, drawable); 2758 } 2759 } 2760 } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) { 2761 // System.out.println("Drawable changed: old=" + st.cur 2762 // + ", new=" + drawable); 2763 st.cur = drawable; 2764 st.curAlpha = st.alpha; 2765 onDrawableChanged(featureId, drawable, st.alpha); 2766 } 2767 } 2768 2769 private void updateInt(int featureId, int value, boolean fromResume) { 2770 2771 // Do nothing if the decor is not yet installed... an update will 2772 // need to be forced when we eventually become active. 2773 if (mContentParent == null) { 2774 return; 2775 } 2776 2777 final int featureMask = 1 << featureId; 2778 2779 if ((getFeatures() & featureMask) == 0 && !fromResume) { 2780 return; 2781 } 2782 2783 if ((getLocalFeatures() & featureMask) == 0) { 2784 if (getContainer() != null) { 2785 getContainer().setChildInt(featureId, value); 2786 } 2787 } else { 2788 onIntChanged(featureId, value); 2789 } 2790 } 2791 2792 private ImageView getLeftIconView() { 2793 if (mLeftIconView != null) { 2794 return mLeftIconView; 2795 } 2796 if (mContentParent == null) { 2797 installDecor(); 2798 } 2799 return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon)); 2800 } 2801 2802 private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) { 2803 if (mCircularProgressBar != null) { 2804 return mCircularProgressBar; 2805 } 2806 if (mContentParent == null && shouldInstallDecor) { 2807 installDecor(); 2808 } 2809 mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular); 2810 if (mCircularProgressBar != null) { 2811 mCircularProgressBar.setVisibility(View.INVISIBLE); 2812 } 2813 return mCircularProgressBar; 2814 } 2815 2816 private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) { 2817 if (mHorizontalProgressBar != null) { 2818 return mHorizontalProgressBar; 2819 } 2820 if (mContentParent == null && shouldInstallDecor) { 2821 installDecor(); 2822 } 2823 mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal); 2824 if (mHorizontalProgressBar != null) { 2825 mHorizontalProgressBar.setVisibility(View.INVISIBLE); 2826 } 2827 return mHorizontalProgressBar; 2828 } 2829 2830 private ImageView getRightIconView() { 2831 if (mRightIconView != null) { 2832 return mRightIconView; 2833 } 2834 if (mContentParent == null) { 2835 installDecor(); 2836 } 2837 return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon)); 2838 } 2839 2840 /** 2841 * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)} 2842 * callback. This method will grab whatever extra state is needed for the 2843 * callback that isn't given in the parameters. If the panel is not open, 2844 * this will not perform the callback. 2845 * 2846 * @param featureId Feature ID of the panel that was closed. Must be given. 2847 * @param panel Panel that was closed. Optional but useful if there is no 2848 * menu given. 2849 * @param menu The menu that was closed. Optional, but give if you have. 2850 */ 2851 private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) { 2852 final Callback cb = getCallback(); 2853 if (cb == null) 2854 return; 2855 2856 // Try to get a menu 2857 if (menu == null) { 2858 // Need a panel to grab the menu, so try to get that 2859 if (panel == null) { 2860 if ((featureId >= 0) && (featureId < mPanels.length)) { 2861 panel = mPanels[featureId]; 2862 } 2863 } 2864 2865 if (panel != null) { 2866 // menu still may be null, which is okay--we tried our best 2867 menu = panel.menu; 2868 } 2869 } 2870 2871 // If the panel is not open, do not callback 2872 if ((panel != null) && (!panel.isOpen)) 2873 return; 2874 2875 if (!isDestroyed()) { 2876 cb.onPanelClosed(featureId, menu); 2877 } 2878 } 2879 2880 /** 2881 * Helper method for adding launch-search to most applications. Opens the 2882 * search window using default settings. 2883 * 2884 * @return true if search window opened 2885 */ 2886 private boolean launchDefaultSearch() { 2887 final Callback cb = getCallback(); 2888 if (cb == null || isDestroyed()) { 2889 return false; 2890 } else { 2891 sendCloseSystemWindows("search"); 2892 return cb.onSearchRequested(); 2893 } 2894 } 2895 2896 @Override 2897 public void setVolumeControlStream(int streamType) { 2898 mVolumeControlStreamType = streamType; 2899 } 2900 2901 @Override 2902 public int getVolumeControlStream() { 2903 return mVolumeControlStreamType; 2904 } 2905 2906 private static final class DrawableFeatureState { 2907 DrawableFeatureState(int _featureId) { 2908 featureId = _featureId; 2909 } 2910 2911 final int featureId; 2912 2913 int resid; 2914 2915 Uri uri; 2916 2917 Drawable local; 2918 2919 Drawable child; 2920 2921 Drawable def; 2922 2923 Drawable cur; 2924 2925 int alpha = 255; 2926 2927 int curAlpha = 255; 2928 } 2929 2930 private static final class PanelFeatureState { 2931 2932 /** Feature ID for this panel. */ 2933 int featureId; 2934 2935 // Information pulled from the style for this panel. 2936 2937 int background; 2938 2939 /** The background when the panel spans the entire available width. */ 2940 int fullBackground; 2941 2942 int gravity; 2943 2944 int x; 2945 2946 int y; 2947 2948 int windowAnimations; 2949 2950 /** Dynamic state of the panel. */ 2951 DecorView decorView; 2952 2953 /** The panel that was returned by onCreatePanelView(). */ 2954 View createdPanelView; 2955 2956 /** The panel that we are actually showing. */ 2957 View shownPanelView; 2958 2959 /** Use {@link #setMenu} to set this. */ 2960 MenuBuilder menu; 2961 2962 IconMenuPresenter iconMenuPresenter; 2963 ListMenuPresenter expandedMenuPresenter; 2964 2965 /** 2966 * Whether the panel has been prepared (see 2967 * {@link PhoneWindow#preparePanel}). 2968 */ 2969 boolean isPrepared; 2970 2971 /** 2972 * Whether an item's action has been performed. This happens in obvious 2973 * scenarios (user clicks on menu item), but can also happen with 2974 * chording menu+(shortcut key). 2975 */ 2976 boolean isHandled; 2977 2978 boolean isOpen; 2979 2980 /** 2981 * True if the menu is in expanded mode, false if the menu is in icon 2982 * mode 2983 */ 2984 boolean isInExpandedMode; 2985 2986 public boolean qwertyMode; 2987 2988 boolean refreshDecorView; 2989 2990 boolean refreshMenuContent; 2991 2992 boolean wasLastOpen; 2993 2994 boolean wasLastExpanded; 2995 2996 /** 2997 * Contains the state of the menu when told to freeze. 2998 */ 2999 Bundle frozenMenuState; 3000 3001 PanelFeatureState(int featureId) { 3002 this.featureId = featureId; 3003 3004 refreshDecorView = false; 3005 } 3006 3007 public boolean hasPanelItems() { 3008 if (shownPanelView == null) return false; 3009 3010 if (isInExpandedMode) { 3011 return expandedMenuPresenter.getAdapter().getCount() > 0; 3012 } else { 3013 return ((ViewGroup) shownPanelView).getChildCount() > 0; 3014 } 3015 } 3016 3017 /** 3018 * Unregister and free attached MenuPresenters. They will be recreated as needed. 3019 */ 3020 public void clearMenuPresenters() { 3021 if (menu != null) { 3022 menu.removeMenuPresenter(iconMenuPresenter); 3023 menu.removeMenuPresenter(expandedMenuPresenter); 3024 } 3025 iconMenuPresenter = null; 3026 expandedMenuPresenter = null; 3027 } 3028 3029 void setStyle(Context context) { 3030 TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme); 3031 background = a.getResourceId( 3032 com.android.internal.R.styleable.Theme_panelBackground, 0); 3033 fullBackground = a.getResourceId( 3034 com.android.internal.R.styleable.Theme_panelFullBackground, 0); 3035 windowAnimations = a.getResourceId( 3036 com.android.internal.R.styleable.Theme_windowAnimationStyle, 0); 3037 a.recycle(); 3038 } 3039 3040 void setMenu(MenuBuilder menu) { 3041 this.menu = menu; 3042 } 3043 3044 MenuView getExpandedMenuView(MenuPresenter.Callback cb) { 3045 if (menu == null) return null; 3046 3047 getIconMenuView(cb); // Need this initialized to know where our offset goes 3048 3049 boolean init = false; 3050 if (expandedMenuPresenter == null) { 3051 expandedMenuPresenter = new ListMenuPresenter( 3052 com.android.internal.R.layout.list_menu_item_layout, 3053 com.android.internal.R.style.Theme_ExpandedMenu); 3054 expandedMenuPresenter.setCallback(cb); 3055 menu.addMenuPresenter(expandedMenuPresenter); 3056 init = true; 3057 } 3058 3059 expandedMenuPresenter.setItemIndexOffset(iconMenuPresenter.getNumActualItemsShown()); 3060 MenuView result = expandedMenuPresenter.getMenuView(decorView); 3061 3062 if (init && frozenMenuState != null) { 3063 expandedMenuPresenter.restoreHierarchyState(frozenMenuState); 3064 // Once we initialize the expanded menu we're done with the frozen state 3065 // since we will have also restored any icon menu state. 3066 frozenMenuState = null; 3067 } 3068 3069 return result; 3070 } 3071 3072 MenuView getIconMenuView(MenuPresenter.Callback cb) { 3073 if (menu == null) return null; 3074 3075 boolean init = false; 3076 if (iconMenuPresenter == null) { 3077 iconMenuPresenter = new IconMenuPresenter(); 3078 iconMenuPresenter.setCallback(cb); 3079 menu.addMenuPresenter(iconMenuPresenter); 3080 init = true; 3081 } 3082 3083 MenuView result = iconMenuPresenter.getMenuView(decorView); 3084 3085 if (init && frozenMenuState != null) { 3086 iconMenuPresenter.restoreHierarchyState(frozenMenuState); 3087 } 3088 3089 return result; 3090 } 3091 3092 Parcelable onSaveInstanceState() { 3093 SavedState savedState = new SavedState(); 3094 savedState.featureId = featureId; 3095 savedState.isOpen = isOpen; 3096 savedState.isInExpandedMode = isInExpandedMode; 3097 3098 if (menu != null) { 3099 savedState.menuState = new Bundle(); 3100 if (iconMenuPresenter != null) { 3101 iconMenuPresenter.saveHierarchyState(savedState.menuState); 3102 } 3103 if (expandedMenuPresenter != null) { 3104 expandedMenuPresenter.saveHierarchyState(savedState.menuState); 3105 } 3106 } 3107 3108 return savedState; 3109 } 3110 3111 void onRestoreInstanceState(Parcelable state) { 3112 SavedState savedState = (SavedState) state; 3113 featureId = savedState.featureId; 3114 wasLastOpen = savedState.isOpen; 3115 wasLastExpanded = savedState.isInExpandedMode; 3116 frozenMenuState = savedState.menuState; 3117 3118 /* 3119 * A LocalActivityManager keeps the same instance of this class around. 3120 * The first time the menu is being shown after restoring, the 3121 * Activity.onCreateOptionsMenu should be called. But, if it is the 3122 * same instance then menu != null and we won't call that method. 3123 * We clear any cached views here. The caller should invalidatePanelMenu. 3124 */ 3125 createdPanelView = null; 3126 shownPanelView = null; 3127 decorView = null; 3128 } 3129 3130 private static class SavedState implements Parcelable { 3131 int featureId; 3132 boolean isOpen; 3133 boolean isInExpandedMode; 3134 Bundle menuState; 3135 3136 public int describeContents() { 3137 return 0; 3138 } 3139 3140 public void writeToParcel(Parcel dest, int flags) { 3141 dest.writeInt(featureId); 3142 dest.writeInt(isOpen ? 1 : 0); 3143 dest.writeInt(isInExpandedMode ? 1 : 0); 3144 3145 if (isOpen) { 3146 dest.writeBundle(menuState); 3147 } 3148 } 3149 3150 private static SavedState readFromParcel(Parcel source) { 3151 SavedState savedState = new SavedState(); 3152 savedState.featureId = source.readInt(); 3153 savedState.isOpen = source.readInt() == 1; 3154 savedState.isInExpandedMode = source.readInt() == 1; 3155 3156 if (savedState.isOpen) { 3157 savedState.menuState = source.readBundle(); 3158 } 3159 3160 return savedState; 3161 } 3162 3163 public static final Parcelable.Creator<SavedState> CREATOR 3164 = new Parcelable.Creator<SavedState>() { 3165 public SavedState createFromParcel(Parcel in) { 3166 return readFromParcel(in); 3167 } 3168 3169 public SavedState[] newArray(int size) { 3170 return new SavedState[size]; 3171 } 3172 }; 3173 } 3174 3175 } 3176 3177 /** 3178 * Simple implementation of MenuBuilder.Callback that: 3179 * <li> Opens a submenu when selected. 3180 * <li> Calls back to the callback's onMenuItemSelected when an item is 3181 * selected. 3182 */ 3183 private final class DialogMenuCallback implements MenuBuilder.Callback, MenuPresenter.Callback { 3184 private int mFeatureId; 3185 private MenuDialogHelper mSubMenuHelper; 3186 3187 public DialogMenuCallback(int featureId) { 3188 mFeatureId = featureId; 3189 } 3190 3191 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 3192 if (menu.getRootMenu() != menu) { 3193 onCloseSubMenu(menu); 3194 } 3195 3196 if (allMenusAreClosing) { 3197 Callback callback = getCallback(); 3198 if (callback != null && !isDestroyed()) { 3199 callback.onPanelClosed(mFeatureId, menu); 3200 } 3201 3202 if (menu == mContextMenu) { 3203 dismissContextMenu(); 3204 } 3205 3206 // Dismiss the submenu, if it is showing 3207 if (mSubMenuHelper != null) { 3208 mSubMenuHelper.dismiss(); 3209 mSubMenuHelper = null; 3210 } 3211 } 3212 } 3213 3214 public void onCloseSubMenu(MenuBuilder menu) { 3215 Callback callback = getCallback(); 3216 if (callback != null && !isDestroyed()) { 3217 callback.onPanelClosed(mFeatureId, menu.getRootMenu()); 3218 } 3219 } 3220 3221 public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { 3222 Callback callback = getCallback(); 3223 return (callback != null && !isDestroyed()) 3224 && callback.onMenuItemSelected(mFeatureId, item); 3225 } 3226 3227 public void onMenuModeChange(MenuBuilder menu) { 3228 } 3229 3230 public boolean onOpenSubMenu(MenuBuilder subMenu) { 3231 // Set a simple callback for the submenu 3232 subMenu.setCallback(this); 3233 3234 // The window manager will give us a valid window token 3235 mSubMenuHelper = new MenuDialogHelper(subMenu); 3236 mSubMenuHelper.show(null); 3237 3238 return true; 3239 } 3240 } 3241 3242 void sendCloseSystemWindows() { 3243 PhoneWindowManager.sendCloseSystemWindows(getContext(), null); 3244 } 3245 3246 void sendCloseSystemWindows(String reason) { 3247 PhoneWindowManager.sendCloseSystemWindows(getContext(), reason); 3248 } 3249} 3250