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