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