PhoneWindow.java revision 0d8ec1d739e15c232c58a5a5de605685830c287e
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 if (st.decorView == null || st.refreshDecorView) { 502 if (st.decorView == null) { 503 // Initialize the panel decor, this will populate st.decorView 504 if (!initializePanelDecor(st) || (st.decorView == null)) 505 return; 506 } else if (st.refreshDecorView && (st.decorView.getChildCount() > 0)) { 507 // Decor needs refreshing, so remove its views 508 st.decorView.removeAllViews(); 509 } 510 511 // This will populate st.shownPanelView 512 if (!initializePanelContent(st) || !st.hasPanelItems()) { 513 return; 514 } 515 516 ViewGroup.LayoutParams lp = st.shownPanelView.getLayoutParams(); 517 if (lp == null) { 518 lp = new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT); 519 } 520 521 int backgroundResId; 522 if (lp.width == ViewGroup.LayoutParams.MATCH_PARENT) { 523 // If the contents is fill parent for the width, set the 524 // corresponding background 525 backgroundResId = st.fullBackground; 526 } else { 527 // Otherwise, set the normal panel background 528 backgroundResId = st.background; 529 } 530 st.decorView.setWindowBackground(getContext().getResources().getDrawable( 531 backgroundResId)); 532 533 534 st.decorView.addView(st.shownPanelView, lp); 535 536 /* 537 * Give focus to the view, if it or one of its children does not 538 * already have it. 539 */ 540 if (!st.shownPanelView.hasFocus()) { 541 st.shownPanelView.requestFocus(); 542 } 543 } 544 545 st.isOpen = true; 546 st.isHandled = false; 547 548 WindowManager.LayoutParams lp = new WindowManager.LayoutParams( 549 WRAP_CONTENT, WRAP_CONTENT, 550 st.x, st.y, WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG, 551 WindowManager.LayoutParams.FLAG_DITHER 552 | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM 553 | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH, 554 st.decorView.mDefaultOpacity); 555 556 lp.gravity = st.gravity; 557 lp.windowAnimations = st.windowAnimations; 558 559 wm.addView(st.decorView, lp); 560 // Log.v(TAG, "Adding main menu to window manager."); 561 } 562 563 @Override 564 public final void closePanel(int featureId) { 565 if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null && 566 mActionBar.isOverflowReserved()) { 567 mActionBar.hideOverflowMenu(); 568 } else if (featureId == FEATURE_CONTEXT_MENU) { 569 closeContextMenu(); 570 } else { 571 closePanel(getPanelState(featureId, true), true); 572 } 573 } 574 575 /** 576 * Closes the given panel. 577 * 578 * @param st The panel to be closed. 579 * @param doCallback Whether to notify the callback that the panel was 580 * closed. If the panel is in the process of re-opening or 581 * opening another panel (e.g., menu opening a sub menu), the 582 * callback should not happen and this variable should be false. 583 * In addition, this method internally will only perform the 584 * callback if the panel is open. 585 */ 586 public final void closePanel(PanelFeatureState st, boolean doCallback) { 587 // System.out.println("Close panel: isOpen=" + st.isOpen); 588 if (doCallback && st.featureId == FEATURE_OPTIONS_PANEL && 589 mActionBar != null && mActionBar.isOverflowMenuShowing()) { 590 checkCloseActionMenu(st.menu); 591 return; 592 } 593 594 final ViewManager wm = getWindowManager(); 595 if ((wm != null) && st.isOpen) { 596 if (st.decorView != null) { 597 wm.removeView(st.decorView); 598 // Log.v(TAG, "Removing main menu from window manager."); 599 } 600 601 if (doCallback) { 602 callOnPanelClosed(st.featureId, st, null); 603 } 604 } 605 606 st.isPrepared = false; 607 st.isHandled = false; 608 st.isOpen = false; 609 610 // This view is no longer shown, so null it out 611 st.shownPanelView = null; 612 613 if (st.isInExpandedMode) { 614 // Next time the menu opens, it should not be in expanded mode, so 615 // force a refresh of the decor 616 st.refreshDecorView = true; 617 st.isInExpandedMode = false; 618 } 619 620 if (mPreparedPanel == st) { 621 mPreparedPanel = null; 622 mPanelChordingKey = 0; 623 } 624 } 625 626 void checkCloseActionMenu(Menu menu) { 627 if (mClosingActionMenu) { 628 return; 629 } 630 631 mClosingActionMenu = true; 632 mActionBar.dismissPopupMenus(); 633 Callback cb = getCallback(); 634 if (cb != null && !isDestroyed()) { 635 cb.onPanelClosed(FEATURE_ACTION_BAR, menu); 636 } 637 mClosingActionMenu = false; 638 } 639 640 @Override 641 public final void togglePanel(int featureId, KeyEvent event) { 642 PanelFeatureState st = getPanelState(featureId, true); 643 if (st.isOpen) { 644 closePanel(st, true); 645 } else { 646 openPanel(st, event); 647 } 648 } 649 650 @Override 651 public void invalidatePanelMenu(int featureId) { 652 PanelFeatureState st = getPanelState(featureId, true); 653 if (st.menu != null) { 654 st.menu.clear(); 655 } 656 st.refreshMenuContent = true; 657 st.refreshDecorView = true; 658 659 // Prepare the options panel if we have an action bar 660 if ((featureId == FEATURE_ACTION_BAR || featureId == FEATURE_OPTIONS_PANEL) 661 && mActionBar != null) { 662 st = getPanelState(Window.FEATURE_OPTIONS_PANEL, false); 663 if (st != null) { 664 st.isPrepared = false; 665 preparePanel(st, null); 666 } 667 } 668 } 669 670 /** 671 * Called when the panel key is pushed down. 672 * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}. 673 * @param event The key event. 674 * @return Whether the key was handled. 675 */ 676 public final boolean onKeyDownPanel(int featureId, KeyEvent event) { 677 final int keyCode = event.getKeyCode(); 678 679 if (event.getRepeatCount() == 0) { 680 // The panel key was pushed, so set the chording key 681 mPanelChordingKey = keyCode; 682 683 PanelFeatureState st = getPanelState(featureId, true); 684 if (!st.isOpen) { 685 return preparePanel(st, event); 686 } 687 } 688 689 return false; 690 } 691 692 /** 693 * Called when the panel key is released. 694 * @param featureId The feature ID of the relevant panel (defaults to FEATURE_OPTIONS_PANEL}. 695 * @param event The key event. 696 */ 697 public final void onKeyUpPanel(int featureId, KeyEvent event) { 698 // The panel key was released, so clear the chording key 699 if (mPanelChordingKey != 0) { 700 mPanelChordingKey = 0; 701 702 if (event.isCanceled()) { 703 return; 704 } 705 706 boolean playSoundEffect = false; 707 final PanelFeatureState st = getPanelState(featureId, true); 708 if (featureId == FEATURE_OPTIONS_PANEL && mActionBar != null && 709 mActionBar.isOverflowReserved()) { 710 if (mActionBar.getVisibility() == View.VISIBLE) { 711 if (!mActionBar.isOverflowMenuShowing()) { 712 final Callback cb = getCallback(); 713 if (cb != null && !isDestroyed() && 714 cb.onPreparePanel(featureId, st.createdPanelView, st.menu)) { 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 outState.putBoolean(ACTION_BAR_TAG, mActionBar.isOverflowMenuShowing()); 1450 } 1451 1452 return outState; 1453 } 1454 1455 /** {@inheritDoc} */ 1456 @Override 1457 public void restoreHierarchyState(Bundle savedInstanceState) { 1458 if (mContentParent == null) { 1459 return; 1460 } 1461 1462 SparseArray<Parcelable> savedStates 1463 = savedInstanceState.getSparseParcelableArray(VIEWS_TAG); 1464 if (savedStates != null) { 1465 mContentParent.restoreHierarchyState(savedStates); 1466 } 1467 1468 // restore the focused view 1469 int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID); 1470 if (focusedViewId != View.NO_ID) { 1471 View needsFocus = mContentParent.findViewById(focusedViewId); 1472 if (needsFocus != null) { 1473 needsFocus.requestFocus(); 1474 } else { 1475 Log.w(TAG, 1476 "Previously focused view reported id " + focusedViewId 1477 + " during save, but can't be found during restore."); 1478 } 1479 } 1480 1481 // restore the panels 1482 SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG); 1483 if (panelStates != null) { 1484 restorePanelState(panelStates); 1485 } 1486 1487 if (mActionBar != null && savedInstanceState.getBoolean(ACTION_BAR_TAG)) { 1488 mActionBar.postShowOverflowMenu(); 1489 } 1490 } 1491 1492 /** 1493 * Invoked when the panels should freeze their state. 1494 * 1495 * @param icicles Save state into this. This is usually indexed by the 1496 * featureId. This will be given to {@link #restorePanelState} in the 1497 * future. 1498 */ 1499 private void savePanelState(SparseArray<Parcelable> icicles) { 1500 PanelFeatureState[] panels = mPanels; 1501 if (panels == null) { 1502 return; 1503 } 1504 1505 for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) { 1506 if (panels[curFeatureId] != null) { 1507 icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState()); 1508 } 1509 } 1510 } 1511 1512 /** 1513 * Invoked when the panels should thaw their state from a previously frozen state. 1514 * 1515 * @param icicles The state saved by {@link #savePanelState} that needs to be thawed. 1516 */ 1517 private void restorePanelState(SparseArray<Parcelable> icicles) { 1518 PanelFeatureState st; 1519 for (int curFeatureId = icicles.size() - 1; curFeatureId >= 0; curFeatureId--) { 1520 st = getPanelState(curFeatureId, false /* required */); 1521 if (st == null) { 1522 // The panel must not have been required, and is currently not around, skip it 1523 continue; 1524 } 1525 1526 st.onRestoreInstanceState(icicles.get(curFeatureId)); 1527 } 1528 1529 /* 1530 * Implementation note: call openPanelsAfterRestore later to actually open the 1531 * restored panels. 1532 */ 1533 } 1534 1535 /** 1536 * Opens the panels that have had their state restored. This should be 1537 * called sometime after {@link #restorePanelState} when it is safe to add 1538 * to the window manager. 1539 */ 1540 private void openPanelsAfterRestore() { 1541 PanelFeatureState[] panels = mPanels; 1542 1543 if (panels == null) { 1544 return; 1545 } 1546 1547 PanelFeatureState st; 1548 for (int i = panels.length - 1; i >= 0; i--) { 1549 st = panels[i]; 1550 // We restore the panel if it was last open; we skip it if it 1551 // now is open, to avoid a race condition if the user immediately 1552 // opens it when we are resuming. 1553 if ((st != null) && !st.isOpen && st.wasLastOpen) { 1554 st.isInExpandedMode = st.wasLastExpanded; 1555 openPanel(st, null); 1556 } 1557 } 1558 } 1559 1560 private class PanelMenuPresenterCallback implements MenuPresenter.Callback { 1561 @Override 1562 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 1563 final Menu parentMenu = menu.getRootMenu(); 1564 final boolean isSubMenu = parentMenu != menu; 1565 final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu); 1566 if (panel != null) { 1567 if (isSubMenu) { 1568 callOnPanelClosed(panel.featureId, panel, parentMenu); 1569 closePanel(panel, true); 1570 } else { 1571 // Close the panel and only do the callback if the menu is being 1572 // closed completely, not if opening a sub menu 1573 closePanel(panel, allMenusAreClosing); 1574 } 1575 } 1576 } 1577 1578 @Override 1579 public boolean onOpenSubMenu(MenuBuilder subMenu) { 1580 if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) { 1581 Callback cb = getCallback(); 1582 if (cb != null && !isDestroyed()) { 1583 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 1584 } 1585 } 1586 1587 return true; 1588 } 1589 } 1590 1591 private final class ActionMenuPresenterCallback implements MenuPresenter.Callback { 1592 @Override 1593 public boolean onOpenSubMenu(MenuBuilder subMenu) { 1594 Callback cb = getCallback(); 1595 if (cb != null) { 1596 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 1597 return true; 1598 } 1599 return false; 1600 } 1601 1602 @Override 1603 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 1604 checkCloseActionMenu(menu); 1605 } 1606 } 1607 1608 private final class DecorView extends FrameLayout implements RootViewSurfaceTaker { 1609 /* package */int mDefaultOpacity = PixelFormat.OPAQUE; 1610 1611 /** The feature ID of the panel, or -1 if this is the application's DecorView */ 1612 private final int mFeatureId; 1613 1614 private final Rect mDrawingBounds = new Rect(); 1615 1616 private final Rect mBackgroundPadding = new Rect(); 1617 1618 private final Rect mFramePadding = new Rect(); 1619 1620 private final Rect mFrameOffsets = new Rect(); 1621 1622 private boolean mChanging; 1623 1624 private Drawable mMenuBackground; 1625 private boolean mWatchingForMenu; 1626 private int mDownY; 1627 1628 private ActionMode mActionMode; 1629 private ActionBarContextView mActionModeView; 1630 private PopupWindow mActionModePopup; 1631 private Runnable mShowActionModePopup; 1632 1633 public DecorView(Context context, int featureId) { 1634 super(context); 1635 mFeatureId = featureId; 1636 } 1637 1638 @Override 1639 public boolean dispatchKeyEvent(KeyEvent event) { 1640 final int keyCode = event.getKeyCode(); 1641 final int action = event.getAction(); 1642 final boolean isDown = action == KeyEvent.ACTION_DOWN; 1643 1644 if (isDown && (event.getRepeatCount() == 0)) { 1645 // First handle chording of panel key: if a panel key is held 1646 // but not released, try to execute a shortcut in it. 1647 if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) { 1648 boolean handled = dispatchKeyShortcutEvent(event); 1649 if (handled) { 1650 return true; 1651 } 1652 } 1653 1654 // If a panel is open, perform a shortcut on it without the 1655 // chorded panel key 1656 if ((mPreparedPanel != null) && mPreparedPanel.isOpen) { 1657 if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) { 1658 return true; 1659 } 1660 } 1661 } 1662 1663 // Back cancels action modes first. 1664 if (mActionMode != null && keyCode == KeyEvent.KEYCODE_BACK) { 1665 if (action == KeyEvent.ACTION_UP) { 1666 mActionMode.finish(); 1667 } 1668 return true; 1669 } 1670 1671 if (!isDestroyed()) { 1672 final Callback cb = getCallback(); 1673 final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event) 1674 : super.dispatchKeyEvent(event); 1675 if (handled) { 1676 return true; 1677 } 1678 } 1679 return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event) 1680 : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event); 1681 } 1682 1683 @Override 1684 public boolean dispatchKeyShortcutEvent(KeyEvent ev) { 1685 // Perform the shortcut (mPreparedPanel can be null since 1686 // global shortcuts (such as search) don't rely on a 1687 // prepared panel or menu). 1688 boolean handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev, 1689 Menu.FLAG_PERFORM_NO_CLOSE); 1690 if (handled) { 1691 if (mPreparedPanel != null) { 1692 mPreparedPanel.isHandled = true; 1693 } 1694 return true; 1695 } 1696 1697 // Shortcut not handled by the panel. Dispatch to the view hierarchy. 1698 final Callback cb = getCallback(); 1699 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchKeyShortcutEvent(ev) 1700 : super.dispatchKeyShortcutEvent(ev); 1701 } 1702 1703 @Override 1704 public boolean dispatchTouchEvent(MotionEvent ev) { 1705 final Callback cb = getCallback(); 1706 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) 1707 : super.dispatchTouchEvent(ev); 1708 } 1709 1710 @Override 1711 public boolean dispatchTrackballEvent(MotionEvent ev) { 1712 final Callback cb = getCallback(); 1713 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev) 1714 : super.dispatchTrackballEvent(ev); 1715 } 1716 1717 @Override 1718 public boolean dispatchGenericMotionEvent(MotionEvent ev) { 1719 final Callback cb = getCallback(); 1720 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev) 1721 : super.dispatchGenericMotionEvent(ev); 1722 } 1723 1724 public boolean superDispatchKeyEvent(KeyEvent event) { 1725 return super.dispatchKeyEvent(event); 1726 } 1727 1728 public boolean superDispatchKeyShortcutEvent(KeyEvent event) { 1729 return super.dispatchKeyShortcutEvent(event); 1730 } 1731 1732 public boolean superDispatchTouchEvent(MotionEvent event) { 1733 return super.dispatchTouchEvent(event); 1734 } 1735 1736 public boolean superDispatchTrackballEvent(MotionEvent event) { 1737 return super.dispatchTrackballEvent(event); 1738 } 1739 1740 public boolean superDispatchGenericMotionEvent(MotionEvent event) { 1741 return super.dispatchGenericMotionEvent(event); 1742 } 1743 1744 @Override 1745 public boolean onTouchEvent(MotionEvent event) { 1746 return onInterceptTouchEvent(event); 1747 } 1748 1749 private boolean isOutOfBounds(int x, int y) { 1750 return x < -5 || y < -5 || x > (getWidth() + 5) 1751 || y > (getHeight() + 5); 1752 } 1753 1754 @Override 1755 public boolean onInterceptTouchEvent(MotionEvent event) { 1756 int action = event.getAction(); 1757 if (mFeatureId >= 0) { 1758 if (action == MotionEvent.ACTION_DOWN) { 1759 int x = (int)event.getX(); 1760 int y = (int)event.getY(); 1761 if (isOutOfBounds(x, y)) { 1762 closePanel(mFeatureId); 1763 return true; 1764 } 1765 } 1766 } 1767 1768 if (!SWEEP_OPEN_MENU) { 1769 return false; 1770 } 1771 1772 if (mFeatureId >= 0) { 1773 if (action == MotionEvent.ACTION_DOWN) { 1774 Log.i(TAG, "Watchiing!"); 1775 mWatchingForMenu = true; 1776 mDownY = (int) event.getY(); 1777 return false; 1778 } 1779 1780 if (!mWatchingForMenu) { 1781 return false; 1782 } 1783 1784 int y = (int)event.getY(); 1785 if (action == MotionEvent.ACTION_MOVE) { 1786 if (y > (mDownY+30)) { 1787 Log.i(TAG, "Closing!"); 1788 closePanel(mFeatureId); 1789 mWatchingForMenu = false; 1790 return true; 1791 } 1792 } else if (action == MotionEvent.ACTION_UP) { 1793 mWatchingForMenu = false; 1794 } 1795 1796 return false; 1797 } 1798 1799 //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY() 1800 // + " (in " + getHeight() + ")"); 1801 1802 if (action == MotionEvent.ACTION_DOWN) { 1803 int y = (int)event.getY(); 1804 if (y >= (getHeight()-5) && !hasChildren()) { 1805 Log.i(TAG, "Watchiing!"); 1806 mWatchingForMenu = true; 1807 } 1808 return false; 1809 } 1810 1811 if (!mWatchingForMenu) { 1812 return false; 1813 } 1814 1815 int y = (int)event.getY(); 1816 if (action == MotionEvent.ACTION_MOVE) { 1817 if (y < (getHeight()-30)) { 1818 Log.i(TAG, "Opening!"); 1819 openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent( 1820 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)); 1821 mWatchingForMenu = false; 1822 return true; 1823 } 1824 } else if (action == MotionEvent.ACTION_UP) { 1825 mWatchingForMenu = false; 1826 } 1827 1828 return false; 1829 } 1830 1831 @Override 1832 public void sendAccessibilityEvent(int eventType) { 1833 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 1834 return; 1835 } 1836 1837 // if we are showing a feature that should be announced and one child 1838 // make this child the event source since this is the feature itself 1839 // otherwise the callback will take over and announce its client 1840 if ((mFeatureId == FEATURE_OPTIONS_PANEL || 1841 mFeatureId == FEATURE_CONTEXT_MENU || 1842 mFeatureId == FEATURE_PROGRESS || 1843 mFeatureId == FEATURE_INDETERMINATE_PROGRESS) 1844 && getChildCount() == 1) { 1845 getChildAt(0).sendAccessibilityEvent(eventType); 1846 } else { 1847 super.sendAccessibilityEvent(eventType); 1848 } 1849 } 1850 1851 @Override 1852 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 1853 final Callback cb = getCallback(); 1854 if (cb != null && !isDestroyed()) { 1855 if (cb.dispatchPopulateAccessibilityEvent(event)) { 1856 return true; 1857 } 1858 } 1859 return super.dispatchPopulateAccessibilityEvent(event); 1860 } 1861 1862 @Override 1863 protected boolean setFrame(int l, int t, int r, int b) { 1864 boolean changed = super.setFrame(l, t, r, b); 1865 if (changed) { 1866 final Rect drawingBounds = mDrawingBounds; 1867 getDrawingRect(drawingBounds); 1868 1869 Drawable fg = getForeground(); 1870 if (fg != null) { 1871 final Rect frameOffsets = mFrameOffsets; 1872 drawingBounds.left += frameOffsets.left; 1873 drawingBounds.top += frameOffsets.top; 1874 drawingBounds.right -= frameOffsets.right; 1875 drawingBounds.bottom -= frameOffsets.bottom; 1876 fg.setBounds(drawingBounds); 1877 final Rect framePadding = mFramePadding; 1878 drawingBounds.left += framePadding.left - frameOffsets.left; 1879 drawingBounds.top += framePadding.top - frameOffsets.top; 1880 drawingBounds.right -= framePadding.right - frameOffsets.right; 1881 drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom; 1882 } 1883 1884 Drawable bg = getBackground(); 1885 if (bg != null) { 1886 bg.setBounds(drawingBounds); 1887 } 1888 1889 if (SWEEP_OPEN_MENU) { 1890 if (mMenuBackground == null && mFeatureId < 0 1891 && getAttributes().height 1892 == WindowManager.LayoutParams.MATCH_PARENT) { 1893 mMenuBackground = getContext().getResources().getDrawable( 1894 com.android.internal.R.drawable.menu_background); 1895 } 1896 if (mMenuBackground != null) { 1897 mMenuBackground.setBounds(drawingBounds.left, 1898 drawingBounds.bottom-6, drawingBounds.right, 1899 drawingBounds.bottom+20); 1900 } 1901 } 1902 } 1903 return changed; 1904 } 1905 1906 @Override 1907 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 1908 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); 1909 final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; 1910 1911 final int widthMode = getMode(widthMeasureSpec); 1912 1913 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1914 1915 int width = getMeasuredWidth(); 1916 boolean measure = false; 1917 1918 widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); 1919 1920 final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; 1921 1922 if (widthMode == AT_MOST && tv.type != TypedValue.TYPE_NULL) { 1923 final int min; 1924 if (tv.type == TypedValue.TYPE_DIMENSION) { 1925 min = (int)tv.getDimension(metrics); 1926 } else if (tv.type == TypedValue.TYPE_FRACTION) { 1927 min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); 1928 } else { 1929 min = 0; 1930 } 1931 1932 if (width < min) { 1933 widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); 1934 measure = true; 1935 } 1936 } 1937 1938 // TODO: Support height? 1939 1940 if (measure) { 1941 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 1942 } 1943 } 1944 1945 @Override 1946 public void draw(Canvas canvas) { 1947 super.draw(canvas); 1948 1949 if (mMenuBackground != null) { 1950 mMenuBackground.draw(canvas); 1951 } 1952 } 1953 1954 1955 @Override 1956 public boolean showContextMenuForChild(View originalView) { 1957 // Reuse the context menu builder 1958 if (mContextMenu == null) { 1959 mContextMenu = new ContextMenuBuilder(getContext()); 1960 mContextMenu.setCallback(mContextMenuCallback); 1961 } else { 1962 mContextMenu.clearAll(); 1963 } 1964 1965 mContextMenuHelper = mContextMenu.show(originalView, originalView.getWindowToken()); 1966 return mContextMenuHelper != null; 1967 } 1968 1969 @Override 1970 public ActionMode startActionModeForChild(View originalView, 1971 ActionMode.Callback callback) { 1972 // originalView can be used here to be sure that we don't obscure 1973 // relevant content with the context mode UI. 1974 return startActionMode(callback); 1975 } 1976 1977 @Override 1978 public ActionMode startActionMode(ActionMode.Callback callback) { 1979 if (mActionMode != null) { 1980 mActionMode.finish(); 1981 } 1982 1983 final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback); 1984 ActionMode mode = null; 1985 if (getCallback() != null && !isDestroyed()) { 1986 try { 1987 mode = getCallback().onWindowStartingActionMode(wrappedCallback); 1988 } catch (AbstractMethodError ame) { 1989 // Older apps might not implement this callback method. 1990 } 1991 } 1992 if (mode != null) { 1993 mActionMode = mode; 1994 } else { 1995 if (mActionModeView == null) { 1996 if (hasFeature(FEATURE_ACTION_MODE_OVERLAY)) { 1997 mActionModeView = new ActionBarContextView(mContext); 1998 mActionModePopup = new PopupWindow(mContext, null, 1999 com.android.internal.R.attr.actionModePopupWindowStyle); 2000 mActionModePopup.setLayoutInScreenEnabled(true); 2001 mActionModePopup.setClippingEnabled(false); 2002 mActionModePopup.setContentView(mActionModeView); 2003 mActionModePopup.setWidth(MATCH_PARENT); 2004 2005 TypedValue heightValue = new TypedValue(); 2006 mContext.getTheme().resolveAttribute( 2007 com.android.internal.R.attr.actionBarSize, heightValue, false); 2008 final int height = TypedValue.complexToDimensionPixelSize(heightValue.data, 2009 mContext.getResources().getDisplayMetrics()); 2010 mActionModePopup.setHeight(height); 2011 mShowActionModePopup = new Runnable() { 2012 public void run() { 2013 mActionModePopup.showAtLocation(PhoneWindow.DecorView.this, 2014 Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0); 2015 } 2016 }; 2017 } else { 2018 ViewStub stub = (ViewStub) findViewById( 2019 com.android.internal.R.id.action_mode_bar_stub); 2020 if (stub != null) { 2021 mActionModeView = (ActionBarContextView) stub.inflate(); 2022 } 2023 } 2024 } 2025 2026 if (mActionModeView != null) { 2027 mActionModeView.killMode(); 2028 mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback); 2029 if (callback.onCreateActionMode(mode, mode.getMenu())) { 2030 mode.invalidate(); 2031 mActionModeView.initForMode(mode); 2032 mActionModeView.setVisibility(View.VISIBLE); 2033 mActionMode = mode; 2034 if (mActionModePopup != null) { 2035 post(mShowActionModePopup); 2036 } 2037 } else { 2038 mActionMode = null; 2039 } 2040 } 2041 } 2042 if (mActionMode != null && getCallback() != null && !isDestroyed()) { 2043 try { 2044 getCallback().onActionModeStarted(mActionMode); 2045 } catch (AbstractMethodError ame) { 2046 // Older apps might not implement this callback method. 2047 } 2048 } 2049 return mActionMode; 2050 } 2051 2052 public void startChanging() { 2053 mChanging = true; 2054 } 2055 2056 public void finishChanging() { 2057 mChanging = false; 2058 drawableChanged(); 2059 } 2060 2061 public void setWindowBackground(Drawable drawable) { 2062 if (getBackground() != drawable) { 2063 setBackgroundDrawable(drawable); 2064 if (drawable != null) { 2065 drawable.getPadding(mBackgroundPadding); 2066 } else { 2067 mBackgroundPadding.setEmpty(); 2068 } 2069 drawableChanged(); 2070 } 2071 } 2072 2073 @Override 2074 public void setBackgroundDrawable(Drawable d) { 2075 super.setBackgroundDrawable(d); 2076 if (getWindowToken() != null) { 2077 updateWindowResizeState(); 2078 } 2079 } 2080 2081 public void setWindowFrame(Drawable drawable) { 2082 if (getForeground() != drawable) { 2083 setForeground(drawable); 2084 if (drawable != null) { 2085 drawable.getPadding(mFramePadding); 2086 } else { 2087 mFramePadding.setEmpty(); 2088 } 2089 drawableChanged(); 2090 } 2091 } 2092 2093 @Override 2094 protected boolean fitSystemWindows(Rect insets) { 2095 mFrameOffsets.set(insets); 2096 if (getForeground() != null) { 2097 drawableChanged(); 2098 } 2099 return super.fitSystemWindows(insets); 2100 } 2101 2102 private void drawableChanged() { 2103 if (mChanging) { 2104 return; 2105 } 2106 2107 setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top 2108 + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right, 2109 mFramePadding.bottom + mBackgroundPadding.bottom); 2110 requestLayout(); 2111 invalidate(); 2112 2113 int opacity = PixelFormat.OPAQUE; 2114 2115 // Note: if there is no background, we will assume opaque. The 2116 // common case seems to be that an application sets there to be 2117 // no background so it can draw everything itself. For that, 2118 // we would like to assume OPAQUE and let the app force it to 2119 // the slower TRANSLUCENT mode if that is really what it wants. 2120 Drawable bg = getBackground(); 2121 Drawable fg = getForeground(); 2122 if (bg != null) { 2123 if (fg == null) { 2124 opacity = bg.getOpacity(); 2125 } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0 2126 && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) { 2127 // If the frame padding is zero, then we can be opaque 2128 // if either the frame -or- the background is opaque. 2129 int fop = fg.getOpacity(); 2130 int bop = bg.getOpacity(); 2131 if (false) 2132 Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop); 2133 if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) { 2134 opacity = PixelFormat.OPAQUE; 2135 } else if (fop == PixelFormat.UNKNOWN) { 2136 opacity = bop; 2137 } else if (bop == PixelFormat.UNKNOWN) { 2138 opacity = fop; 2139 } else { 2140 opacity = Drawable.resolveOpacity(fop, bop); 2141 } 2142 } else { 2143 // For now we have to assume translucent if there is a 2144 // frame with padding... there is no way to tell if the 2145 // frame and background together will draw all pixels. 2146 if (false) 2147 Log.v(TAG, "Padding: " + mFramePadding); 2148 opacity = PixelFormat.TRANSLUCENT; 2149 } 2150 } 2151 2152 if (false) 2153 Log.v(TAG, "Background: " + bg + ", Frame: " + fg); 2154 if (false) 2155 Log.v(TAG, "Selected default opacity: " + opacity); 2156 2157 mDefaultOpacity = opacity; 2158 if (mFeatureId < 0) { 2159 setDefaultWindowFormat(opacity); 2160 } 2161 } 2162 2163 @Override 2164 public void onWindowFocusChanged(boolean hasWindowFocus) { 2165 super.onWindowFocusChanged(hasWindowFocus); 2166 2167 // If the user is chording a menu shortcut, release the chord since 2168 // this window lost focus 2169 if (!hasWindowFocus && mPanelChordingKey != 0) { 2170 closePanel(FEATURE_OPTIONS_PANEL); 2171 } 2172 2173 final Callback cb = getCallback(); 2174 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2175 cb.onWindowFocusChanged(hasWindowFocus); 2176 } 2177 } 2178 2179 void updateWindowResizeState() { 2180 Drawable bg = getBackground(); 2181 hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity() 2182 != PixelFormat.OPAQUE); 2183 } 2184 2185 @Override 2186 protected void onAttachedToWindow() { 2187 super.onAttachedToWindow(); 2188 2189 updateWindowResizeState(); 2190 2191 final Callback cb = getCallback(); 2192 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2193 cb.onAttachedToWindow(); 2194 } 2195 2196 if (mFeatureId == -1) { 2197 /* 2198 * The main window has been attached, try to restore any panels 2199 * that may have been open before. This is called in cases where 2200 * an activity is being killed for configuration change and the 2201 * menu was open. When the activity is recreated, the menu 2202 * should be shown again. 2203 */ 2204 openPanelsAfterRestore(); 2205 } 2206 } 2207 2208 @Override 2209 protected void onDetachedFromWindow() { 2210 super.onDetachedFromWindow(); 2211 2212 final Callback cb = getCallback(); 2213 if (cb != null && mFeatureId < 0) { 2214 cb.onDetachedFromWindow(); 2215 } 2216 2217 if (mActionBar != null) { 2218 mActionBar.dismissPopupMenus(); 2219 } 2220 2221 if (mActionModePopup != null) { 2222 removeCallbacks(mShowActionModePopup); 2223 if (mActionModePopup.isShowing()) { 2224 mActionModePopup.dismiss(); 2225 } 2226 mActionModePopup = null; 2227 } 2228 } 2229 2230 @Override 2231 public void onCloseSystemDialogs(String reason) { 2232 if (mFeatureId >= 0) { 2233 closeAllPanels(); 2234 } 2235 } 2236 2237 public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() { 2238 return mFeatureId < 0 ? mTakeSurfaceCallback : null; 2239 } 2240 2241 public InputQueue.Callback willYouTakeTheInputQueue() { 2242 return mFeatureId < 0 ? mTakeInputQueueCallback : null; 2243 } 2244 2245 public void setSurfaceType(int type) { 2246 PhoneWindow.this.setType(type); 2247 } 2248 2249 public void setSurfaceFormat(int format) { 2250 PhoneWindow.this.setFormat(format); 2251 } 2252 2253 public void setSurfaceKeepScreenOn(boolean keepOn) { 2254 if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2255 else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 2256 } 2257 2258 /** 2259 * Clears out internal reference when the action mode is destroyed. 2260 */ 2261 private class ActionModeCallbackWrapper implements ActionMode.Callback { 2262 private ActionMode.Callback mWrapped; 2263 2264 public ActionModeCallbackWrapper(ActionMode.Callback wrapped) { 2265 mWrapped = wrapped; 2266 } 2267 2268 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 2269 return mWrapped.onCreateActionMode(mode, menu); 2270 } 2271 2272 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 2273 return mWrapped.onPrepareActionMode(mode, menu); 2274 } 2275 2276 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 2277 return mWrapped.onActionItemClicked(mode, item); 2278 } 2279 2280 public void onDestroyActionMode(ActionMode mode) { 2281 mWrapped.onDestroyActionMode(mode); 2282 if (mActionModePopup != null) { 2283 removeCallbacks(mShowActionModePopup); 2284 mActionModePopup.dismiss(); 2285 } else if (mActionModeView != null) { 2286 mActionModeView.setVisibility(GONE); 2287 } 2288 if (mActionModeView != null) { 2289 mActionModeView.removeAllViews(); 2290 } 2291 if (getCallback() != null && !isDestroyed()) { 2292 try { 2293 getCallback().onActionModeFinished(mActionMode); 2294 } catch (AbstractMethodError ame) { 2295 // Older apps might not implement this callback method. 2296 } 2297 } 2298 mActionMode = null; 2299 } 2300 } 2301 } 2302 2303 protected DecorView generateDecor() { 2304 return new DecorView(getContext(), -1); 2305 } 2306 2307 protected void setFeatureFromAttrs(int featureId, TypedArray attrs, 2308 int drawableAttr, int alphaAttr) { 2309 Drawable d = attrs.getDrawable(drawableAttr); 2310 if (d != null) { 2311 requestFeature(featureId); 2312 setFeatureDefaultDrawable(featureId, d); 2313 } 2314 if ((getFeatures() & (1 << featureId)) != 0) { 2315 int alpha = attrs.getInt(alphaAttr, -1); 2316 if (alpha >= 0) { 2317 setFeatureDrawableAlpha(featureId, alpha); 2318 } 2319 } 2320 } 2321 2322 protected ViewGroup generateLayout(DecorView decor) { 2323 // Apply data from current theme. 2324 2325 TypedArray a = getWindowStyle(); 2326 2327 if (false) { 2328 System.out.println("From style:"); 2329 String s = "Attrs:"; 2330 for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) { 2331 s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "=" 2332 + a.getString(i); 2333 } 2334 System.out.println(s); 2335 } 2336 2337 mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false); 2338 int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR) 2339 & (~getForcedWindowFlags()); 2340 if (mIsFloating) { 2341 setLayout(WRAP_CONTENT, WRAP_CONTENT); 2342 setFlags(0, flagsToUpdate); 2343 } else { 2344 setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate); 2345 } 2346 2347 if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) { 2348 requestFeature(FEATURE_NO_TITLE); 2349 } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) { 2350 // Don't allow an action bar if there is no title. 2351 requestFeature(FEATURE_ACTION_BAR); 2352 } 2353 2354 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) { 2355 requestFeature(FEATURE_ACTION_BAR_OVERLAY); 2356 } 2357 2358 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) { 2359 requestFeature(FEATURE_ACTION_MODE_OVERLAY); 2360 } 2361 2362 if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) { 2363 setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN&(~getForcedWindowFlags())); 2364 } 2365 2366 if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) { 2367 setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags())); 2368 } 2369 2370 if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch, 2371 getContext().getApplicationInfo().targetSdkVersion 2372 >= android.os.Build.VERSION_CODES.HONEYCOMB)) { 2373 setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags())); 2374 } 2375 2376 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor); 2377 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor); 2378 2379 if (getContext().getApplicationInfo().targetSdkVersion 2380 < android.os.Build.VERSION_CODES.HONEYCOMB) { 2381 addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY); 2382 } 2383 2384 if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion 2385 >= android.os.Build.VERSION_CODES.HONEYCOMB) { 2386 if (a.getBoolean( 2387 com.android.internal.R.styleable.Window_windowCloseOnTouchOutside, 2388 false)) { 2389 setCloseOnTouchOutsideIfNotSet(true); 2390 } 2391 } 2392 2393 WindowManager.LayoutParams params = getAttributes(); 2394 2395 if (!hasSoftInputMode()) { 2396 params.softInputMode = a.getInt( 2397 com.android.internal.R.styleable.Window_windowSoftInputMode, 2398 params.softInputMode); 2399 } 2400 2401 if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled, 2402 mIsFloating)) { 2403 /* All dialogs should have the window dimmed */ 2404 if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) { 2405 params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; 2406 } 2407 params.dimAmount = a.getFloat( 2408 android.R.styleable.Window_backgroundDimAmount, 0.5f); 2409 } 2410 2411 if (params.windowAnimations == 0) { 2412 params.windowAnimations = a.getResourceId( 2413 com.android.internal.R.styleable.Window_windowAnimationStyle, 0); 2414 } 2415 2416 // The rest are only done if this window is not embedded; otherwise, 2417 // the values are inherited from our container. 2418 if (getContainer() == null) { 2419 if (mBackgroundDrawable == null) { 2420 if (mBackgroundResource == 0) { 2421 mBackgroundResource = a.getResourceId( 2422 com.android.internal.R.styleable.Window_windowBackground, 0); 2423 } 2424 if (mFrameResource == 0) { 2425 mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0); 2426 } 2427 if (false) { 2428 System.out.println("Background: " 2429 + Integer.toHexString(mBackgroundResource) + " Frame: " 2430 + Integer.toHexString(mFrameResource)); 2431 } 2432 } 2433 mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000); 2434 } 2435 2436 // Inflate the window decor. 2437 2438 int layoutResource; 2439 int features = getLocalFeatures(); 2440 // System.out.println("Features: 0x" + Integer.toHexString(features)); 2441 if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) { 2442 if (mIsFloating) { 2443 TypedValue res = new TypedValue(); 2444 getContext().getTheme().resolveAttribute( 2445 com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true); 2446 layoutResource = res.resourceId; 2447 } else { 2448 layoutResource = com.android.internal.R.layout.screen_title_icons; 2449 } 2450 // XXX Remove this once action bar supports these features. 2451 removeFeature(FEATURE_ACTION_BAR); 2452 // System.out.println("Title Icons!"); 2453 } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0 2454 && (features & (1 << FEATURE_ACTION_BAR)) == 0) { 2455 // Special case for a window with only a progress bar (and title). 2456 // XXX Need to have a no-title version of embedded windows. 2457 layoutResource = com.android.internal.R.layout.screen_progress; 2458 // System.out.println("Progress!"); 2459 } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) { 2460 // Special case for a window with a custom title. 2461 // If the window is floating, we need a dialog layout 2462 if (mIsFloating) { 2463 TypedValue res = new TypedValue(); 2464 getContext().getTheme().resolveAttribute( 2465 com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true); 2466 layoutResource = res.resourceId; 2467 } else { 2468 layoutResource = com.android.internal.R.layout.screen_custom_title; 2469 } 2470 // XXX Remove this once action bar supports these features. 2471 removeFeature(FEATURE_ACTION_BAR); 2472 } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) { 2473 // If no other features and not embedded, only need a title. 2474 // If the window is floating, we need a dialog layout 2475 if (mIsFloating) { 2476 TypedValue res = new TypedValue(); 2477 getContext().getTheme().resolveAttribute( 2478 com.android.internal.R.attr.dialogTitleDecorLayout, res, true); 2479 layoutResource = res.resourceId; 2480 } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) { 2481 if ((features & (1 << FEATURE_ACTION_BAR_OVERLAY)) != 0) { 2482 layoutResource = com.android.internal.R.layout.screen_action_bar_overlay; 2483 } else { 2484 layoutResource = com.android.internal.R.layout.screen_action_bar; 2485 } 2486 } else { 2487 layoutResource = com.android.internal.R.layout.screen_title; 2488 } 2489 // System.out.println("Title!"); 2490 } else { 2491 // Embedded, so no decoration is needed. 2492 layoutResource = com.android.internal.R.layout.screen_simple; 2493 // System.out.println("Simple!"); 2494 } 2495 2496 mDecor.startChanging(); 2497 2498 View in = mLayoutInflater.inflate(layoutResource, null); 2499 decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 2500 2501 ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); 2502 if (contentParent == null) { 2503 throw new RuntimeException("Window couldn't find content container view"); 2504 } 2505 2506 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 2507 ProgressBar progress = getCircularProgressBar(false); 2508 if (progress != null) { 2509 progress.setIndeterminate(true); 2510 } 2511 } 2512 2513 // Remaining setup -- of background and title -- that only applies 2514 // to top-level windows. 2515 if (getContainer() == null) { 2516 Drawable drawable = mBackgroundDrawable; 2517 if (mBackgroundResource != 0) { 2518 drawable = getContext().getResources().getDrawable(mBackgroundResource); 2519 } 2520 mDecor.setWindowBackground(drawable); 2521 drawable = null; 2522 if (mFrameResource != 0) { 2523 drawable = getContext().getResources().getDrawable(mFrameResource); 2524 } 2525 mDecor.setWindowFrame(drawable); 2526 2527 // System.out.println("Text=" + Integer.toHexString(mTextColor) + 2528 // " Sel=" + Integer.toHexString(mTextSelectedColor) + 2529 // " Title=" + Integer.toHexString(mTitleColor)); 2530 2531 if (mTitleColor == 0) { 2532 mTitleColor = mTextColor; 2533 } 2534 2535 if (mTitle != null) { 2536 setTitle(mTitle); 2537 } 2538 setTitleColor(mTitleColor); 2539 } 2540 2541 mDecor.finishChanging(); 2542 2543 return contentParent; 2544 } 2545 2546 /** @hide */ 2547 public void alwaysReadCloseOnTouchAttr() { 2548 mAlwaysReadCloseOnTouchAttr = true; 2549 } 2550 2551 private void installDecor() { 2552 if (mDecor == null) { 2553 mDecor = generateDecor(); 2554 mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); 2555 mDecor.setIsRootNamespace(true); 2556 } 2557 if (mContentParent == null) { 2558 mContentParent = generateLayout(mDecor); 2559 2560 mTitleView = (TextView)findViewById(com.android.internal.R.id.title); 2561 if (mTitleView != null) { 2562 if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) { 2563 View titleContainer = findViewById(com.android.internal.R.id.title_container); 2564 if (titleContainer != null) { 2565 titleContainer.setVisibility(View.GONE); 2566 } else { 2567 mTitleView.setVisibility(View.GONE); 2568 } 2569 if (mContentParent instanceof FrameLayout) { 2570 ((FrameLayout)mContentParent).setForeground(null); 2571 } 2572 } else { 2573 mTitleView.setText(mTitle); 2574 } 2575 } else { 2576 mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar); 2577 if (mActionBar != null) { 2578 if (mActionBar.getTitle() == null) { 2579 mActionBar.setWindowTitle(mTitle); 2580 } 2581 final int localFeatures = getLocalFeatures(); 2582 if ((localFeatures & (1 << FEATURE_PROGRESS)) != 0) { 2583 mActionBar.initProgress(); 2584 } 2585 if ((localFeatures & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 2586 mActionBar.initIndeterminateProgress(); 2587 } 2588 2589 final boolean splitActionBar = getWindowStyle().getBoolean( 2590 com.android.internal.R.styleable.Window_windowSplitActionBar, false); 2591 if (splitActionBar) { 2592 final ActionBarContainer splitView = (ActionBarContainer) findViewById( 2593 com.android.internal.R.id.split_action_bar); 2594 if (splitView != null) { 2595 splitView.setVisibility(View.VISIBLE); 2596 mActionBar.setSplitActionBar(splitActionBar); 2597 mActionBar.setSplitView(splitView); 2598 2599 final ActionBarContextView cab = (ActionBarContextView) findViewById( 2600 com.android.internal.R.id.action_context_bar); 2601 cab.setSplitView(splitView); 2602 } else { 2603 Log.e(TAG, "Window style requested split action bar with " + 2604 "incompatible window decor! Ignoring request."); 2605 } 2606 } 2607 2608 // Post the panel invalidate for later; avoid application onCreateOptionsMenu 2609 // being called in the middle of onCreate or similar. 2610 mDecor.post(new Runnable() { 2611 public void run() { 2612 if (!isDestroyed()) { 2613 invalidatePanelMenu(FEATURE_ACTION_BAR); 2614 } 2615 } 2616 }); 2617 } 2618 } 2619 } 2620 } 2621 2622 private Drawable loadImageURI(Uri uri) { 2623 try { 2624 return Drawable.createFromStream( 2625 getContext().getContentResolver().openInputStream(uri), null); 2626 } catch (Exception e) { 2627 Log.w(TAG, "Unable to open content: " + uri); 2628 } 2629 return null; 2630 } 2631 2632 private DrawableFeatureState getDrawableState(int featureId, boolean required) { 2633 if ((getFeatures() & (1 << featureId)) == 0) { 2634 if (!required) { 2635 return null; 2636 } 2637 throw new RuntimeException("The feature has not been requested"); 2638 } 2639 2640 DrawableFeatureState[] ar; 2641 if ((ar = mDrawables) == null || ar.length <= featureId) { 2642 DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1]; 2643 if (ar != null) { 2644 System.arraycopy(ar, 0, nar, 0, ar.length); 2645 } 2646 mDrawables = ar = nar; 2647 } 2648 2649 DrawableFeatureState st = ar[featureId]; 2650 if (st == null) { 2651 ar[featureId] = st = new DrawableFeatureState(featureId); 2652 } 2653 return st; 2654 } 2655 2656 /** 2657 * Gets a panel's state based on its feature ID. 2658 * 2659 * @param featureId The feature ID of the panel. 2660 * @param required Whether the panel is required (if it is required and it 2661 * isn't in our features, this throws an exception). 2662 * @return The panel state. 2663 */ 2664 private PanelFeatureState getPanelState(int featureId, boolean required) { 2665 return getPanelState(featureId, required, null); 2666 } 2667 2668 /** 2669 * Gets a panel's state based on its feature ID. 2670 * 2671 * @param featureId The feature ID of the panel. 2672 * @param required Whether the panel is required (if it is required and it 2673 * isn't in our features, this throws an exception). 2674 * @param convertPanelState Optional: If the panel state does not exist, use 2675 * this as the panel state. 2676 * @return The panel state. 2677 */ 2678 private PanelFeatureState getPanelState(int featureId, boolean required, 2679 PanelFeatureState convertPanelState) { 2680 if ((getFeatures() & (1 << featureId)) == 0) { 2681 if (!required) { 2682 return null; 2683 } 2684 throw new RuntimeException("The feature has not been requested"); 2685 } 2686 2687 PanelFeatureState[] ar; 2688 if ((ar = mPanels) == null || ar.length <= featureId) { 2689 PanelFeatureState[] nar = new PanelFeatureState[featureId + 1]; 2690 if (ar != null) { 2691 System.arraycopy(ar, 0, nar, 0, ar.length); 2692 } 2693 mPanels = ar = nar; 2694 } 2695 2696 PanelFeatureState st = ar[featureId]; 2697 if (st == null) { 2698 ar[featureId] = st = (convertPanelState != null) 2699 ? convertPanelState 2700 : new PanelFeatureState(featureId); 2701 } 2702 return st; 2703 } 2704 2705 @Override 2706 public final void setChildDrawable(int featureId, Drawable drawable) { 2707 DrawableFeatureState st = getDrawableState(featureId, true); 2708 st.child = drawable; 2709 updateDrawable(featureId, st, false); 2710 } 2711 2712 @Override 2713 public final void setChildInt(int featureId, int value) { 2714 updateInt(featureId, value, false); 2715 } 2716 2717 @Override 2718 public boolean isShortcutKey(int keyCode, KeyEvent event) { 2719 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 2720 return st.menu != null && st.menu.isShortcutKey(keyCode, event); 2721 } 2722 2723 private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) { 2724 // Do nothing if the decor is not yet installed... an update will 2725 // need to be forced when we eventually become active. 2726 if (mContentParent == null) { 2727 return; 2728 } 2729 2730 final int featureMask = 1 << featureId; 2731 2732 if ((getFeatures() & featureMask) == 0 && !fromResume) { 2733 return; 2734 } 2735 2736 Drawable drawable = null; 2737 if (st != null) { 2738 drawable = st.child; 2739 if (drawable == null) 2740 drawable = st.local; 2741 if (drawable == null) 2742 drawable = st.def; 2743 } 2744 if ((getLocalFeatures() & featureMask) == 0) { 2745 if (getContainer() != null) { 2746 if (isActive() || fromResume) { 2747 getContainer().setChildDrawable(featureId, drawable); 2748 } 2749 } 2750 } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) { 2751 // System.out.println("Drawable changed: old=" + st.cur 2752 // + ", new=" + drawable); 2753 st.cur = drawable; 2754 st.curAlpha = st.alpha; 2755 onDrawableChanged(featureId, drawable, st.alpha); 2756 } 2757 } 2758 2759 private void updateInt(int featureId, int value, boolean fromResume) { 2760 2761 // Do nothing if the decor is not yet installed... an update will 2762 // need to be forced when we eventually become active. 2763 if (mContentParent == null) { 2764 return; 2765 } 2766 2767 final int featureMask = 1 << featureId; 2768 2769 if ((getFeatures() & featureMask) == 0 && !fromResume) { 2770 return; 2771 } 2772 2773 if ((getLocalFeatures() & featureMask) == 0) { 2774 if (getContainer() != null) { 2775 getContainer().setChildInt(featureId, value); 2776 } 2777 } else { 2778 onIntChanged(featureId, value); 2779 } 2780 } 2781 2782 private ImageView getLeftIconView() { 2783 if (mLeftIconView != null) { 2784 return mLeftIconView; 2785 } 2786 if (mContentParent == null) { 2787 installDecor(); 2788 } 2789 return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon)); 2790 } 2791 2792 private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) { 2793 if (mCircularProgressBar != null) { 2794 return mCircularProgressBar; 2795 } 2796 if (mContentParent == null && shouldInstallDecor) { 2797 installDecor(); 2798 } 2799 mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular); 2800 if (mCircularProgressBar != null) { 2801 mCircularProgressBar.setVisibility(View.INVISIBLE); 2802 } 2803 return mCircularProgressBar; 2804 } 2805 2806 private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) { 2807 if (mHorizontalProgressBar != null) { 2808 return mHorizontalProgressBar; 2809 } 2810 if (mContentParent == null && shouldInstallDecor) { 2811 installDecor(); 2812 } 2813 mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal); 2814 if (mHorizontalProgressBar != null) { 2815 mHorizontalProgressBar.setVisibility(View.INVISIBLE); 2816 } 2817 return mHorizontalProgressBar; 2818 } 2819 2820 private ImageView getRightIconView() { 2821 if (mRightIconView != null) { 2822 return mRightIconView; 2823 } 2824 if (mContentParent == null) { 2825 installDecor(); 2826 } 2827 return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon)); 2828 } 2829 2830 /** 2831 * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)} 2832 * callback. This method will grab whatever extra state is needed for the 2833 * callback that isn't given in the parameters. If the panel is not open, 2834 * this will not perform the callback. 2835 * 2836 * @param featureId Feature ID of the panel that was closed. Must be given. 2837 * @param panel Panel that was closed. Optional but useful if there is no 2838 * menu given. 2839 * @param menu The menu that was closed. Optional, but give if you have. 2840 */ 2841 private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) { 2842 final Callback cb = getCallback(); 2843 if (cb == null) 2844 return; 2845 2846 // Try to get a menu 2847 if (menu == null) { 2848 // Need a panel to grab the menu, so try to get that 2849 if (panel == null) { 2850 if ((featureId >= 0) && (featureId < mPanels.length)) { 2851 panel = mPanels[featureId]; 2852 } 2853 } 2854 2855 if (panel != null) { 2856 // menu still may be null, which is okay--we tried our best 2857 menu = panel.menu; 2858 } 2859 } 2860 2861 // If the panel is not open, do not callback 2862 if ((panel != null) && (!panel.isOpen)) 2863 return; 2864 2865 if (!isDestroyed()) { 2866 cb.onPanelClosed(featureId, menu); 2867 } 2868 } 2869 2870 /** 2871 * Helper method for adding launch-search to most applications. Opens the 2872 * search window using default settings. 2873 * 2874 * @return true if search window opened 2875 */ 2876 private boolean launchDefaultSearch() { 2877 final Callback cb = getCallback(); 2878 if (cb == null || isDestroyed()) { 2879 return false; 2880 } else { 2881 sendCloseSystemWindows("search"); 2882 return cb.onSearchRequested(); 2883 } 2884 } 2885 2886 @Override 2887 public void setVolumeControlStream(int streamType) { 2888 mVolumeControlStreamType = streamType; 2889 } 2890 2891 @Override 2892 public int getVolumeControlStream() { 2893 return mVolumeControlStreamType; 2894 } 2895 2896 private static final class DrawableFeatureState { 2897 DrawableFeatureState(int _featureId) { 2898 featureId = _featureId; 2899 } 2900 2901 final int featureId; 2902 2903 int resid; 2904 2905 Uri uri; 2906 2907 Drawable local; 2908 2909 Drawable child; 2910 2911 Drawable def; 2912 2913 Drawable cur; 2914 2915 int alpha = 255; 2916 2917 int curAlpha = 255; 2918 } 2919 2920 private static final class PanelFeatureState { 2921 2922 /** Feature ID for this panel. */ 2923 int featureId; 2924 2925 // Information pulled from the style for this panel. 2926 2927 int background; 2928 2929 /** The background when the panel spans the entire available width. */ 2930 int fullBackground; 2931 2932 int gravity; 2933 2934 int x; 2935 2936 int y; 2937 2938 int windowAnimations; 2939 2940 /** Dynamic state of the panel. */ 2941 DecorView decorView; 2942 2943 /** The panel that was returned by onCreatePanelView(). */ 2944 View createdPanelView; 2945 2946 /** The panel that we are actually showing. */ 2947 View shownPanelView; 2948 2949 /** Use {@link #setMenu} to set this. */ 2950 MenuBuilder menu; 2951 2952 IconMenuPresenter iconMenuPresenter; 2953 ListMenuPresenter expandedMenuPresenter; 2954 2955 /** 2956 * Whether the panel has been prepared (see 2957 * {@link PhoneWindow#preparePanel}). 2958 */ 2959 boolean isPrepared; 2960 2961 /** 2962 * Whether an item's action has been performed. This happens in obvious 2963 * scenarios (user clicks on menu item), but can also happen with 2964 * chording menu+(shortcut key). 2965 */ 2966 boolean isHandled; 2967 2968 boolean isOpen; 2969 2970 /** 2971 * True if the menu is in expanded mode, false if the menu is in icon 2972 * mode 2973 */ 2974 boolean isInExpandedMode; 2975 2976 public boolean qwertyMode; 2977 2978 boolean refreshDecorView; 2979 2980 boolean refreshMenuContent; 2981 2982 boolean wasLastOpen; 2983 2984 boolean wasLastExpanded; 2985 2986 /** 2987 * Contains the state of the menu when told to freeze. 2988 */ 2989 Bundle frozenMenuState; 2990 2991 PanelFeatureState(int featureId) { 2992 this.featureId = featureId; 2993 2994 refreshDecorView = false; 2995 } 2996 2997 public boolean hasPanelItems() { 2998 if (shownPanelView == null) return false; 2999 3000 if (isInExpandedMode) { 3001 return expandedMenuPresenter.getAdapter().getCount() > 0; 3002 } else { 3003 return ((ViewGroup) shownPanelView).getChildCount() > 0; 3004 } 3005 } 3006 3007 /** 3008 * Unregister and free attached MenuPresenters. They will be recreated as needed. 3009 */ 3010 public void clearMenuPresenters() { 3011 if (menu != null) { 3012 menu.removeMenuPresenter(iconMenuPresenter); 3013 menu.removeMenuPresenter(expandedMenuPresenter); 3014 } 3015 iconMenuPresenter = null; 3016 expandedMenuPresenter = null; 3017 } 3018 3019 void setStyle(Context context) { 3020 TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme); 3021 background = a.getResourceId( 3022 com.android.internal.R.styleable.Theme_panelBackground, 0); 3023 fullBackground = a.getResourceId( 3024 com.android.internal.R.styleable.Theme_panelFullBackground, 0); 3025 windowAnimations = a.getResourceId( 3026 com.android.internal.R.styleable.Theme_windowAnimationStyle, 0); 3027 a.recycle(); 3028 } 3029 3030 void setMenu(MenuBuilder menu) { 3031 this.menu = menu; 3032 } 3033 3034 MenuView getExpandedMenuView(MenuPresenter.Callback cb) { 3035 if (menu == null) return null; 3036 3037 getIconMenuView(cb); // Need this initialized to know where our offset goes 3038 3039 boolean init = false; 3040 if (expandedMenuPresenter == null) { 3041 expandedMenuPresenter = new ListMenuPresenter( 3042 com.android.internal.R.layout.list_menu_item_layout, 3043 com.android.internal.R.style.Theme_ExpandedMenu); 3044 expandedMenuPresenter.setCallback(cb); 3045 menu.addMenuPresenter(expandedMenuPresenter); 3046 init = true; 3047 } 3048 3049 expandedMenuPresenter.setItemIndexOffset(iconMenuPresenter.getNumActualItemsShown()); 3050 MenuView result = expandedMenuPresenter.getMenuView(decorView); 3051 3052 if (init && frozenMenuState != null) { 3053 expandedMenuPresenter.restoreHierarchyState(frozenMenuState); 3054 // Once we initialize the expanded menu we're done with the frozen state 3055 // since we will have also restored any icon menu state. 3056 frozenMenuState = null; 3057 } 3058 3059 return result; 3060 } 3061 3062 MenuView getIconMenuView(MenuPresenter.Callback cb) { 3063 if (menu == null) return null; 3064 3065 boolean init = false; 3066 if (iconMenuPresenter == null) { 3067 iconMenuPresenter = new IconMenuPresenter(); 3068 iconMenuPresenter.setCallback(cb); 3069 menu.addMenuPresenter(iconMenuPresenter); 3070 init = true; 3071 } 3072 3073 MenuView result = iconMenuPresenter.getMenuView(decorView); 3074 3075 if (init && frozenMenuState != null) { 3076 iconMenuPresenter.restoreHierarchyState(frozenMenuState); 3077 } 3078 3079 return result; 3080 } 3081 3082 Parcelable onSaveInstanceState() { 3083 SavedState savedState = new SavedState(); 3084 savedState.featureId = featureId; 3085 savedState.isOpen = isOpen; 3086 savedState.isInExpandedMode = isInExpandedMode; 3087 3088 if (menu != null) { 3089 savedState.menuState = new Bundle(); 3090 if (iconMenuPresenter != null) { 3091 iconMenuPresenter.saveHierarchyState(savedState.menuState); 3092 } 3093 if (expandedMenuPresenter != null) { 3094 expandedMenuPresenter.saveHierarchyState(savedState.menuState); 3095 } 3096 } 3097 3098 return savedState; 3099 } 3100 3101 void onRestoreInstanceState(Parcelable state) { 3102 SavedState savedState = (SavedState) state; 3103 featureId = savedState.featureId; 3104 wasLastOpen = savedState.isOpen; 3105 wasLastExpanded = savedState.isInExpandedMode; 3106 frozenMenuState = savedState.menuState; 3107 3108 /* 3109 * A LocalActivityManager keeps the same instance of this class around. 3110 * The first time the menu is being shown after restoring, the 3111 * Activity.onCreateOptionsMenu should be called. But, if it is the 3112 * same instance then menu != null and we won't call that method. 3113 * So, clear this. Also clear any cached views. 3114 */ 3115 menu = null; 3116 createdPanelView = null; 3117 shownPanelView = null; 3118 decorView = null; 3119 } 3120 3121 private static class SavedState implements Parcelable { 3122 int featureId; 3123 boolean isOpen; 3124 boolean isInExpandedMode; 3125 Bundle menuState; 3126 3127 public int describeContents() { 3128 return 0; 3129 } 3130 3131 public void writeToParcel(Parcel dest, int flags) { 3132 dest.writeInt(featureId); 3133 dest.writeInt(isOpen ? 1 : 0); 3134 dest.writeInt(isInExpandedMode ? 1 : 0); 3135 3136 if (isOpen) { 3137 dest.writeBundle(menuState); 3138 } 3139 } 3140 3141 private static SavedState readFromParcel(Parcel source) { 3142 SavedState savedState = new SavedState(); 3143 savedState.featureId = source.readInt(); 3144 savedState.isOpen = source.readInt() == 1; 3145 savedState.isInExpandedMode = source.readInt() == 1; 3146 3147 if (savedState.isOpen) { 3148 savedState.menuState = source.readBundle(); 3149 } 3150 3151 return savedState; 3152 } 3153 3154 public static final Parcelable.Creator<SavedState> CREATOR 3155 = new Parcelable.Creator<SavedState>() { 3156 public SavedState createFromParcel(Parcel in) { 3157 return readFromParcel(in); 3158 } 3159 3160 public SavedState[] newArray(int size) { 3161 return new SavedState[size]; 3162 } 3163 }; 3164 } 3165 3166 } 3167 3168 /** 3169 * Simple implementation of MenuBuilder.Callback that: 3170 * <li> Opens a submenu when selected. 3171 * <li> Calls back to the callback's onMenuItemSelected when an item is 3172 * selected. 3173 */ 3174 private final class DialogMenuCallback implements MenuBuilder.Callback { 3175 private int mFeatureId; 3176 private MenuDialogHelper mSubMenuHelper; 3177 3178 public DialogMenuCallback(int featureId) { 3179 mFeatureId = featureId; 3180 } 3181 3182 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 3183 if (allMenusAreClosing) { 3184 Callback callback = getCallback(); 3185 if (callback != null && !isDestroyed()) { 3186 callback.onPanelClosed(mFeatureId, menu); 3187 } 3188 3189 if (menu == mContextMenu) { 3190 dismissContextMenu(); 3191 } 3192 3193 // Dismiss the submenu, if it is showing 3194 if (mSubMenuHelper != null) { 3195 mSubMenuHelper.dismiss(); 3196 mSubMenuHelper = null; 3197 } 3198 } 3199 } 3200 3201 public void onCloseSubMenu(SubMenuBuilder menu) { 3202 Callback callback = getCallback(); 3203 if (callback != null && !isDestroyed()) { 3204 callback.onPanelClosed(mFeatureId, menu.getRootMenu()); 3205 } 3206 } 3207 3208 public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { 3209 Callback callback = getCallback(); 3210 return (callback != null && !isDestroyed()) 3211 && callback.onMenuItemSelected(mFeatureId, item); 3212 } 3213 3214 public void onMenuModeChange(MenuBuilder menu) { 3215 } 3216 3217 public boolean onSubMenuSelected(SubMenuBuilder subMenu) { 3218 // Set a simple callback for the submenu 3219 subMenu.setCallback(this); 3220 3221 // The window manager will give us a valid window token 3222 mSubMenuHelper = new MenuDialogHelper(subMenu); 3223 mSubMenuHelper.show(null); 3224 3225 return true; 3226 } 3227 } 3228 3229 void sendCloseSystemWindows() { 3230 PhoneWindowManager.sendCloseSystemWindows(getContext(), null); 3231 } 3232 3233 void sendCloseSystemWindows(String reason) { 3234 PhoneWindowManager.sendCloseSystemWindows(getContext(), reason); 3235 } 3236} 3237