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