PhoneWindow.java revision 0048da2114b54357e4901f40930afc7d503e0e24
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, AudioManager.FLAG_SHOW_UI); 1708 } 1709 return true; 1710 } 1711 case KeyEvent.KEYCODE_VOLUME_MUTE: { 1712 getAudioManager().handleKeyDown(event, mVolumeControlStreamType); 1713 return true; 1714 } 1715 // These are all the recognized media key codes in 1716 // KeyEvent.isMediaKey() 1717 case KeyEvent.KEYCODE_MEDIA_PLAY: 1718 case KeyEvent.KEYCODE_MEDIA_PAUSE: 1719 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: 1720 case KeyEvent.KEYCODE_MUTE: 1721 case KeyEvent.KEYCODE_HEADSETHOOK: 1722 case KeyEvent.KEYCODE_MEDIA_STOP: 1723 case KeyEvent.KEYCODE_MEDIA_NEXT: 1724 case KeyEvent.KEYCODE_MEDIA_PREVIOUS: 1725 case KeyEvent.KEYCODE_MEDIA_REWIND: 1726 case KeyEvent.KEYCODE_MEDIA_RECORD: 1727 case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: { 1728 if (mMediaController != null) { 1729 if (mMediaController.dispatchMediaButtonEvent(event)) { 1730 return true; 1731 } 1732 } 1733 return false; 1734 } 1735 1736 case KeyEvent.KEYCODE_MENU: { 1737 onKeyDownPanel((featureId < 0) ? FEATURE_OPTIONS_PANEL : featureId, event); 1738 return true; 1739 } 1740 1741 case KeyEvent.KEYCODE_BACK: { 1742 if (event.getRepeatCount() > 0) break; 1743 if (featureId < 0) break; 1744 // Currently don't do anything with long press. 1745 if (dispatcher != null) { 1746 dispatcher.startTracking(event, this); 1747 } 1748 return true; 1749 } 1750 1751 } 1752 1753 return false; 1754 } 1755 1756 private KeyguardManager getKeyguardManager() { 1757 if (mKeyguardManager == null) { 1758 mKeyguardManager = (KeyguardManager) getContext().getSystemService( 1759 Context.KEYGUARD_SERVICE); 1760 } 1761 return mKeyguardManager; 1762 } 1763 1764 AudioManager getAudioManager() { 1765 if (mAudioManager == null) { 1766 mAudioManager = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE); 1767 } 1768 return mAudioManager; 1769 } 1770 1771 /** 1772 * A key was released and not handled by anything else in the window. 1773 * 1774 * @see #onKeyDown 1775 * @see android.view.KeyEvent 1776 */ 1777 protected boolean onKeyUp(int featureId, int keyCode, KeyEvent event) { 1778 final KeyEvent.DispatcherState dispatcher = 1779 mDecor != null ? mDecor.getKeyDispatcherState() : null; 1780 if (dispatcher != null) { 1781 dispatcher.handleUpEvent(event); 1782 } 1783 //Log.i(TAG, "Key up: repeat=" + event.getRepeatCount() 1784 // + " flags=0x" + Integer.toHexString(event.getFlags())); 1785 1786 switch (keyCode) { 1787 case KeyEvent.KEYCODE_VOLUME_UP: 1788 case KeyEvent.KEYCODE_VOLUME_DOWN: { 1789 // If we have a session send it the volume command, otherwise 1790 // use the suggested stream. 1791 if (mMediaController != null) { 1792 mMediaController.adjustVolume(0, AudioManager.FLAG_PLAY_SOUND 1793 | AudioManager.FLAG_VIBRATE); 1794 } else { 1795 MediaSessionLegacyHelper.getHelper(getContext()).sendAdjustVolumeBy( 1796 mVolumeControlStreamType, 0, 1797 AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE); 1798 } 1799 return true; 1800 } 1801 case KeyEvent.KEYCODE_VOLUME_MUTE: { 1802 // Similar code is in PhoneFallbackEventHandler in case the window 1803 // doesn't have one of these. In this case, we execute it here and 1804 // eat the event instead, because we have mVolumeControlStreamType 1805 // and they don't. 1806 getAudioManager().handleKeyUp(event, mVolumeControlStreamType); 1807 return true; 1808 } 1809 // These are all the recognized media key codes in 1810 // KeyEvent.isMediaKey() 1811 case KeyEvent.KEYCODE_MEDIA_PLAY: 1812 case KeyEvent.KEYCODE_MEDIA_PAUSE: 1813 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE: 1814 case KeyEvent.KEYCODE_MUTE: 1815 case KeyEvent.KEYCODE_HEADSETHOOK: 1816 case KeyEvent.KEYCODE_MEDIA_STOP: 1817 case KeyEvent.KEYCODE_MEDIA_NEXT: 1818 case KeyEvent.KEYCODE_MEDIA_PREVIOUS: 1819 case KeyEvent.KEYCODE_MEDIA_REWIND: 1820 case KeyEvent.KEYCODE_MEDIA_RECORD: 1821 case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD: { 1822 if (mMediaController != null) { 1823 if (mMediaController.dispatchMediaButtonEvent(event)) { 1824 return true; 1825 } 1826 } 1827 return false; 1828 } 1829 1830 case KeyEvent.KEYCODE_MENU: { 1831 onKeyUpPanel(featureId < 0 ? FEATURE_OPTIONS_PANEL : featureId, 1832 event); 1833 return true; 1834 } 1835 1836 case KeyEvent.KEYCODE_BACK: { 1837 if (featureId < 0) break; 1838 if (event.isTracking() && !event.isCanceled()) { 1839 if (featureId == FEATURE_OPTIONS_PANEL) { 1840 PanelFeatureState st = getPanelState(featureId, false); 1841 if (st != null && st.isInExpandedMode) { 1842 // If the user is in an expanded menu and hits back, it 1843 // should go back to the icon menu 1844 reopenMenu(true); 1845 return true; 1846 } 1847 } 1848 closePanel(featureId); 1849 return true; 1850 } 1851 break; 1852 } 1853 1854 case KeyEvent.KEYCODE_SEARCH: { 1855 /* 1856 * Do this in onKeyUp since the Search key is also used for 1857 * chording quick launch shortcuts. 1858 */ 1859 if (getKeyguardManager().inKeyguardRestrictedInputMode()) { 1860 break; 1861 } 1862 if (event.isTracking() && !event.isCanceled()) { 1863 launchDefaultSearch(); 1864 } 1865 return true; 1866 } 1867 } 1868 1869 return false; 1870 } 1871 1872 @Override 1873 protected void onActive() { 1874 } 1875 1876 @Override 1877 public final View getDecorView() { 1878 if (mDecor == null) { 1879 installDecor(); 1880 } 1881 return mDecor; 1882 } 1883 1884 @Override 1885 public final View peekDecorView() { 1886 return mDecor; 1887 } 1888 1889 static private final String FOCUSED_ID_TAG = "android:focusedViewId"; 1890 static private final String VIEWS_TAG = "android:views"; 1891 static private final String PANELS_TAG = "android:Panels"; 1892 static private final String ACTION_BAR_TAG = "android:ActionBar"; 1893 1894 /** {@inheritDoc} */ 1895 @Override 1896 public Bundle saveHierarchyState() { 1897 Bundle outState = new Bundle(); 1898 if (mContentParent == null) { 1899 return outState; 1900 } 1901 1902 SparseArray<Parcelable> states = new SparseArray<Parcelable>(); 1903 mContentParent.saveHierarchyState(states); 1904 outState.putSparseParcelableArray(VIEWS_TAG, states); 1905 1906 // save the focused view id 1907 View focusedView = mContentParent.findFocus(); 1908 if (focusedView != null) { 1909 if (focusedView.getId() != View.NO_ID) { 1910 outState.putInt(FOCUSED_ID_TAG, focusedView.getId()); 1911 } else { 1912 if (false) { 1913 Log.d(TAG, "couldn't save which view has focus because the focused view " 1914 + focusedView + " has no id."); 1915 } 1916 } 1917 } 1918 1919 // save the panels 1920 SparseArray<Parcelable> panelStates = new SparseArray<Parcelable>(); 1921 savePanelState(panelStates); 1922 if (panelStates.size() > 0) { 1923 outState.putSparseParcelableArray(PANELS_TAG, panelStates); 1924 } 1925 1926 if (mDecorContentParent != null) { 1927 SparseArray<Parcelable> actionBarStates = new SparseArray<Parcelable>(); 1928 mDecorContentParent.saveToolbarHierarchyState(actionBarStates); 1929 outState.putSparseParcelableArray(ACTION_BAR_TAG, actionBarStates); 1930 } 1931 1932 return outState; 1933 } 1934 1935 /** {@inheritDoc} */ 1936 @Override 1937 public void restoreHierarchyState(Bundle savedInstanceState) { 1938 if (mContentParent == null) { 1939 return; 1940 } 1941 1942 SparseArray<Parcelable> savedStates 1943 = savedInstanceState.getSparseParcelableArray(VIEWS_TAG); 1944 if (savedStates != null) { 1945 mContentParent.restoreHierarchyState(savedStates); 1946 } 1947 1948 // restore the focused view 1949 int focusedViewId = savedInstanceState.getInt(FOCUSED_ID_TAG, View.NO_ID); 1950 if (focusedViewId != View.NO_ID) { 1951 View needsFocus = mContentParent.findViewById(focusedViewId); 1952 if (needsFocus != null) { 1953 needsFocus.requestFocus(); 1954 } else { 1955 Log.w(TAG, 1956 "Previously focused view reported id " + focusedViewId 1957 + " during save, but can't be found during restore."); 1958 } 1959 } 1960 1961 // restore the panels 1962 SparseArray<Parcelable> panelStates = savedInstanceState.getSparseParcelableArray(PANELS_TAG); 1963 if (panelStates != null) { 1964 restorePanelState(panelStates); 1965 } 1966 1967 if (mDecorContentParent != null) { 1968 SparseArray<Parcelable> actionBarStates = 1969 savedInstanceState.getSparseParcelableArray(ACTION_BAR_TAG); 1970 if (actionBarStates != null) { 1971 mDecorContentParent.restoreToolbarHierarchyState(actionBarStates); 1972 } else { 1973 Log.w(TAG, "Missing saved instance states for action bar views! " + 1974 "State will not be restored."); 1975 } 1976 } 1977 } 1978 1979 /** 1980 * Invoked when the panels should freeze their state. 1981 * 1982 * @param icicles Save state into this. This is usually indexed by the 1983 * featureId. This will be given to {@link #restorePanelState} in the 1984 * future. 1985 */ 1986 private void savePanelState(SparseArray<Parcelable> icicles) { 1987 PanelFeatureState[] panels = mPanels; 1988 if (panels == null) { 1989 return; 1990 } 1991 1992 for (int curFeatureId = panels.length - 1; curFeatureId >= 0; curFeatureId--) { 1993 if (panels[curFeatureId] != null) { 1994 icicles.put(curFeatureId, panels[curFeatureId].onSaveInstanceState()); 1995 } 1996 } 1997 } 1998 1999 /** 2000 * Invoked when the panels should thaw their state from a previously frozen state. 2001 * 2002 * @param icicles The state saved by {@link #savePanelState} that needs to be thawed. 2003 */ 2004 private void restorePanelState(SparseArray<Parcelable> icicles) { 2005 PanelFeatureState st; 2006 int curFeatureId; 2007 for (int i = icicles.size() - 1; i >= 0; i--) { 2008 curFeatureId = icicles.keyAt(i); 2009 st = getPanelState(curFeatureId, false /* required */); 2010 if (st == null) { 2011 // The panel must not have been required, and is currently not around, skip it 2012 continue; 2013 } 2014 2015 st.onRestoreInstanceState(icicles.get(curFeatureId)); 2016 invalidatePanelMenu(curFeatureId); 2017 } 2018 2019 /* 2020 * Implementation note: call openPanelsAfterRestore later to actually open the 2021 * restored panels. 2022 */ 2023 } 2024 2025 /** 2026 * Opens the panels that have had their state restored. This should be 2027 * called sometime after {@link #restorePanelState} when it is safe to add 2028 * to the window manager. 2029 */ 2030 private void openPanelsAfterRestore() { 2031 PanelFeatureState[] panels = mPanels; 2032 2033 if (panels == null) { 2034 return; 2035 } 2036 2037 PanelFeatureState st; 2038 for (int i = panels.length - 1; i >= 0; i--) { 2039 st = panels[i]; 2040 // We restore the panel if it was last open; we skip it if it 2041 // now is open, to avoid a race condition if the user immediately 2042 // opens it when we are resuming. 2043 if (st != null) { 2044 st.applyFrozenState(); 2045 if (!st.isOpen && st.wasLastOpen) { 2046 st.isInExpandedMode = st.wasLastExpanded; 2047 openPanel(st, null); 2048 } 2049 } 2050 } 2051 } 2052 2053 private class PanelMenuPresenterCallback implements MenuPresenter.Callback { 2054 @Override 2055 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 2056 final Menu parentMenu = menu.getRootMenu(); 2057 final boolean isSubMenu = parentMenu != menu; 2058 final PanelFeatureState panel = findMenuPanel(isSubMenu ? parentMenu : menu); 2059 if (panel != null) { 2060 if (isSubMenu) { 2061 callOnPanelClosed(panel.featureId, panel, parentMenu); 2062 closePanel(panel, true); 2063 } else { 2064 // Close the panel and only do the callback if the menu is being 2065 // closed completely, not if opening a sub menu 2066 closePanel(panel, allMenusAreClosing); 2067 } 2068 } 2069 } 2070 2071 @Override 2072 public boolean onOpenSubMenu(MenuBuilder subMenu) { 2073 if (subMenu == null && hasFeature(FEATURE_ACTION_BAR)) { 2074 Callback cb = getCallback(); 2075 if (cb != null && !isDestroyed()) { 2076 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 2077 } 2078 } 2079 2080 return true; 2081 } 2082 } 2083 2084 private final class ActionMenuPresenterCallback implements MenuPresenter.Callback { 2085 @Override 2086 public boolean onOpenSubMenu(MenuBuilder subMenu) { 2087 Callback cb = getCallback(); 2088 if (cb != null) { 2089 cb.onMenuOpened(FEATURE_ACTION_BAR, subMenu); 2090 return true; 2091 } 2092 return false; 2093 } 2094 2095 @Override 2096 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 2097 checkCloseActionMenu(menu); 2098 } 2099 } 2100 2101 private final class DecorView extends FrameLayout implements RootViewSurfaceTaker, 2102 View.OnSystemUiVisibilityChangeListener { 2103 /* package */int mDefaultOpacity = PixelFormat.OPAQUE; 2104 2105 /** The feature ID of the panel, or -1 if this is the application's DecorView */ 2106 private final int mFeatureId; 2107 2108 private final Rect mDrawingBounds = new Rect(); 2109 2110 private final Rect mBackgroundPadding = new Rect(); 2111 2112 private final Rect mFramePadding = new Rect(); 2113 2114 private final Rect mFrameOffsets = new Rect(); 2115 2116 private boolean mChanging; 2117 2118 private Drawable mMenuBackground; 2119 private boolean mWatchingForMenu; 2120 private int mDownY; 2121 2122 private ActionMode mActionMode; 2123 private ActionBarContextView mActionModeView; 2124 private PopupWindow mActionModePopup; 2125 private Runnable mShowActionModePopup; 2126 2127 // View added at runtime to draw under the status bar area 2128 private View mStatusGuard; 2129 // View added at runtime to draw under the navigation bar area 2130 private View mNavigationGuard; 2131 2132 private View mStatusColorView; 2133 private View mNavigationColorView; 2134 2135 private int mLastTopInset = 0; 2136 private int mLastBottomInset = 0; 2137 private int mLastSystemUiVisibility = 0; 2138 2139 2140 public DecorView(Context context, int featureId) { 2141 super(context); 2142 mFeatureId = featureId; 2143 } 2144 2145 @Override 2146 public boolean dispatchKeyEvent(KeyEvent event) { 2147 final int keyCode = event.getKeyCode(); 2148 final int action = event.getAction(); 2149 final boolean isDown = action == KeyEvent.ACTION_DOWN; 2150 2151 if (isDown && (event.getRepeatCount() == 0)) { 2152 // First handle chording of panel key: if a panel key is held 2153 // but not released, try to execute a shortcut in it. 2154 if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)) { 2155 boolean handled = dispatchKeyShortcutEvent(event); 2156 if (handled) { 2157 return true; 2158 } 2159 } 2160 2161 // If a panel is open, perform a shortcut on it without the 2162 // chorded panel key 2163 if ((mPreparedPanel != null) && mPreparedPanel.isOpen) { 2164 if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) { 2165 return true; 2166 } 2167 } 2168 } 2169 2170 if (!isDestroyed()) { 2171 final Callback cb = getCallback(); 2172 final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event) 2173 : super.dispatchKeyEvent(event); 2174 if (handled) { 2175 return true; 2176 } 2177 } 2178 2179 return isDown ? PhoneWindow.this.onKeyDown(mFeatureId, event.getKeyCode(), event) 2180 : PhoneWindow.this.onKeyUp(mFeatureId, event.getKeyCode(), event); 2181 } 2182 2183 @Override 2184 public boolean dispatchKeyShortcutEvent(KeyEvent ev) { 2185 // If the panel is already prepared, then perform the shortcut using it. 2186 boolean handled; 2187 if (mPreparedPanel != null) { 2188 handled = performPanelShortcut(mPreparedPanel, ev.getKeyCode(), ev, 2189 Menu.FLAG_PERFORM_NO_CLOSE); 2190 if (handled) { 2191 if (mPreparedPanel != null) { 2192 mPreparedPanel.isHandled = true; 2193 } 2194 return true; 2195 } 2196 } 2197 2198 // Shortcut not handled by the panel. Dispatch to the view hierarchy. 2199 final Callback cb = getCallback(); 2200 handled = cb != null && !isDestroyed() && mFeatureId < 0 2201 ? cb.dispatchKeyShortcutEvent(ev) : super.dispatchKeyShortcutEvent(ev); 2202 if (handled) { 2203 return true; 2204 } 2205 2206 // If the panel is not prepared, then we may be trying to handle a shortcut key 2207 // combination such as Control+C. Temporarily prepare the panel then mark it 2208 // unprepared again when finished to ensure that the panel will again be prepared 2209 // the next time it is shown for real. 2210 if (mPreparedPanel == null) { 2211 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 2212 preparePanel(st, ev); 2213 handled = performPanelShortcut(st, ev.getKeyCode(), ev, 2214 Menu.FLAG_PERFORM_NO_CLOSE); 2215 st.isPrepared = false; 2216 if (handled) { 2217 return true; 2218 } 2219 } 2220 return false; 2221 } 2222 2223 @Override 2224 public boolean dispatchTouchEvent(MotionEvent ev) { 2225 final Callback cb = getCallback(); 2226 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) 2227 : super.dispatchTouchEvent(ev); 2228 } 2229 2230 @Override 2231 public boolean dispatchTrackballEvent(MotionEvent ev) { 2232 final Callback cb = getCallback(); 2233 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTrackballEvent(ev) 2234 : super.dispatchTrackballEvent(ev); 2235 } 2236 2237 @Override 2238 public boolean dispatchGenericMotionEvent(MotionEvent ev) { 2239 final Callback cb = getCallback(); 2240 return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchGenericMotionEvent(ev) 2241 : super.dispatchGenericMotionEvent(ev); 2242 } 2243 2244 public boolean superDispatchKeyEvent(KeyEvent event) { 2245 // Give priority to closing action modes if applicable. 2246 if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { 2247 final int action = event.getAction(); 2248 // Back cancels action modes first. 2249 if (mActionMode != null) { 2250 if (action == KeyEvent.ACTION_UP) { 2251 mActionMode.finish(); 2252 } 2253 return true; 2254 } 2255 } 2256 2257 return super.dispatchKeyEvent(event); 2258 } 2259 2260 public boolean superDispatchKeyShortcutEvent(KeyEvent event) { 2261 return super.dispatchKeyShortcutEvent(event); 2262 } 2263 2264 public boolean superDispatchTouchEvent(MotionEvent event) { 2265 return super.dispatchTouchEvent(event); 2266 } 2267 2268 public boolean superDispatchTrackballEvent(MotionEvent event) { 2269 return super.dispatchTrackballEvent(event); 2270 } 2271 2272 public boolean superDispatchGenericMotionEvent(MotionEvent event) { 2273 return super.dispatchGenericMotionEvent(event); 2274 } 2275 2276 @Override 2277 public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) { 2278 if (mOutsetBottom != null) { 2279 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); 2280 int bottom = (int) mOutsetBottom.getDimension(metrics); 2281 WindowInsets newInsets = insets.replaceSystemWindowInsets( 2282 insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(), 2283 insets.getSystemWindowInsetRight(), 2284 insets.getSystemWindowInsetBottom() + bottom); 2285 return super.dispatchApplyWindowInsets(newInsets); 2286 } else { 2287 return super.dispatchApplyWindowInsets(insets); 2288 } 2289 } 2290 2291 2292 @Override 2293 public boolean onTouchEvent(MotionEvent event) { 2294 return onInterceptTouchEvent(event); 2295 } 2296 2297 private boolean isOutOfBounds(int x, int y) { 2298 return x < -5 || y < -5 || x > (getWidth() + 5) 2299 || y > (getHeight() + 5); 2300 } 2301 2302 @Override 2303 public boolean onInterceptTouchEvent(MotionEvent event) { 2304 int action = event.getAction(); 2305 if (mFeatureId >= 0) { 2306 if (action == MotionEvent.ACTION_DOWN) { 2307 int x = (int)event.getX(); 2308 int y = (int)event.getY(); 2309 if (isOutOfBounds(x, y)) { 2310 closePanel(mFeatureId); 2311 return true; 2312 } 2313 } 2314 } 2315 2316 if (!SWEEP_OPEN_MENU) { 2317 return false; 2318 } 2319 2320 if (mFeatureId >= 0) { 2321 if (action == MotionEvent.ACTION_DOWN) { 2322 Log.i(TAG, "Watchiing!"); 2323 mWatchingForMenu = true; 2324 mDownY = (int) event.getY(); 2325 return false; 2326 } 2327 2328 if (!mWatchingForMenu) { 2329 return false; 2330 } 2331 2332 int y = (int)event.getY(); 2333 if (action == MotionEvent.ACTION_MOVE) { 2334 if (y > (mDownY+30)) { 2335 Log.i(TAG, "Closing!"); 2336 closePanel(mFeatureId); 2337 mWatchingForMenu = false; 2338 return true; 2339 } 2340 } else if (action == MotionEvent.ACTION_UP) { 2341 mWatchingForMenu = false; 2342 } 2343 2344 return false; 2345 } 2346 2347 //Log.i(TAG, "Intercept: action=" + action + " y=" + event.getY() 2348 // + " (in " + getHeight() + ")"); 2349 2350 if (action == MotionEvent.ACTION_DOWN) { 2351 int y = (int)event.getY(); 2352 if (y >= (getHeight()-5) && !hasChildren()) { 2353 Log.i(TAG, "Watchiing!"); 2354 mWatchingForMenu = true; 2355 } 2356 return false; 2357 } 2358 2359 if (!mWatchingForMenu) { 2360 return false; 2361 } 2362 2363 int y = (int)event.getY(); 2364 if (action == MotionEvent.ACTION_MOVE) { 2365 if (y < (getHeight()-30)) { 2366 Log.i(TAG, "Opening!"); 2367 openPanel(FEATURE_OPTIONS_PANEL, new KeyEvent( 2368 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU)); 2369 mWatchingForMenu = false; 2370 return true; 2371 } 2372 } else if (action == MotionEvent.ACTION_UP) { 2373 mWatchingForMenu = false; 2374 } 2375 2376 return false; 2377 } 2378 2379 @Override 2380 public void sendAccessibilityEvent(int eventType) { 2381 if (!AccessibilityManager.getInstance(mContext).isEnabled()) { 2382 return; 2383 } 2384 2385 // if we are showing a feature that should be announced and one child 2386 // make this child the event source since this is the feature itself 2387 // otherwise the callback will take over and announce its client 2388 if ((mFeatureId == FEATURE_OPTIONS_PANEL || 2389 mFeatureId == FEATURE_CONTEXT_MENU || 2390 mFeatureId == FEATURE_PROGRESS || 2391 mFeatureId == FEATURE_INDETERMINATE_PROGRESS) 2392 && getChildCount() == 1) { 2393 getChildAt(0).sendAccessibilityEvent(eventType); 2394 } else { 2395 super.sendAccessibilityEvent(eventType); 2396 } 2397 } 2398 2399 @Override 2400 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 2401 final Callback cb = getCallback(); 2402 if (cb != null && !isDestroyed()) { 2403 if (cb.dispatchPopulateAccessibilityEvent(event)) { 2404 return true; 2405 } 2406 } 2407 return super.dispatchPopulateAccessibilityEvent(event); 2408 } 2409 2410 @Override 2411 protected boolean setFrame(int l, int t, int r, int b) { 2412 boolean changed = super.setFrame(l, t, r, b); 2413 if (changed) { 2414 final Rect drawingBounds = mDrawingBounds; 2415 getDrawingRect(drawingBounds); 2416 2417 Drawable fg = getForeground(); 2418 if (fg != null) { 2419 final Rect frameOffsets = mFrameOffsets; 2420 drawingBounds.left += frameOffsets.left; 2421 drawingBounds.top += frameOffsets.top; 2422 drawingBounds.right -= frameOffsets.right; 2423 drawingBounds.bottom -= frameOffsets.bottom; 2424 fg.setBounds(drawingBounds); 2425 final Rect framePadding = mFramePadding; 2426 drawingBounds.left += framePadding.left - frameOffsets.left; 2427 drawingBounds.top += framePadding.top - frameOffsets.top; 2428 drawingBounds.right -= framePadding.right - frameOffsets.right; 2429 drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom; 2430 } 2431 2432 Drawable bg = getBackground(); 2433 if (bg != null) { 2434 bg.setBounds(drawingBounds); 2435 } 2436 2437 if (SWEEP_OPEN_MENU) { 2438 if (mMenuBackground == null && mFeatureId < 0 2439 && getAttributes().height 2440 == WindowManager.LayoutParams.MATCH_PARENT) { 2441 mMenuBackground = getContext().getDrawable( 2442 com.android.internal.R.drawable.menu_background); 2443 } 2444 if (mMenuBackground != null) { 2445 mMenuBackground.setBounds(drawingBounds.left, 2446 drawingBounds.bottom-6, drawingBounds.right, 2447 drawingBounds.bottom+20); 2448 } 2449 } 2450 } 2451 return changed; 2452 } 2453 2454 @Override 2455 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 2456 final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics(); 2457 final boolean isPortrait = metrics.widthPixels < metrics.heightPixels; 2458 2459 final int widthMode = getMode(widthMeasureSpec); 2460 final int heightMode = getMode(heightMeasureSpec); 2461 2462 boolean fixedWidth = false; 2463 if (widthMode == AT_MOST) { 2464 final TypedValue tvw = isPortrait ? mFixedWidthMinor : mFixedWidthMajor; 2465 if (tvw != null && tvw.type != TypedValue.TYPE_NULL) { 2466 final int w; 2467 if (tvw.type == TypedValue.TYPE_DIMENSION) { 2468 w = (int) tvw.getDimension(metrics); 2469 } else if (tvw.type == TypedValue.TYPE_FRACTION) { 2470 w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels); 2471 } else { 2472 w = 0; 2473 } 2474 2475 if (w > 0) { 2476 final int widthSize = MeasureSpec.getSize(widthMeasureSpec); 2477 widthMeasureSpec = MeasureSpec.makeMeasureSpec( 2478 Math.min(w, widthSize), EXACTLY); 2479 fixedWidth = true; 2480 } 2481 } 2482 } 2483 2484 if (heightMode == AT_MOST) { 2485 final TypedValue tvh = isPortrait ? mFixedHeightMajor : mFixedHeightMinor; 2486 if (tvh != null && tvh.type != TypedValue.TYPE_NULL) { 2487 final int h; 2488 if (tvh.type == TypedValue.TYPE_DIMENSION) { 2489 h = (int) tvh.getDimension(metrics); 2490 } else if (tvh.type == TypedValue.TYPE_FRACTION) { 2491 h = (int) tvh.getFraction(metrics.heightPixels, metrics.heightPixels); 2492 } else { 2493 h = 0; 2494 } 2495 if (h > 0) { 2496 final int heightSize = MeasureSpec.getSize(heightMeasureSpec); 2497 heightMeasureSpec = MeasureSpec.makeMeasureSpec( 2498 Math.min(h, heightSize), EXACTLY); 2499 } 2500 } 2501 } 2502 2503 if (mOutsetBottom != null) { 2504 int mode = MeasureSpec.getMode(heightMeasureSpec); 2505 if (mode != MeasureSpec.UNSPECIFIED) { 2506 int outset = (int) mOutsetBottom.getDimension(metrics); 2507 int height = MeasureSpec.getSize(heightMeasureSpec); 2508 heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + outset, mode); 2509 } 2510 } 2511 2512 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 2513 2514 int width = getMeasuredWidth(); 2515 boolean measure = false; 2516 2517 widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY); 2518 2519 if (!fixedWidth && widthMode == AT_MOST) { 2520 final TypedValue tv = isPortrait ? mMinWidthMinor : mMinWidthMajor; 2521 if (tv.type != TypedValue.TYPE_NULL) { 2522 final int min; 2523 if (tv.type == TypedValue.TYPE_DIMENSION) { 2524 min = (int)tv.getDimension(metrics); 2525 } else if (tv.type == TypedValue.TYPE_FRACTION) { 2526 min = (int)tv.getFraction(metrics.widthPixels, metrics.widthPixels); 2527 } else { 2528 min = 0; 2529 } 2530 2531 if (width < min) { 2532 widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY); 2533 measure = true; 2534 } 2535 } 2536 } 2537 2538 // TODO: Support height? 2539 2540 if (measure) { 2541 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 2542 } 2543 } 2544 2545 @Override 2546 public void draw(Canvas canvas) { 2547 super.draw(canvas); 2548 2549 if (mMenuBackground != null) { 2550 mMenuBackground.draw(canvas); 2551 } 2552 } 2553 2554 2555 @Override 2556 public boolean showContextMenuForChild(View originalView) { 2557 // Reuse the context menu builder 2558 if (mContextMenu == null) { 2559 mContextMenu = new ContextMenuBuilder(getContext()); 2560 mContextMenu.setCallback(mContextMenuCallback); 2561 } else { 2562 mContextMenu.clearAll(); 2563 } 2564 2565 final MenuDialogHelper helper = mContextMenu.show(originalView, 2566 originalView.getWindowToken()); 2567 if (helper != null) { 2568 helper.setPresenterCallback(mContextMenuCallback); 2569 } else if (mContextMenuHelper != null) { 2570 // No menu to show, but if we have a menu currently showing it just became blank. 2571 // Close it. 2572 mContextMenuHelper.dismiss(); 2573 } 2574 mContextMenuHelper = helper; 2575 return helper != null; 2576 } 2577 2578 @Override 2579 public ActionMode startActionModeForChild(View originalView, 2580 ActionMode.Callback callback) { 2581 // originalView can be used here to be sure that we don't obscure 2582 // relevant content with the context mode UI. 2583 return startActionMode(callback); 2584 } 2585 2586 @Override 2587 public ActionMode startActionMode(ActionMode.Callback callback) { 2588 if (mActionMode != null) { 2589 mActionMode.finish(); 2590 } 2591 2592 final ActionMode.Callback wrappedCallback = new ActionModeCallbackWrapper(callback); 2593 ActionMode mode = null; 2594 if (getCallback() != null && !isDestroyed()) { 2595 try { 2596 mode = getCallback().onWindowStartingActionMode(wrappedCallback); 2597 } catch (AbstractMethodError ame) { 2598 // Older apps might not implement this callback method. 2599 } 2600 } 2601 if (mode != null) { 2602 mActionMode = mode; 2603 } else { 2604 if (mActionModeView == null) { 2605 if (isFloating()) { 2606 mActionModeView = new ActionBarContextView(mContext); 2607 mActionModePopup = new PopupWindow(mContext, null, 2608 com.android.internal.R.attr.actionModePopupWindowStyle); 2609 mActionModePopup.setWindowLayoutType( 2610 WindowManager.LayoutParams.TYPE_APPLICATION); 2611 mActionModePopup.setContentView(mActionModeView); 2612 mActionModePopup.setWidth(MATCH_PARENT); 2613 2614 TypedValue heightValue = new TypedValue(); 2615 mContext.getTheme().resolveAttribute( 2616 com.android.internal.R.attr.actionBarSize, heightValue, true); 2617 final int height = TypedValue.complexToDimensionPixelSize(heightValue.data, 2618 mContext.getResources().getDisplayMetrics()); 2619 mActionModeView.setContentHeight(height); 2620 mActionModePopup.setHeight(WRAP_CONTENT); 2621 mShowActionModePopup = new Runnable() { 2622 public void run() { 2623 mActionModePopup.showAtLocation( 2624 mActionModeView.getApplicationWindowToken(), 2625 Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0); 2626 } 2627 }; 2628 } else { 2629 ViewStub stub = (ViewStub) findViewById( 2630 com.android.internal.R.id.action_mode_bar_stub); 2631 if (stub != null) { 2632 mActionModeView = (ActionBarContextView) stub.inflate(); 2633 } 2634 } 2635 } 2636 2637 if (mActionModeView != null) { 2638 mActionModeView.killMode(); 2639 mode = new StandaloneActionMode(getContext(), mActionModeView, wrappedCallback, 2640 mActionModePopup == null); 2641 if (callback.onCreateActionMode(mode, mode.getMenu())) { 2642 mode.invalidate(); 2643 mActionModeView.initForMode(mode); 2644 mActionModeView.setVisibility(View.VISIBLE); 2645 mActionMode = mode; 2646 if (mActionModePopup != null) { 2647 post(mShowActionModePopup); 2648 } 2649 mActionModeView.sendAccessibilityEvent( 2650 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED); 2651 } else { 2652 mActionMode = null; 2653 } 2654 } 2655 } 2656 if (mActionMode != null && getCallback() != null && !isDestroyed()) { 2657 try { 2658 getCallback().onActionModeStarted(mActionMode); 2659 } catch (AbstractMethodError ame) { 2660 // Older apps might not implement this callback method. 2661 } 2662 } 2663 return mActionMode; 2664 } 2665 2666 public void startChanging() { 2667 mChanging = true; 2668 } 2669 2670 public void finishChanging() { 2671 mChanging = false; 2672 drawableChanged(); 2673 } 2674 2675 public void setWindowBackground(Drawable drawable) { 2676 if (getBackground() != drawable) { 2677 setBackgroundDrawable(drawable); 2678 if (drawable != null) { 2679 drawable.getPadding(mBackgroundPadding); 2680 } else { 2681 mBackgroundPadding.setEmpty(); 2682 } 2683 drawableChanged(); 2684 } 2685 } 2686 2687 @Override 2688 public void setBackgroundDrawable(Drawable d) { 2689 super.setBackgroundDrawable(d); 2690 if (getWindowToken() != null) { 2691 updateWindowResizeState(); 2692 } 2693 } 2694 2695 public void setWindowFrame(Drawable drawable) { 2696 if (getForeground() != drawable) { 2697 setForeground(drawable); 2698 if (drawable != null) { 2699 drawable.getPadding(mFramePadding); 2700 } else { 2701 mFramePadding.setEmpty(); 2702 } 2703 drawableChanged(); 2704 } 2705 } 2706 2707 @Override 2708 public void onSystemUiVisibilityChange(int visible) { 2709 mLastSystemUiVisibility = visible; 2710 updateColorViews(null /* insets */); 2711 } 2712 2713 @Override 2714 public WindowInsets onApplyWindowInsets(WindowInsets insets) { 2715 mFrameOffsets.set(insets.getSystemWindowInsets()); 2716 updateColorViews(insets); 2717 insets = updateStatusGuard(insets); 2718 updateNavigationGuard(insets); 2719 if (getForeground() != null) { 2720 drawableChanged(); 2721 } 2722 return insets; 2723 } 2724 2725 @Override 2726 public boolean isTransitionGroup() { 2727 return false; 2728 } 2729 2730 private WindowInsets updateColorViews(WindowInsets insets) { 2731 if (!mIsFloating && ActivityManager.isHighEndGfx()) { 2732 if (insets != null) { 2733 mLastTopInset = insets.getStableInsetTop(); 2734 mLastBottomInset = insets.getStableInsetBottom(); 2735 } 2736 mStatusColorView = updateColorViewInt(mStatusColorView, 2737 SYSTEM_UI_FLAG_FULLSCREEN, FLAG_TRANSLUCENT_STATUS, 2738 mStatusBarColor, mLastTopInset, Gravity.TOP, 2739 STATUS_BAR_BACKGROUND_TRANSITION_NAME); 2740 mNavigationColorView = updateColorViewInt(mNavigationColorView, 2741 SYSTEM_UI_FLAG_HIDE_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION, 2742 mNavigationBarColor, mLastBottomInset, Gravity.BOTTOM, 2743 NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME); 2744 } 2745 if (insets != null) { 2746 insets = insets.consumeStableInsets(); 2747 } 2748 return insets; 2749 } 2750 2751 private View updateColorViewInt(View view, int systemUiHideFlag, int translucentFlag, 2752 int color, int height, int verticalGravity, String transitionName) { 2753 boolean show = height > 0 && (mLastSystemUiVisibility & systemUiHideFlag) == 0 2754 && (getAttributes().flags & translucentFlag) == 0 2755 && (color & Color.BLACK) != 0 2756 && (getAttributes().flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0; 2757 2758 if (view == null) { 2759 if (show) { 2760 view = new View(mContext); 2761 view.setBackgroundColor(color); 2762 view.setTransitionName(transitionName); 2763 addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, height, 2764 Gravity.START | verticalGravity)); 2765 } 2766 } else { 2767 int vis = show ? VISIBLE : INVISIBLE; 2768 view.setVisibility(vis); 2769 if (show) { 2770 LayoutParams lp = (LayoutParams) view.getLayoutParams(); 2771 if (lp.height != height) { 2772 lp.height = height; 2773 view.setLayoutParams(lp); 2774 } 2775 view.setBackgroundColor(color); 2776 } 2777 } 2778 return view; 2779 } 2780 2781 private WindowInsets updateStatusGuard(WindowInsets insets) { 2782 boolean showStatusGuard = false; 2783 // Show the status guard when the non-overlay contextual action bar is showing 2784 if (mActionModeView != null) { 2785 if (mActionModeView.getLayoutParams() instanceof MarginLayoutParams) { 2786 MarginLayoutParams mlp = (MarginLayoutParams) mActionModeView.getLayoutParams(); 2787 boolean mlpChanged = false; 2788 final boolean nonOverlayShown = 2789 (getLocalFeatures() & (1 << FEATURE_ACTION_MODE_OVERLAY)) == 0 2790 && mActionModeView.isShown(); 2791 if (nonOverlayShown) { 2792 // set top margin to top insets, show status guard 2793 if (mlp.topMargin != insets.getSystemWindowInsetTop()) { 2794 mlpChanged = true; 2795 mlp.topMargin = insets.getSystemWindowInsetTop(); 2796 if (mStatusGuard == null) { 2797 mStatusGuard = new View(mContext); 2798 mStatusGuard.setBackgroundColor(mContext.getResources() 2799 .getColor(R.color.input_method_navigation_guard)); 2800 addView(mStatusGuard, indexOfChild(mStatusColorView), 2801 new LayoutParams(LayoutParams.MATCH_PARENT, mlp.topMargin, 2802 Gravity.START | Gravity.TOP)); 2803 } else { 2804 LayoutParams lp = (LayoutParams) mStatusGuard.getLayoutParams(); 2805 if (lp.height != mlp.topMargin) { 2806 lp.height = mlp.topMargin; 2807 mStatusGuard.setLayoutParams(lp); 2808 } 2809 } 2810 } 2811 insets = insets.consumeSystemWindowInsets( 2812 false, true /* top */, false, false); 2813 showStatusGuard = true; 2814 } else { 2815 // reset top margin 2816 if (mlp.topMargin != 0) { 2817 mlpChanged = true; 2818 mlp.topMargin = 0; 2819 } 2820 } 2821 if (mlpChanged) { 2822 mActionModeView.setLayoutParams(mlp); 2823 } 2824 } 2825 } 2826 if (mStatusGuard != null) { 2827 mStatusGuard.setVisibility(showStatusGuard ? View.VISIBLE : View.GONE); 2828 } 2829 return insets; 2830 } 2831 2832 private void updateNavigationGuard(WindowInsets insets) { 2833 // IMEs lay out below the nav bar, but the content view must not (for back compat) 2834 if (getAttributes().type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) { 2835 // prevent the content view from including the nav bar height 2836 if (mContentParent != null) { 2837 if (mContentParent.getLayoutParams() instanceof MarginLayoutParams) { 2838 MarginLayoutParams mlp = 2839 (MarginLayoutParams) mContentParent.getLayoutParams(); 2840 mlp.bottomMargin = insets.getSystemWindowInsetBottom(); 2841 mContentParent.setLayoutParams(mlp); 2842 } 2843 } 2844 // position the navigation guard view, creating it if necessary 2845 if (mNavigationGuard == null) { 2846 mNavigationGuard = new View(mContext); 2847 mNavigationGuard.setBackgroundColor(mContext.getResources() 2848 .getColor(R.color.input_method_navigation_guard)); 2849 addView(mNavigationGuard, indexOfChild(mNavigationColorView), new LayoutParams( 2850 LayoutParams.MATCH_PARENT, insets.getSystemWindowInsetBottom(), 2851 Gravity.START | Gravity.BOTTOM)); 2852 } else { 2853 LayoutParams lp = (LayoutParams) mNavigationGuard.getLayoutParams(); 2854 lp.height = insets.getSystemWindowInsetBottom(); 2855 mNavigationGuard.setLayoutParams(lp); 2856 } 2857 } 2858 } 2859 2860 private void drawableChanged() { 2861 if (mChanging) { 2862 return; 2863 } 2864 2865 setPadding(mFramePadding.left + mBackgroundPadding.left, mFramePadding.top 2866 + mBackgroundPadding.top, mFramePadding.right + mBackgroundPadding.right, 2867 mFramePadding.bottom + mBackgroundPadding.bottom); 2868 requestLayout(); 2869 invalidate(); 2870 2871 int opacity = PixelFormat.OPAQUE; 2872 2873 // Note: if there is no background, we will assume opaque. The 2874 // common case seems to be that an application sets there to be 2875 // no background so it can draw everything itself. For that, 2876 // we would like to assume OPAQUE and let the app force it to 2877 // the slower TRANSLUCENT mode if that is really what it wants. 2878 Drawable bg = getBackground(); 2879 Drawable fg = getForeground(); 2880 if (bg != null) { 2881 if (fg == null) { 2882 opacity = bg.getOpacity(); 2883 } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0 2884 && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) { 2885 // If the frame padding is zero, then we can be opaque 2886 // if either the frame -or- the background is opaque. 2887 int fop = fg.getOpacity(); 2888 int bop = bg.getOpacity(); 2889 if (false) 2890 Log.v(TAG, "Background opacity: " + bop + ", Frame opacity: " + fop); 2891 if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) { 2892 opacity = PixelFormat.OPAQUE; 2893 } else if (fop == PixelFormat.UNKNOWN) { 2894 opacity = bop; 2895 } else if (bop == PixelFormat.UNKNOWN) { 2896 opacity = fop; 2897 } else { 2898 opacity = Drawable.resolveOpacity(fop, bop); 2899 } 2900 } else { 2901 // For now we have to assume translucent if there is a 2902 // frame with padding... there is no way to tell if the 2903 // frame and background together will draw all pixels. 2904 if (false) 2905 Log.v(TAG, "Padding: " + mFramePadding); 2906 opacity = PixelFormat.TRANSLUCENT; 2907 } 2908 } 2909 2910 if (false) 2911 Log.v(TAG, "Background: " + bg + ", Frame: " + fg); 2912 if (false) 2913 Log.v(TAG, "Selected default opacity: " + opacity); 2914 2915 mDefaultOpacity = opacity; 2916 if (mFeatureId < 0) { 2917 setDefaultWindowFormat(opacity); 2918 } 2919 } 2920 2921 @Override 2922 public void onWindowFocusChanged(boolean hasWindowFocus) { 2923 super.onWindowFocusChanged(hasWindowFocus); 2924 2925 // If the user is chording a menu shortcut, release the chord since 2926 // this window lost focus 2927 if (!hasWindowFocus && mPanelChordingKey != 0) { 2928 closePanel(FEATURE_OPTIONS_PANEL); 2929 } 2930 2931 final Callback cb = getCallback(); 2932 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2933 cb.onWindowFocusChanged(hasWindowFocus); 2934 } 2935 } 2936 2937 void updateWindowResizeState() { 2938 Drawable bg = getBackground(); 2939 hackTurnOffWindowResizeAnim(bg == null || bg.getOpacity() 2940 != PixelFormat.OPAQUE); 2941 } 2942 2943 @Override 2944 protected void onAttachedToWindow() { 2945 super.onAttachedToWindow(); 2946 2947 updateWindowResizeState(); 2948 2949 final Callback cb = getCallback(); 2950 if (cb != null && !isDestroyed() && mFeatureId < 0) { 2951 cb.onAttachedToWindow(); 2952 } 2953 2954 if (mFeatureId == -1) { 2955 /* 2956 * The main window has been attached, try to restore any panels 2957 * that may have been open before. This is called in cases where 2958 * an activity is being killed for configuration change and the 2959 * menu was open. When the activity is recreated, the menu 2960 * should be shown again. 2961 */ 2962 openPanelsAfterRestore(); 2963 } 2964 } 2965 2966 @Override 2967 protected void onDetachedFromWindow() { 2968 super.onDetachedFromWindow(); 2969 2970 final Callback cb = getCallback(); 2971 if (cb != null && mFeatureId < 0) { 2972 cb.onDetachedFromWindow(); 2973 } 2974 2975 if (mDecorContentParent != null) { 2976 mDecorContentParent.dismissPopups(); 2977 } 2978 2979 if (mActionModePopup != null) { 2980 removeCallbacks(mShowActionModePopup); 2981 if (mActionModePopup.isShowing()) { 2982 mActionModePopup.dismiss(); 2983 } 2984 mActionModePopup = null; 2985 } 2986 2987 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false); 2988 if (st != null && st.menu != null && mFeatureId < 0) { 2989 st.menu.close(); 2990 } 2991 } 2992 2993 @Override 2994 public void onCloseSystemDialogs(String reason) { 2995 if (mFeatureId >= 0) { 2996 closeAllPanels(); 2997 } 2998 } 2999 3000 public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() { 3001 return mFeatureId < 0 ? mTakeSurfaceCallback : null; 3002 } 3003 3004 public InputQueue.Callback willYouTakeTheInputQueue() { 3005 return mFeatureId < 0 ? mTakeInputQueueCallback : null; 3006 } 3007 3008 public void setSurfaceType(int type) { 3009 PhoneWindow.this.setType(type); 3010 } 3011 3012 public void setSurfaceFormat(int format) { 3013 PhoneWindow.this.setFormat(format); 3014 } 3015 3016 public void setSurfaceKeepScreenOn(boolean keepOn) { 3017 if (keepOn) PhoneWindow.this.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 3018 else PhoneWindow.this.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 3019 } 3020 3021 /** 3022 * Clears out internal reference when the action mode is destroyed. 3023 */ 3024 private class ActionModeCallbackWrapper implements ActionMode.Callback { 3025 private ActionMode.Callback mWrapped; 3026 3027 public ActionModeCallbackWrapper(ActionMode.Callback wrapped) { 3028 mWrapped = wrapped; 3029 } 3030 3031 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 3032 return mWrapped.onCreateActionMode(mode, menu); 3033 } 3034 3035 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 3036 requestFitSystemWindows(); 3037 return mWrapped.onPrepareActionMode(mode, menu); 3038 } 3039 3040 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 3041 return mWrapped.onActionItemClicked(mode, item); 3042 } 3043 3044 public void onDestroyActionMode(ActionMode mode) { 3045 mWrapped.onDestroyActionMode(mode); 3046 if (mActionModePopup != null) { 3047 removeCallbacks(mShowActionModePopup); 3048 mActionModePopup.dismiss(); 3049 } else if (mActionModeView != null) { 3050 mActionModeView.setVisibility(GONE); 3051 } 3052 if (mActionModeView != null) { 3053 mActionModeView.removeAllViews(); 3054 } 3055 if (getCallback() != null && !isDestroyed()) { 3056 try { 3057 getCallback().onActionModeFinished(mActionMode); 3058 } catch (AbstractMethodError ame) { 3059 // Older apps might not implement this callback method. 3060 } 3061 } 3062 mActionMode = null; 3063 requestFitSystemWindows(); 3064 } 3065 } 3066 } 3067 3068 protected DecorView generateDecor() { 3069 return new DecorView(getContext(), -1); 3070 } 3071 3072 protected void setFeatureFromAttrs(int featureId, TypedArray attrs, 3073 int drawableAttr, int alphaAttr) { 3074 Drawable d = attrs.getDrawable(drawableAttr); 3075 if (d != null) { 3076 requestFeature(featureId); 3077 setFeatureDefaultDrawable(featureId, d); 3078 } 3079 if ((getFeatures() & (1 << featureId)) != 0) { 3080 int alpha = attrs.getInt(alphaAttr, -1); 3081 if (alpha >= 0) { 3082 setFeatureDrawableAlpha(featureId, alpha); 3083 } 3084 } 3085 } 3086 3087 protected ViewGroup generateLayout(DecorView decor) { 3088 // Apply data from current theme. 3089 3090 TypedArray a = getWindowStyle(); 3091 3092 if (false) { 3093 System.out.println("From style:"); 3094 String s = "Attrs:"; 3095 for (int i = 0; i < com.android.internal.R.styleable.Window.length; i++) { 3096 s = s + " " + Integer.toHexString(com.android.internal.R.styleable.Window[i]) + "=" 3097 + a.getString(i); 3098 } 3099 System.out.println(s); 3100 } 3101 3102 mIsFloating = a.getBoolean(com.android.internal.R.styleable.Window_windowIsFloating, false); 3103 int flagsToUpdate = (FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR) 3104 & (~getForcedWindowFlags()); 3105 if (mIsFloating) { 3106 setLayout(WRAP_CONTENT, WRAP_CONTENT); 3107 setFlags(0, flagsToUpdate); 3108 } else { 3109 setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate); 3110 } 3111 3112 if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) { 3113 requestFeature(FEATURE_NO_TITLE); 3114 } else if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBar, false)) { 3115 // Don't allow an action bar if there is no title. 3116 requestFeature(FEATURE_ACTION_BAR); 3117 } 3118 3119 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionBarOverlay, false)) { 3120 requestFeature(FEATURE_ACTION_BAR_OVERLAY); 3121 } 3122 3123 if (a.getBoolean(com.android.internal.R.styleable.Window_windowActionModeOverlay, false)) { 3124 requestFeature(FEATURE_ACTION_MODE_OVERLAY); 3125 } 3126 3127 if (a.getBoolean(com.android.internal.R.styleable.Window_windowSwipeToDismiss, false)) { 3128 requestFeature(FEATURE_SWIPE_TO_DISMISS); 3129 } 3130 3131 if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) { 3132 setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags())); 3133 } 3134 3135 if (a.getBoolean(com.android.internal.R.styleable.Window_windowTranslucentStatus, 3136 false)) { 3137 setFlags(FLAG_TRANSLUCENT_STATUS, FLAG_TRANSLUCENT_STATUS 3138 & (~getForcedWindowFlags())); 3139 } 3140 3141 if (a.getBoolean(com.android.internal.R.styleable.Window_windowTranslucentNavigation, 3142 false)) { 3143 setFlags(FLAG_TRANSLUCENT_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION 3144 & (~getForcedWindowFlags())); 3145 } 3146 3147 if (a.getBoolean(com.android.internal.R.styleable.Window_windowOverscan, false)) { 3148 setFlags(FLAG_LAYOUT_IN_OVERSCAN, FLAG_LAYOUT_IN_OVERSCAN&(~getForcedWindowFlags())); 3149 } 3150 3151 if (a.getBoolean(com.android.internal.R.styleable.Window_windowShowWallpaper, false)) { 3152 setFlags(FLAG_SHOW_WALLPAPER, FLAG_SHOW_WALLPAPER&(~getForcedWindowFlags())); 3153 } 3154 3155 if (a.getBoolean(com.android.internal.R.styleable.Window_windowEnableSplitTouch, 3156 getContext().getApplicationInfo().targetSdkVersion 3157 >= android.os.Build.VERSION_CODES.HONEYCOMB)) { 3158 setFlags(FLAG_SPLIT_TOUCH, FLAG_SPLIT_TOUCH&(~getForcedWindowFlags())); 3159 } 3160 3161 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMajor, mMinWidthMajor); 3162 a.getValue(com.android.internal.R.styleable.Window_windowMinWidthMinor, mMinWidthMinor); 3163 if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedWidthMajor)) { 3164 if (mFixedWidthMajor == null) mFixedWidthMajor = new TypedValue(); 3165 a.getValue(com.android.internal.R.styleable.Window_windowFixedWidthMajor, 3166 mFixedWidthMajor); 3167 } 3168 if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedWidthMinor)) { 3169 if (mFixedWidthMinor == null) mFixedWidthMinor = new TypedValue(); 3170 a.getValue(com.android.internal.R.styleable.Window_windowFixedWidthMinor, 3171 mFixedWidthMinor); 3172 } 3173 if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedHeightMajor)) { 3174 if (mFixedHeightMajor == null) mFixedHeightMajor = new TypedValue(); 3175 a.getValue(com.android.internal.R.styleable.Window_windowFixedHeightMajor, 3176 mFixedHeightMajor); 3177 } 3178 if (a.hasValue(com.android.internal.R.styleable.Window_windowFixedHeightMinor)) { 3179 if (mFixedHeightMinor == null) mFixedHeightMinor = new TypedValue(); 3180 a.getValue(com.android.internal.R.styleable.Window_windowFixedHeightMinor, 3181 mFixedHeightMinor); 3182 } 3183 if (a.getBoolean(com.android.internal.R.styleable.Window_windowContentTransitions, false)) { 3184 requestFeature(FEATURE_CONTENT_TRANSITIONS); 3185 } 3186 3187 final WindowManager windowService = (WindowManager) getContext().getSystemService( 3188 Context.WINDOW_SERVICE); 3189 if (windowService != null) { 3190 final Display display = windowService.getDefaultDisplay(); 3191 if (display.getDisplayId() == Display.DEFAULT_DISPLAY && 3192 a.hasValue(com.android.internal.R.styleable.Window_windowOutsetBottom)) { 3193 if (mOutsetBottom == null) mOutsetBottom = new TypedValue(); 3194 a.getValue(com.android.internal.R.styleable.Window_windowOutsetBottom, 3195 mOutsetBottom); 3196 } 3197 } 3198 3199 final Context context = getContext(); 3200 final int targetSdk = context.getApplicationInfo().targetSdkVersion; 3201 final boolean targetPreHoneycomb = targetSdk < android.os.Build.VERSION_CODES.HONEYCOMB; 3202 final boolean targetPreIcs = targetSdk < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; 3203 final boolean targetPreL = targetSdk < android.os.Build.VERSION_CODES.L; 3204 final boolean targetHcNeedsOptions = context.getResources().getBoolean( 3205 com.android.internal.R.bool.target_honeycomb_needs_options_menu); 3206 final boolean noActionBar = !hasFeature(FEATURE_ACTION_BAR) || hasFeature(FEATURE_NO_TITLE); 3207 3208 if (targetPreHoneycomb || (targetPreIcs && targetHcNeedsOptions && noActionBar)) { 3209 addFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY); 3210 } else { 3211 clearFlags(WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY); 3212 } 3213 3214 // Non-floating windows on high end devices must put up decor beneath the system bars and 3215 // therefore must know about visibility changes of those. 3216 if (!mIsFloating && ActivityManager.isHighEndGfx()) { 3217 if (!targetPreL && a.getBoolean( 3218 com.android.internal.R.styleable.Window_windowDrawsSystemBarBackgrounds, 3219 false)) { 3220 setFlags(FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS, 3221 FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS & ~getForcedWindowFlags()); 3222 } 3223 decor.setOnSystemUiVisibilityChangeListener(decor); 3224 } 3225 if (!mForcedStatusBarColor) { 3226 mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000); 3227 } 3228 if (!mForcedNavigationBarColor) { 3229 mNavigationBarColor = a.getColor(R.styleable.Window_navigationBarColor, 0xFF000000); 3230 } 3231 3232 if (mAlwaysReadCloseOnTouchAttr || getContext().getApplicationInfo().targetSdkVersion 3233 >= android.os.Build.VERSION_CODES.HONEYCOMB) { 3234 if (a.getBoolean( 3235 com.android.internal.R.styleable.Window_windowCloseOnTouchOutside, 3236 false)) { 3237 setCloseOnTouchOutsideIfNotSet(true); 3238 } 3239 } 3240 3241 WindowManager.LayoutParams params = getAttributes(); 3242 3243 if (!hasSoftInputMode()) { 3244 params.softInputMode = a.getInt( 3245 com.android.internal.R.styleable.Window_windowSoftInputMode, 3246 params.softInputMode); 3247 } 3248 3249 if (a.getBoolean(com.android.internal.R.styleable.Window_backgroundDimEnabled, 3250 mIsFloating)) { 3251 /* All dialogs should have the window dimmed */ 3252 if ((getForcedWindowFlags()&WindowManager.LayoutParams.FLAG_DIM_BEHIND) == 0) { 3253 params.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; 3254 } 3255 if (!haveDimAmount()) { 3256 params.dimAmount = a.getFloat( 3257 android.R.styleable.Window_backgroundDimAmount, 0.5f); 3258 } 3259 } 3260 3261 if (params.windowAnimations == 0) { 3262 params.windowAnimations = a.getResourceId( 3263 com.android.internal.R.styleable.Window_windowAnimationStyle, 0); 3264 } 3265 3266 // The rest are only done if this window is not embedded; otherwise, 3267 // the values are inherited from our container. 3268 if (getContainer() == null) { 3269 if (mBackgroundDrawable == null) { 3270 if (mBackgroundResource == 0) { 3271 mBackgroundResource = a.getResourceId( 3272 com.android.internal.R.styleable.Window_windowBackground, 0); 3273 } 3274 if (mFrameResource == 0) { 3275 mFrameResource = a.getResourceId(com.android.internal.R.styleable.Window_windowFrame, 0); 3276 } 3277 if (false) { 3278 System.out.println("Background: " 3279 + Integer.toHexString(mBackgroundResource) + " Frame: " 3280 + Integer.toHexString(mFrameResource)); 3281 } 3282 } 3283 mElevation = a.getDimension(com.android.internal.R.styleable.Window_windowElevation, 0); 3284 mTextColor = a.getColor(com.android.internal.R.styleable.Window_textColor, 0xFF000000); 3285 } 3286 3287 // Inflate the window decor. 3288 3289 int layoutResource; 3290 int features = getLocalFeatures(); 3291 // System.out.println("Features: 0x" + Integer.toHexString(features)); 3292 if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) { 3293 layoutResource = com.android.internal.R.layout.screen_swipe_dismiss; 3294 } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) { 3295 if (mIsFloating) { 3296 TypedValue res = new TypedValue(); 3297 getContext().getTheme().resolveAttribute( 3298 com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true); 3299 layoutResource = res.resourceId; 3300 } else { 3301 layoutResource = com.android.internal.R.layout.screen_title_icons; 3302 } 3303 // XXX Remove this once action bar supports these features. 3304 removeFeature(FEATURE_ACTION_BAR); 3305 // System.out.println("Title Icons!"); 3306 } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0 3307 && (features & (1 << FEATURE_ACTION_BAR)) == 0) { 3308 // Special case for a window with only a progress bar (and title). 3309 // XXX Need to have a no-title version of embedded windows. 3310 layoutResource = com.android.internal.R.layout.screen_progress; 3311 // System.out.println("Progress!"); 3312 } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) { 3313 // Special case for a window with a custom title. 3314 // If the window is floating, we need a dialog layout 3315 if (mIsFloating) { 3316 TypedValue res = new TypedValue(); 3317 getContext().getTheme().resolveAttribute( 3318 com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true); 3319 layoutResource = res.resourceId; 3320 } else { 3321 layoutResource = com.android.internal.R.layout.screen_custom_title; 3322 } 3323 // XXX Remove this once action bar supports these features. 3324 removeFeature(FEATURE_ACTION_BAR); 3325 } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) { 3326 // If no other features and not embedded, only need a title. 3327 // If the window is floating, we need a dialog layout 3328 if (mIsFloating) { 3329 TypedValue res = new TypedValue(); 3330 getContext().getTheme().resolveAttribute( 3331 com.android.internal.R.attr.dialogTitleDecorLayout, res, true); 3332 layoutResource = res.resourceId; 3333 } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) { 3334 layoutResource = a.getResourceId( 3335 com.android.internal.R.styleable.Window_windowActionBarFullscreenDecorLayout, 3336 com.android.internal.R.layout.screen_action_bar); 3337 } else { 3338 layoutResource = com.android.internal.R.layout.screen_title; 3339 } 3340 // System.out.println("Title!"); 3341 } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) { 3342 layoutResource = com.android.internal.R.layout.screen_simple_overlay_action_mode; 3343 } else { 3344 // Embedded, so no decoration is needed. 3345 layoutResource = com.android.internal.R.layout.screen_simple; 3346 // System.out.println("Simple!"); 3347 } 3348 3349 mDecor.startChanging(); 3350 3351 View in = mLayoutInflater.inflate(layoutResource, null); 3352 decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); 3353 3354 ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT); 3355 if (contentParent == null) { 3356 throw new RuntimeException("Window couldn't find content container view"); 3357 } 3358 3359 if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) { 3360 ProgressBar progress = getCircularProgressBar(false); 3361 if (progress != null) { 3362 progress.setIndeterminate(true); 3363 } 3364 } 3365 3366 if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) { 3367 registerSwipeCallbacks(); 3368 } 3369 3370 // Remaining setup -- of background and title -- that only applies 3371 // to top-level windows. 3372 if (getContainer() == null) { 3373 final Drawable background; 3374 if (mBackgroundResource != 0) { 3375 background = getContext().getDrawable(mBackgroundResource); 3376 } else { 3377 background = mBackgroundDrawable; 3378 } 3379 mDecor.setWindowBackground(background); 3380 3381 final Drawable frame; 3382 if (mFrameResource != 0) { 3383 frame = getContext().getDrawable(mFrameResource); 3384 } else { 3385 frame = null; 3386 } 3387 mDecor.setWindowFrame(frame); 3388 3389 mDecor.setElevation(mElevation); 3390 3391 if (mTitle != null) { 3392 setTitle(mTitle); 3393 } 3394 3395 if (mTitleColor == 0) { 3396 mTitleColor = mTextColor; 3397 } 3398 setTitleColor(mTitleColor); 3399 } 3400 3401 mDecor.finishChanging(); 3402 3403 return contentParent; 3404 } 3405 3406 /** @hide */ 3407 public void alwaysReadCloseOnTouchAttr() { 3408 mAlwaysReadCloseOnTouchAttr = true; 3409 } 3410 3411 private void installDecor() { 3412 if (mDecor == null) { 3413 mDecor = generateDecor(); 3414 mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); 3415 mDecor.setIsRootNamespace(true); 3416 if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) { 3417 mDecor.postOnAnimation(mInvalidatePanelMenuRunnable); 3418 } 3419 } 3420 if (mContentParent == null) { 3421 mContentParent = generateLayout(mDecor); 3422 3423 // Set up decor part of UI to ignore fitsSystemWindows if appropriate. 3424 mDecor.makeOptionalFitsSystemWindows(); 3425 3426 final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById( 3427 com.android.internal.R.id.decor_content_parent); 3428 3429 if (decorContentParent != null) { 3430 mDecorContentParent = decorContentParent; 3431 mDecorContentParent.setWindowCallback(getCallback()); 3432 if (mDecorContentParent.getTitle() == null) { 3433 mDecorContentParent.setWindowTitle(mTitle); 3434 } 3435 3436 final int localFeatures = getLocalFeatures(); 3437 for (int i = 0; i < FEATURE_MAX; i++) { 3438 if ((localFeatures & (1 << i)) != 0) { 3439 mDecorContentParent.initFeature(i); 3440 } 3441 } 3442 3443 mDecorContentParent.setUiOptions(mUiOptions); 3444 3445 if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) != 0 || 3446 (mIconRes != 0 && !mDecorContentParent.hasIcon())) { 3447 mDecorContentParent.setIcon(mIconRes); 3448 } else if ((mResourcesSetFlags & FLAG_RESOURCE_SET_ICON) == 0 && 3449 mIconRes == 0 && !mDecorContentParent.hasIcon()) { 3450 mDecorContentParent.setIcon( 3451 getContext().getPackageManager().getDefaultActivityIcon()); 3452 mResourcesSetFlags |= FLAG_RESOURCE_SET_ICON_FALLBACK; 3453 } 3454 if ((mResourcesSetFlags & FLAG_RESOURCE_SET_LOGO) != 0 || 3455 (mLogoRes != 0 && !mDecorContentParent.hasLogo())) { 3456 mDecorContentParent.setLogo(mLogoRes); 3457 } 3458 3459 // Post the panel invalidate for later; avoid application onCreateOptionsMenu 3460 // being called in the middle of onCreate or similar. 3461 mDecor.post(new Runnable() { 3462 public void run() { 3463 // Invalidate if the panel menu hasn't been created before this. 3464 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false); 3465 if (!isDestroyed() && (st == null || st.menu == null)) { 3466 invalidatePanelMenu(FEATURE_ACTION_BAR); 3467 } 3468 } 3469 }); 3470 } else { 3471 mTitleView = (TextView)findViewById(com.android.internal.R.id.title); 3472 if (mTitleView != null) { 3473 mTitleView.setLayoutDirection(mDecor.getLayoutDirection()); 3474 if ((getLocalFeatures() & (1 << FEATURE_NO_TITLE)) != 0) { 3475 View titleContainer = findViewById( 3476 com.android.internal.R.id.title_container); 3477 if (titleContainer != null) { 3478 titleContainer.setVisibility(View.GONE); 3479 } else { 3480 mTitleView.setVisibility(View.GONE); 3481 } 3482 if (mContentParent instanceof FrameLayout) { 3483 ((FrameLayout)mContentParent).setForeground(null); 3484 } 3485 } else { 3486 mTitleView.setText(mTitle); 3487 } 3488 } 3489 } 3490 3491 // Only inflate or create a new TransitionManager if the caller hasn't 3492 // already set a custom one. 3493 if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) { 3494 if (mTransitionManager == null) { 3495 final int transitionRes = getWindowStyle().getResourceId( 3496 com.android.internal.R.styleable.Window_windowContentTransitionManager, 3497 0); 3498 if (transitionRes != 0) { 3499 final TransitionInflater inflater = TransitionInflater.from(getContext()); 3500 mTransitionManager = inflater.inflateTransitionManager(transitionRes, 3501 mContentParent); 3502 } else { 3503 mTransitionManager = new TransitionManager(); 3504 } 3505 } 3506 3507 mEnterTransition = getTransition(mEnterTransition, 3508 com.android.internal.R.styleable.Window_windowEnterTransition); 3509 mExitTransition = getTransition(mExitTransition, 3510 com.android.internal.R.styleable.Window_windowExitTransition); 3511 mSharedElementEnterTransition = getTransition(mSharedElementEnterTransition, 3512 com.android.internal.R.styleable.Window_windowSharedElementEnterTransition); 3513 mSharedElementExitTransition = getTransition(mSharedElementExitTransition, 3514 com.android.internal.R.styleable.Window_windowSharedElementExitTransition); 3515 if (mAllowEnterTransitionOverlap == null) { 3516 mAllowEnterTransitionOverlap = getWindowStyle().getBoolean( 3517 com.android.internal.R.styleable. 3518 Window_windowAllowEnterTransitionOverlap, true); 3519 } 3520 if (mAllowExitTransitionOverlap == null) { 3521 mAllowExitTransitionOverlap = getWindowStyle().getBoolean( 3522 com.android.internal.R.styleable. 3523 Window_windowAllowExitTransitionOverlap, true); 3524 } 3525 if (mBackgroundFadeDurationMillis < 0) { 3526 mBackgroundFadeDurationMillis = getWindowStyle().getInteger( 3527 com.android.internal.R.styleable. 3528 Window_windowTransitionBackgroundFadeDuration, 3529 DEFAULT_BACKGROUND_FADE_DURATION_MS); 3530 } 3531 } 3532 } 3533 } 3534 3535 private Transition getTransition(Transition currentValue, int id) { 3536 if (currentValue != null) { 3537 return currentValue; 3538 } 3539 int transitionId = getWindowStyle().getResourceId(id, -1); 3540 Transition transition = null; 3541 if (transitionId != -1 && transitionId != com.android.internal.R.transition.no_transition) { 3542 TransitionInflater inflater = TransitionInflater.from(getContext()); 3543 transition = inflater.inflateTransition(transitionId); 3544 } 3545 return transition; 3546 } 3547 3548 private Drawable loadImageURI(Uri uri) { 3549 try { 3550 return Drawable.createFromStream( 3551 getContext().getContentResolver().openInputStream(uri), null); 3552 } catch (Exception e) { 3553 Log.w(TAG, "Unable to open content: " + uri); 3554 } 3555 return null; 3556 } 3557 3558 private DrawableFeatureState getDrawableState(int featureId, boolean required) { 3559 if ((getFeatures() & (1 << featureId)) == 0) { 3560 if (!required) { 3561 return null; 3562 } 3563 throw new RuntimeException("The feature has not been requested"); 3564 } 3565 3566 DrawableFeatureState[] ar; 3567 if ((ar = mDrawables) == null || ar.length <= featureId) { 3568 DrawableFeatureState[] nar = new DrawableFeatureState[featureId + 1]; 3569 if (ar != null) { 3570 System.arraycopy(ar, 0, nar, 0, ar.length); 3571 } 3572 mDrawables = ar = nar; 3573 } 3574 3575 DrawableFeatureState st = ar[featureId]; 3576 if (st == null) { 3577 ar[featureId] = st = new DrawableFeatureState(featureId); 3578 } 3579 return st; 3580 } 3581 3582 /** 3583 * Gets a panel's state based on its feature ID. 3584 * 3585 * @param featureId The feature ID of the panel. 3586 * @param required Whether the panel is required (if it is required and it 3587 * isn't in our features, this throws an exception). 3588 * @return The panel state. 3589 */ 3590 private PanelFeatureState getPanelState(int featureId, boolean required) { 3591 return getPanelState(featureId, required, null); 3592 } 3593 3594 /** 3595 * Gets a panel's state based on its feature ID. 3596 * 3597 * @param featureId The feature ID of the panel. 3598 * @param required Whether the panel is required (if it is required and it 3599 * isn't in our features, this throws an exception). 3600 * @param convertPanelState Optional: If the panel state does not exist, use 3601 * this as the panel state. 3602 * @return The panel state. 3603 */ 3604 private PanelFeatureState getPanelState(int featureId, boolean required, 3605 PanelFeatureState convertPanelState) { 3606 if ((getFeatures() & (1 << featureId)) == 0) { 3607 if (!required) { 3608 return null; 3609 } 3610 throw new RuntimeException("The feature has not been requested"); 3611 } 3612 3613 PanelFeatureState[] ar; 3614 if ((ar = mPanels) == null || ar.length <= featureId) { 3615 PanelFeatureState[] nar = new PanelFeatureState[featureId + 1]; 3616 if (ar != null) { 3617 System.arraycopy(ar, 0, nar, 0, ar.length); 3618 } 3619 mPanels = ar = nar; 3620 } 3621 3622 PanelFeatureState st = ar[featureId]; 3623 if (st == null) { 3624 ar[featureId] = st = (convertPanelState != null) 3625 ? convertPanelState 3626 : new PanelFeatureState(featureId); 3627 } 3628 return st; 3629 } 3630 3631 @Override 3632 public final void setChildDrawable(int featureId, Drawable drawable) { 3633 DrawableFeatureState st = getDrawableState(featureId, true); 3634 st.child = drawable; 3635 updateDrawable(featureId, st, false); 3636 } 3637 3638 @Override 3639 public final void setChildInt(int featureId, int value) { 3640 updateInt(featureId, value, false); 3641 } 3642 3643 @Override 3644 public boolean isShortcutKey(int keyCode, KeyEvent event) { 3645 PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, true); 3646 return st.menu != null && st.menu.isShortcutKey(keyCode, event); 3647 } 3648 3649 private void updateDrawable(int featureId, DrawableFeatureState st, boolean fromResume) { 3650 // Do nothing if the decor is not yet installed... an update will 3651 // need to be forced when we eventually become active. 3652 if (mContentParent == null) { 3653 return; 3654 } 3655 3656 final int featureMask = 1 << featureId; 3657 3658 if ((getFeatures() & featureMask) == 0 && !fromResume) { 3659 return; 3660 } 3661 3662 Drawable drawable = null; 3663 if (st != null) { 3664 drawable = st.child; 3665 if (drawable == null) 3666 drawable = st.local; 3667 if (drawable == null) 3668 drawable = st.def; 3669 } 3670 if ((getLocalFeatures() & featureMask) == 0) { 3671 if (getContainer() != null) { 3672 if (isActive() || fromResume) { 3673 getContainer().setChildDrawable(featureId, drawable); 3674 } 3675 } 3676 } else if (st != null && (st.cur != drawable || st.curAlpha != st.alpha)) { 3677 // System.out.println("Drawable changed: old=" + st.cur 3678 // + ", new=" + drawable); 3679 st.cur = drawable; 3680 st.curAlpha = st.alpha; 3681 onDrawableChanged(featureId, drawable, st.alpha); 3682 } 3683 } 3684 3685 private void updateInt(int featureId, int value, boolean fromResume) { 3686 3687 // Do nothing if the decor is not yet installed... an update will 3688 // need to be forced when we eventually become active. 3689 if (mContentParent == null) { 3690 return; 3691 } 3692 3693 final int featureMask = 1 << featureId; 3694 3695 if ((getFeatures() & featureMask) == 0 && !fromResume) { 3696 return; 3697 } 3698 3699 if ((getLocalFeatures() & featureMask) == 0) { 3700 if (getContainer() != null) { 3701 getContainer().setChildInt(featureId, value); 3702 } 3703 } else { 3704 onIntChanged(featureId, value); 3705 } 3706 } 3707 3708 private ImageView getLeftIconView() { 3709 if (mLeftIconView != null) { 3710 return mLeftIconView; 3711 } 3712 if (mContentParent == null) { 3713 installDecor(); 3714 } 3715 return (mLeftIconView = (ImageView)findViewById(com.android.internal.R.id.left_icon)); 3716 } 3717 3718 @Override 3719 protected void dispatchWindowAttributesChanged(WindowManager.LayoutParams attrs) { 3720 super.dispatchWindowAttributesChanged(attrs); 3721 if (mDecor != null) { 3722 mDecor.updateColorViews(null /* insets */); 3723 } 3724 } 3725 3726 private ProgressBar getCircularProgressBar(boolean shouldInstallDecor) { 3727 if (mCircularProgressBar != null) { 3728 return mCircularProgressBar; 3729 } 3730 if (mContentParent == null && shouldInstallDecor) { 3731 installDecor(); 3732 } 3733 mCircularProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_circular); 3734 if (mCircularProgressBar != null) { 3735 mCircularProgressBar.setVisibility(View.INVISIBLE); 3736 } 3737 return mCircularProgressBar; 3738 } 3739 3740 private ProgressBar getHorizontalProgressBar(boolean shouldInstallDecor) { 3741 if (mHorizontalProgressBar != null) { 3742 return mHorizontalProgressBar; 3743 } 3744 if (mContentParent == null && shouldInstallDecor) { 3745 installDecor(); 3746 } 3747 mHorizontalProgressBar = (ProgressBar) findViewById(com.android.internal.R.id.progress_horizontal); 3748 if (mHorizontalProgressBar != null) { 3749 mHorizontalProgressBar.setVisibility(View.INVISIBLE); 3750 } 3751 return mHorizontalProgressBar; 3752 } 3753 3754 private ImageView getRightIconView() { 3755 if (mRightIconView != null) { 3756 return mRightIconView; 3757 } 3758 if (mContentParent == null) { 3759 installDecor(); 3760 } 3761 return (mRightIconView = (ImageView)findViewById(com.android.internal.R.id.right_icon)); 3762 } 3763 3764 private void registerSwipeCallbacks() { 3765 SwipeDismissLayout swipeDismiss = 3766 (SwipeDismissLayout) findViewById(com.android.internal.R.id.content); 3767 swipeDismiss.setOnDismissedListener(new SwipeDismissLayout.OnDismissedListener() { 3768 @Override 3769 public void onDismissed(SwipeDismissLayout layout) { 3770 dispatchOnWindowDismissed(); 3771 } 3772 }); 3773 swipeDismiss.setOnSwipeProgressChangedListener( 3774 new SwipeDismissLayout.OnSwipeProgressChangedListener() { 3775 private static final float ALPHA_DECREASE = 0.5f; 3776 private boolean mIsTranslucent = false; 3777 @Override 3778 public void onSwipeProgressChanged( 3779 SwipeDismissLayout layout, float progress, float translate) { 3780 WindowManager.LayoutParams newParams = getAttributes(); 3781 newParams.x = (int) translate; 3782 newParams.alpha = 1 - (progress * ALPHA_DECREASE); 3783 setAttributes(newParams); 3784 3785 int flags = 0; 3786 if (newParams.x == 0) { 3787 flags = FLAG_FULLSCREEN; 3788 } else { 3789 flags = FLAG_LAYOUT_NO_LIMITS; 3790 } 3791 setFlags(flags, FLAG_FULLSCREEN | FLAG_LAYOUT_NO_LIMITS); 3792 } 3793 3794 @Override 3795 public void onSwipeCancelled(SwipeDismissLayout layout) { 3796 WindowManager.LayoutParams newParams = getAttributes(); 3797 newParams.x = 0; 3798 newParams.alpha = 1; 3799 setAttributes(newParams); 3800 setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN | FLAG_LAYOUT_NO_LIMITS); 3801 } 3802 }); 3803 } 3804 3805 /** 3806 * Helper method for calling the {@link Callback#onPanelClosed(int, Menu)} 3807 * callback. This method will grab whatever extra state is needed for the 3808 * callback that isn't given in the parameters. If the panel is not open, 3809 * this will not perform the callback. 3810 * 3811 * @param featureId Feature ID of the panel that was closed. Must be given. 3812 * @param panel Panel that was closed. Optional but useful if there is no 3813 * menu given. 3814 * @param menu The menu that was closed. Optional, but give if you have. 3815 */ 3816 private void callOnPanelClosed(int featureId, PanelFeatureState panel, Menu menu) { 3817 final Callback cb = getCallback(); 3818 if (cb == null) 3819 return; 3820 3821 // Try to get a menu 3822 if (menu == null) { 3823 // Need a panel to grab the menu, so try to get that 3824 if (panel == null) { 3825 if ((featureId >= 0) && (featureId < mPanels.length)) { 3826 panel = mPanels[featureId]; 3827 } 3828 } 3829 3830 if (panel != null) { 3831 // menu still may be null, which is okay--we tried our best 3832 menu = panel.menu; 3833 } 3834 } 3835 3836 // If the panel is not open, do not callback 3837 if ((panel != null) && (!panel.isOpen)) 3838 return; 3839 3840 if (!isDestroyed()) { 3841 cb.onPanelClosed(featureId, menu); 3842 } 3843 } 3844 3845 /** 3846 * Helper method for adding launch-search to most applications. Opens the 3847 * search window using default settings. 3848 * 3849 * @return true if search window opened 3850 */ 3851 private boolean launchDefaultSearch() { 3852 final Callback cb = getCallback(); 3853 if (cb == null || isDestroyed()) { 3854 return false; 3855 } else { 3856 sendCloseSystemWindows("search"); 3857 return cb.onSearchRequested(); 3858 } 3859 } 3860 3861 @Override 3862 public void setVolumeControlStream(int streamType) { 3863 mVolumeControlStreamType = streamType; 3864 } 3865 3866 @Override 3867 public int getVolumeControlStream() { 3868 return mVolumeControlStreamType; 3869 } 3870 3871 @Override 3872 public void setMediaController(MediaController controller) { 3873 mMediaController = controller; 3874 } 3875 3876 @Override 3877 public MediaController getMediaController() { 3878 return mMediaController; 3879 } 3880 3881 private boolean isTranslucent() { 3882 TypedArray a = getWindowStyle(); 3883 return a.getBoolean(a.getResourceId( 3884 com.android.internal.R.styleable.Window_windowIsTranslucent, 0), false); 3885 } 3886 3887 @Override 3888 public void setEnterTransition(Transition enterTransition) { 3889 mEnterTransition = enterTransition; 3890 } 3891 3892 @Override 3893 public void setExitTransition(Transition exitTransition) { 3894 mExitTransition = exitTransition; 3895 } 3896 3897 @Override 3898 public void setSharedElementEnterTransition(Transition sharedElementEnterTransition) { 3899 mSharedElementEnterTransition = sharedElementEnterTransition; 3900 } 3901 3902 @Override 3903 public void setSharedElementExitTransition(Transition sharedElementExitTransition) { 3904 mSharedElementExitTransition = sharedElementExitTransition; 3905 } 3906 3907 @Override 3908 public Transition getEnterTransition() { 3909 return mEnterTransition; 3910 } 3911 3912 @Override 3913 public Transition getExitTransition() { 3914 return mExitTransition; 3915 } 3916 3917 @Override 3918 public Transition getSharedElementEnterTransition() { 3919 return mSharedElementEnterTransition; 3920 } 3921 3922 @Override 3923 public Transition getSharedElementExitTransition() { 3924 return mSharedElementExitTransition; 3925 } 3926 3927 @Override 3928 public void setAllowEnterTransitionOverlap(boolean allow) { 3929 mAllowEnterTransitionOverlap = allow; 3930 } 3931 3932 @Override 3933 public boolean getAllowEnterTransitionOverlap() { 3934 return (mAllowEnterTransitionOverlap == null) ? true : mAllowEnterTransitionOverlap; 3935 } 3936 3937 @Override 3938 public void setAllowExitTransitionOverlap(boolean allowExitTransitionOverlap) { 3939 mAllowExitTransitionOverlap = allowExitTransitionOverlap; 3940 } 3941 3942 @Override 3943 public boolean getAllowExitTransitionOverlap() { 3944 return (mAllowExitTransitionOverlap == null) ? true : mAllowExitTransitionOverlap; 3945 } 3946 3947 @Override 3948 public long getTransitionBackgroundFadeDuration() { 3949 return (mBackgroundFadeDurationMillis < 0) ? DEFAULT_BACKGROUND_FADE_DURATION_MS 3950 : mBackgroundFadeDurationMillis; 3951 } 3952 3953 @Override 3954 public void setTransitionBackgroundFadeDuration(long fadeDurationMillis) { 3955 if (fadeDurationMillis < 0) { 3956 throw new IllegalArgumentException("negative durations are not allowed"); 3957 } 3958 mBackgroundFadeDurationMillis = fadeDurationMillis; 3959 } 3960 3961 private static final class DrawableFeatureState { 3962 DrawableFeatureState(int _featureId) { 3963 featureId = _featureId; 3964 } 3965 3966 final int featureId; 3967 3968 int resid; 3969 3970 Uri uri; 3971 3972 Drawable local; 3973 3974 Drawable child; 3975 3976 Drawable def; 3977 3978 Drawable cur; 3979 3980 int alpha = 255; 3981 3982 int curAlpha = 255; 3983 } 3984 3985 private static final class PanelFeatureState { 3986 3987 /** Feature ID for this panel. */ 3988 int featureId; 3989 3990 // Information pulled from the style for this panel. 3991 3992 int background; 3993 3994 /** The background when the panel spans the entire available width. */ 3995 int fullBackground; 3996 3997 int gravity; 3998 3999 int x; 4000 4001 int y; 4002 4003 int windowAnimations; 4004 4005 /** Dynamic state of the panel. */ 4006 DecorView decorView; 4007 4008 /** The panel that was returned by onCreatePanelView(). */ 4009 View createdPanelView; 4010 4011 /** The panel that we are actually showing. */ 4012 View shownPanelView; 4013 4014 /** Use {@link #setMenu} to set this. */ 4015 MenuBuilder menu; 4016 4017 IconMenuPresenter iconMenuPresenter; 4018 ListMenuPresenter listMenuPresenter; 4019 4020 /** true if this menu will show in single-list compact mode */ 4021 boolean isCompact; 4022 4023 /** Theme resource ID for list elements of the panel menu */ 4024 int listPresenterTheme; 4025 4026 /** 4027 * Whether the panel has been prepared (see 4028 * {@link PhoneWindow#preparePanel}). 4029 */ 4030 boolean isPrepared; 4031 4032 /** 4033 * Whether an item's action has been performed. This happens in obvious 4034 * scenarios (user clicks on menu item), but can also happen with 4035 * chording menu+(shortcut key). 4036 */ 4037 boolean isHandled; 4038 4039 boolean isOpen; 4040 4041 /** 4042 * True if the menu is in expanded mode, false if the menu is in icon 4043 * mode 4044 */ 4045 boolean isInExpandedMode; 4046 4047 public boolean qwertyMode; 4048 4049 boolean refreshDecorView; 4050 4051 boolean refreshMenuContent; 4052 4053 boolean wasLastOpen; 4054 4055 boolean wasLastExpanded; 4056 4057 /** 4058 * Contains the state of the menu when told to freeze. 4059 */ 4060 Bundle frozenMenuState; 4061 4062 /** 4063 * Contains the state of associated action views when told to freeze. 4064 * These are saved across invalidations. 4065 */ 4066 Bundle frozenActionViewState; 4067 4068 PanelFeatureState(int featureId) { 4069 this.featureId = featureId; 4070 4071 refreshDecorView = false; 4072 } 4073 4074 public boolean isInListMode() { 4075 return isInExpandedMode || isCompact; 4076 } 4077 4078 public boolean hasPanelItems() { 4079 if (shownPanelView == null) return false; 4080 if (createdPanelView != null) return true; 4081 4082 if (isCompact || isInExpandedMode) { 4083 return listMenuPresenter.getAdapter().getCount() > 0; 4084 } else { 4085 return ((ViewGroup) shownPanelView).getChildCount() > 0; 4086 } 4087 } 4088 4089 /** 4090 * Unregister and free attached MenuPresenters. They will be recreated as needed. 4091 */ 4092 public void clearMenuPresenters() { 4093 if (menu != null) { 4094 menu.removeMenuPresenter(iconMenuPresenter); 4095 menu.removeMenuPresenter(listMenuPresenter); 4096 } 4097 iconMenuPresenter = null; 4098 listMenuPresenter = null; 4099 } 4100 4101 void setStyle(Context context) { 4102 TypedArray a = context.obtainStyledAttributes(com.android.internal.R.styleable.Theme); 4103 background = a.getResourceId( 4104 com.android.internal.R.styleable.Theme_panelBackground, 0); 4105 fullBackground = a.getResourceId( 4106 com.android.internal.R.styleable.Theme_panelFullBackground, 0); 4107 windowAnimations = a.getResourceId( 4108 com.android.internal.R.styleable.Theme_windowAnimationStyle, 0); 4109 isCompact = a.getBoolean( 4110 com.android.internal.R.styleable.Theme_panelMenuIsCompact, false); 4111 listPresenterTheme = a.getResourceId( 4112 com.android.internal.R.styleable.Theme_panelMenuListTheme, 4113 com.android.internal.R.style.Theme_ExpandedMenu); 4114 a.recycle(); 4115 } 4116 4117 void setMenu(MenuBuilder menu) { 4118 if (menu == this.menu) return; 4119 4120 if (this.menu != null) { 4121 this.menu.removeMenuPresenter(iconMenuPresenter); 4122 this.menu.removeMenuPresenter(listMenuPresenter); 4123 } 4124 this.menu = menu; 4125 if (menu != null) { 4126 if (iconMenuPresenter != null) menu.addMenuPresenter(iconMenuPresenter); 4127 if (listMenuPresenter != null) menu.addMenuPresenter(listMenuPresenter); 4128 } 4129 } 4130 4131 MenuView getListMenuView(Context context, MenuPresenter.Callback cb) { 4132 if (menu == null) return null; 4133 4134 if (!isCompact) { 4135 getIconMenuView(context, cb); // Need this initialized to know where our offset goes 4136 } 4137 4138 if (listMenuPresenter == null) { 4139 listMenuPresenter = new ListMenuPresenter( 4140 com.android.internal.R.layout.list_menu_item_layout, listPresenterTheme); 4141 listMenuPresenter.setCallback(cb); 4142 listMenuPresenter.setId(com.android.internal.R.id.list_menu_presenter); 4143 menu.addMenuPresenter(listMenuPresenter); 4144 } 4145 4146 if (iconMenuPresenter != null) { 4147 listMenuPresenter.setItemIndexOffset( 4148 iconMenuPresenter.getNumActualItemsShown()); 4149 } 4150 MenuView result = listMenuPresenter.getMenuView(decorView); 4151 4152 return result; 4153 } 4154 4155 MenuView getIconMenuView(Context context, MenuPresenter.Callback cb) { 4156 if (menu == null) return null; 4157 4158 if (iconMenuPresenter == null) { 4159 iconMenuPresenter = new IconMenuPresenter(context); 4160 iconMenuPresenter.setCallback(cb); 4161 iconMenuPresenter.setId(com.android.internal.R.id.icon_menu_presenter); 4162 menu.addMenuPresenter(iconMenuPresenter); 4163 } 4164 4165 MenuView result = iconMenuPresenter.getMenuView(decorView); 4166 4167 return result; 4168 } 4169 4170 Parcelable onSaveInstanceState() { 4171 SavedState savedState = new SavedState(); 4172 savedState.featureId = featureId; 4173 savedState.isOpen = isOpen; 4174 savedState.isInExpandedMode = isInExpandedMode; 4175 4176 if (menu != null) { 4177 savedState.menuState = new Bundle(); 4178 menu.savePresenterStates(savedState.menuState); 4179 } 4180 4181 return savedState; 4182 } 4183 4184 void onRestoreInstanceState(Parcelable state) { 4185 SavedState savedState = (SavedState) state; 4186 featureId = savedState.featureId; 4187 wasLastOpen = savedState.isOpen; 4188 wasLastExpanded = savedState.isInExpandedMode; 4189 frozenMenuState = savedState.menuState; 4190 4191 /* 4192 * A LocalActivityManager keeps the same instance of this class around. 4193 * The first time the menu is being shown after restoring, the 4194 * Activity.onCreateOptionsMenu should be called. But, if it is the 4195 * same instance then menu != null and we won't call that method. 4196 * We clear any cached views here. The caller should invalidatePanelMenu. 4197 */ 4198 createdPanelView = null; 4199 shownPanelView = null; 4200 decorView = null; 4201 } 4202 4203 void applyFrozenState() { 4204 if (menu != null && frozenMenuState != null) { 4205 menu.restorePresenterStates(frozenMenuState); 4206 frozenMenuState = null; 4207 } 4208 } 4209 4210 private static class SavedState implements Parcelable { 4211 int featureId; 4212 boolean isOpen; 4213 boolean isInExpandedMode; 4214 Bundle menuState; 4215 4216 public int describeContents() { 4217 return 0; 4218 } 4219 4220 public void writeToParcel(Parcel dest, int flags) { 4221 dest.writeInt(featureId); 4222 dest.writeInt(isOpen ? 1 : 0); 4223 dest.writeInt(isInExpandedMode ? 1 : 0); 4224 4225 if (isOpen) { 4226 dest.writeBundle(menuState); 4227 } 4228 } 4229 4230 private static SavedState readFromParcel(Parcel source) { 4231 SavedState savedState = new SavedState(); 4232 savedState.featureId = source.readInt(); 4233 savedState.isOpen = source.readInt() == 1; 4234 savedState.isInExpandedMode = source.readInt() == 1; 4235 4236 if (savedState.isOpen) { 4237 savedState.menuState = source.readBundle(); 4238 } 4239 4240 return savedState; 4241 } 4242 4243 public static final Parcelable.Creator<SavedState> CREATOR 4244 = new Parcelable.Creator<SavedState>() { 4245 public SavedState createFromParcel(Parcel in) { 4246 return readFromParcel(in); 4247 } 4248 4249 public SavedState[] newArray(int size) { 4250 return new SavedState[size]; 4251 } 4252 }; 4253 } 4254 4255 } 4256 4257 static class RotationWatcher extends IRotationWatcher.Stub { 4258 private Handler mHandler; 4259 private final Runnable mRotationChanged = new Runnable() { 4260 public void run() { 4261 dispatchRotationChanged(); 4262 } 4263 }; 4264 private final ArrayList<WeakReference<PhoneWindow>> mWindows = 4265 new ArrayList<WeakReference<PhoneWindow>>(); 4266 private boolean mIsWatching; 4267 4268 @Override 4269 public void onRotationChanged(int rotation) throws RemoteException { 4270 mHandler.post(mRotationChanged); 4271 } 4272 4273 public void addWindow(PhoneWindow phoneWindow) { 4274 synchronized (mWindows) { 4275 if (!mIsWatching) { 4276 try { 4277 WindowManagerHolder.sWindowManager.watchRotation(this); 4278 mHandler = new Handler(); 4279 mIsWatching = true; 4280 } catch (RemoteException ex) { 4281 Log.e(TAG, "Couldn't start watching for device rotation", ex); 4282 } 4283 } 4284 mWindows.add(new WeakReference<PhoneWindow>(phoneWindow)); 4285 } 4286 } 4287 4288 public void removeWindow(PhoneWindow phoneWindow) { 4289 synchronized (mWindows) { 4290 int i = 0; 4291 while (i < mWindows.size()) { 4292 final WeakReference<PhoneWindow> ref = mWindows.get(i); 4293 final PhoneWindow win = ref.get(); 4294 if (win == null || win == phoneWindow) { 4295 mWindows.remove(i); 4296 } else { 4297 i++; 4298 } 4299 } 4300 } 4301 } 4302 4303 void dispatchRotationChanged() { 4304 synchronized (mWindows) { 4305 int i = 0; 4306 while (i < mWindows.size()) { 4307 final WeakReference<PhoneWindow> ref = mWindows.get(i); 4308 final PhoneWindow win = ref.get(); 4309 if (win != null) { 4310 win.onOptionsPanelRotationChanged(); 4311 i++; 4312 } else { 4313 mWindows.remove(i); 4314 } 4315 } 4316 } 4317 } 4318 } 4319 4320 /** 4321 * Simple implementation of MenuBuilder.Callback that: 4322 * <li> Opens a submenu when selected. 4323 * <li> Calls back to the callback's onMenuItemSelected when an item is 4324 * selected. 4325 */ 4326 private final class DialogMenuCallback implements MenuBuilder.Callback, MenuPresenter.Callback { 4327 private int mFeatureId; 4328 private MenuDialogHelper mSubMenuHelper; 4329 4330 public DialogMenuCallback(int featureId) { 4331 mFeatureId = featureId; 4332 } 4333 4334 public void onCloseMenu(MenuBuilder menu, boolean allMenusAreClosing) { 4335 if (menu.getRootMenu() != menu) { 4336 onCloseSubMenu(menu); 4337 } 4338 4339 if (allMenusAreClosing) { 4340 Callback callback = getCallback(); 4341 if (callback != null && !isDestroyed()) { 4342 callback.onPanelClosed(mFeatureId, menu); 4343 } 4344 4345 if (menu == mContextMenu) { 4346 dismissContextMenu(); 4347 } 4348 4349 // Dismiss the submenu, if it is showing 4350 if (mSubMenuHelper != null) { 4351 mSubMenuHelper.dismiss(); 4352 mSubMenuHelper = null; 4353 } 4354 } 4355 } 4356 4357 public void onCloseSubMenu(MenuBuilder menu) { 4358 Callback callback = getCallback(); 4359 if (callback != null && !isDestroyed()) { 4360 callback.onPanelClosed(mFeatureId, menu.getRootMenu()); 4361 } 4362 } 4363 4364 public boolean onMenuItemSelected(MenuBuilder menu, MenuItem item) { 4365 Callback callback = getCallback(); 4366 return (callback != null && !isDestroyed()) 4367 && callback.onMenuItemSelected(mFeatureId, item); 4368 } 4369 4370 public void onMenuModeChange(MenuBuilder menu) { 4371 } 4372 4373 public boolean onOpenSubMenu(MenuBuilder subMenu) { 4374 if (subMenu == null) return false; 4375 4376 // Set a simple callback for the submenu 4377 subMenu.setCallback(this); 4378 4379 // The window manager will give us a valid window token 4380 mSubMenuHelper = new MenuDialogHelper(subMenu); 4381 mSubMenuHelper.show(null); 4382 4383 return true; 4384 } 4385 } 4386 4387 void sendCloseSystemWindows() { 4388 PhoneWindowManager.sendCloseSystemWindows(getContext(), null); 4389 } 4390 4391 void sendCloseSystemWindows(String reason) { 4392 PhoneWindowManager.sendCloseSystemWindows(getContext(), reason); 4393 } 4394 4395 @Override 4396 public int getStatusBarColor() { 4397 return mStatusBarColor; 4398 } 4399 4400 @Override 4401 public void setStatusBarColor(int color) { 4402 mStatusBarColor = color; 4403 mForcedStatusBarColor = true; 4404 if (mDecor != null) { 4405 mDecor.updateColorViews(null); 4406 } 4407 } 4408 4409 @Override 4410 public int getNavigationBarColor() { 4411 return mNavigationBarColor; 4412 } 4413 4414 @Override 4415 public void setNavigationBarColor(int color) { 4416 mNavigationBarColor = color; 4417 mForcedNavigationBarColor = true; 4418 if (mDecor != null) { 4419 mDecor.updateColorViews(null); 4420 } 4421 } 4422} 4423