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