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