Debian Codegraph @

core/java/com/android/internal/policy/PhoneWindow.java

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