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