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