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