DecorView.java revision a213d306d556a140bafe8079b00b3654c62b534c
1/*
2 * Copyright (C) 2015 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
17package com.android.internal.policy;
18
19import android.app.WindowConfiguration;
20import android.graphics.Outline;
21import android.graphics.drawable.InsetDrawable;
22import android.graphics.drawable.LayerDrawable;
23import android.util.Pair;
24import android.view.ViewOutlineProvider;
25import android.view.accessibility.AccessibilityNodeInfo;
26import com.android.internal.R;
27import com.android.internal.policy.PhoneWindow.PanelFeatureState;
28import com.android.internal.policy.PhoneWindow.PhoneWindowMenuCallback;
29import com.android.internal.view.FloatingActionMode;
30import com.android.internal.view.RootViewSurfaceTaker;
31import com.android.internal.view.StandaloneActionMode;
32import com.android.internal.view.menu.ContextMenuBuilder;
33import com.android.internal.view.menu.MenuHelper;
34import com.android.internal.widget.ActionBarContextView;
35import com.android.internal.widget.BackgroundFallback;
36import com.android.internal.widget.DecorCaptionView;
37import com.android.internal.widget.FloatingToolbar;
38
39import java.util.List;
40
41import android.animation.Animator;
42import android.animation.AnimatorListenerAdapter;
43import android.animation.ObjectAnimator;
44import android.content.Context;
45import android.content.res.Configuration;
46import android.content.res.Resources;
47import android.graphics.Canvas;
48import android.graphics.Color;
49import android.graphics.LinearGradient;
50import android.graphics.Paint;
51import android.graphics.PixelFormat;
52import android.graphics.Rect;
53import android.graphics.Region;
54import android.graphics.Shader;
55import android.graphics.drawable.ColorDrawable;
56import android.graphics.drawable.Drawable;
57import android.util.DisplayMetrics;
58import android.util.Log;
59import android.util.TypedValue;
60import android.view.ActionMode;
61import android.view.ContextThemeWrapper;
62import android.view.DisplayListCanvas;
63import android.view.Gravity;
64import android.view.InputQueue;
65import android.view.KeyEvent;
66import android.view.KeyboardShortcutGroup;
67import android.view.LayoutInflater;
68import android.view.Menu;
69import android.view.MenuItem;
70import android.view.MotionEvent;
71import android.view.ThreadedRenderer;
72import android.view.View;
73import android.view.ViewGroup;
74import android.view.ViewStub;
75import android.view.ViewTreeObserver;
76import android.view.Window;
77import android.view.WindowCallbacks;
78import android.view.WindowInsets;
79import android.view.WindowManager;
80import android.view.accessibility.AccessibilityEvent;
81import android.view.accessibility.AccessibilityManager;
82import android.view.animation.AnimationUtils;
83import android.view.animation.Interpolator;
84import android.widget.FrameLayout;
85import android.widget.PopupWindow;
86
87import static android.app.WindowConfiguration.PINNED_WINDOWING_MODE_ELEVATION_IN_DIP;
88import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
89import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
90import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
91import static android.os.Build.VERSION_CODES.M;
92import static android.os.Build.VERSION_CODES.N;
93import static android.view.View.MeasureSpec.AT_MOST;
94import static android.view.View.MeasureSpec.EXACTLY;
95import static android.view.View.MeasureSpec.getMode;
96import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
97import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
98import static android.view.Window.DECOR_CAPTION_SHADE_DARK;
99import static android.view.Window.DECOR_CAPTION_SHADE_LIGHT;
100import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
101import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
102import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
103import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
104import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
105import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
106import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
107import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
108import static android.view.WindowManager.LayoutParams.TYPE_DRAWN_APPLICATION;
109import static com.android.internal.policy.PhoneWindow.FEATURE_OPTIONS_PANEL;
110
111/** @hide */
112public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
113    private static final String TAG = "DecorView";
114
115    private static final boolean DEBUG_MEASURE = false;
116
117    private static final boolean SWEEP_OPEN_MENU = false;
118
119    // The height of a window which has focus in DIP.
120    private final static int DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP = 20;
121    // The height of a window which has not in DIP.
122    private final static int DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP = 5;
123
124    public static final ColorViewAttributes STATUS_BAR_COLOR_VIEW_ATTRIBUTES =
125            new ColorViewAttributes(SYSTEM_UI_FLAG_FULLSCREEN, FLAG_TRANSLUCENT_STATUS,
126                    Gravity.TOP, Gravity.LEFT, Gravity.RIGHT,
127                    Window.STATUS_BAR_BACKGROUND_TRANSITION_NAME,
128                    com.android.internal.R.id.statusBarBackground,
129                    FLAG_FULLSCREEN);
130
131    public static final ColorViewAttributes NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES =
132            new ColorViewAttributes(
133                    SYSTEM_UI_FLAG_HIDE_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION,
134                    Gravity.BOTTOM, Gravity.RIGHT, Gravity.LEFT,
135                    Window.NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME,
136                    com.android.internal.R.id.navigationBarBackground,
137                    0 /* hideWindowFlag */);
138
139    // This is used to workaround an issue where the PiP shadow can be transparent if the window
140    // background is transparent
141    private static final ViewOutlineProvider PIP_OUTLINE_PROVIDER = new ViewOutlineProvider() {
142        @Override
143        public void getOutline(View view, Outline outline) {
144            outline.setRect(0, 0, view.getWidth(), view.getHeight());
145            outline.setAlpha(1f);
146        }
147    };
148
149    // Cludge to address b/22668382: Set the shadow size to the maximum so that the layer
150    // size calculation takes the shadow size into account. We set the elevation currently
151    // to max until the first layout command has been executed.
152    private boolean mAllowUpdateElevation = false;
153
154    private boolean mElevationAdjustedForStack = false;
155
156    // Keeps track of the picture-in-picture mode for the view shadow
157    private boolean mIsInPictureInPictureMode;
158
159    // Stores the previous outline provider prior to applying PIP_OUTLINE_PROVIDER
160    private ViewOutlineProvider mLastOutlineProvider;
161
162    int mDefaultOpacity = PixelFormat.OPAQUE;
163
164    /** The feature ID of the panel, or -1 if this is the application's DecorView */
165    private final int mFeatureId;
166
167    private final Rect mDrawingBounds = new Rect();
168
169    private final Rect mBackgroundPadding = new Rect();
170
171    private final Rect mFramePadding = new Rect();
172
173    private final Rect mFrameOffsets = new Rect();
174
175    private boolean mHasCaption = false;
176
177    private boolean mChanging;
178
179    private Drawable mMenuBackground;
180    private boolean mWatchingForMenu;
181    private int mDownY;
182
183    ActionMode mPrimaryActionMode;
184    private ActionMode mFloatingActionMode;
185    private ActionBarContextView mPrimaryActionModeView;
186    private PopupWindow mPrimaryActionModePopup;
187    private Runnable mShowPrimaryActionModePopup;
188    private ViewTreeObserver.OnPreDrawListener mFloatingToolbarPreDrawListener;
189    private View mFloatingActionModeOriginatingView;
190    private FloatingToolbar mFloatingToolbar;
191    private ObjectAnimator mFadeAnim;
192
193    // View added at runtime to draw under the status bar area
194    private View mStatusGuard;
195
196    private final ColorViewState mStatusColorViewState =
197            new ColorViewState(STATUS_BAR_COLOR_VIEW_ATTRIBUTES);
198    private final ColorViewState mNavigationColorViewState =
199            new ColorViewState(NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES);
200
201    private final Interpolator mShowInterpolator;
202    private final Interpolator mHideInterpolator;
203    private final int mBarEnterExitDuration;
204    final boolean mForceWindowDrawsStatusBarBackground;
205    private final int mSemiTransparentStatusBarColor;
206
207    private final BackgroundFallback mBackgroundFallback = new BackgroundFallback();
208
209    private int mLastTopInset = 0;
210    private int mLastBottomInset = 0;
211    private int mLastRightInset = 0;
212    private int mLastLeftInset = 0;
213    private boolean mLastHasTopStableInset = false;
214    private boolean mLastHasBottomStableInset = false;
215    private boolean mLastHasRightStableInset = false;
216    private boolean mLastHasLeftStableInset = false;
217    private int mLastWindowFlags = 0;
218    private boolean mLastShouldAlwaysConsumeNavBar = false;
219
220    private int mRootScrollY = 0;
221
222    private PhoneWindow mWindow;
223
224    ViewGroup mContentRoot;
225
226    private Rect mTempRect;
227    private Rect mOutsets = new Rect();
228
229    // This is the caption view for the window, containing the caption and window control
230    // buttons. The visibility of this decor depends on the workspace and the window type.
231    // If the window type does not require such a view, this member might be null.
232    DecorCaptionView mDecorCaptionView;
233
234    private boolean mWindowResizeCallbacksAdded = false;
235    private Drawable.Callback mLastBackgroundDrawableCb = null;
236    private BackdropFrameRenderer mBackdropFrameRenderer = null;
237    private Drawable mResizingBackgroundDrawable;
238    private Drawable mCaptionBackgroundDrawable;
239    private Drawable mUserCaptionBackgroundDrawable;
240
241    private float mAvailableWidth;
242
243    String mLogTag = TAG;
244    private final Rect mFloatingInsets = new Rect();
245    private boolean mApplyFloatingVerticalInsets = false;
246    private boolean mApplyFloatingHorizontalInsets = false;
247
248    private int mResizeMode = RESIZE_MODE_INVALID;
249    private final int mResizeShadowSize;
250    private final Paint mVerticalResizeShadowPaint = new Paint();
251    private final Paint mHorizontalResizeShadowPaint = new Paint();
252
253    DecorView(Context context, int featureId, PhoneWindow window,
254            WindowManager.LayoutParams params) {
255        super(context);
256        mFeatureId = featureId;
257
258        mShowInterpolator = AnimationUtils.loadInterpolator(context,
259                android.R.interpolator.linear_out_slow_in);
260        mHideInterpolator = AnimationUtils.loadInterpolator(context,
261                android.R.interpolator.fast_out_linear_in);
262
263        mBarEnterExitDuration = context.getResources().getInteger(
264                R.integer.dock_enter_exit_duration);
265        mForceWindowDrawsStatusBarBackground = context.getResources().getBoolean(
266                R.bool.config_forceWindowDrawsStatusBarBackground)
267                && context.getApplicationInfo().targetSdkVersion >= N;
268        mSemiTransparentStatusBarColor = context.getResources().getColor(
269                R.color.system_bar_background_semi_transparent, null /* theme */);
270
271        updateAvailableWidth();
272
273        setWindow(window);
274
275        updateLogTag(params);
276
277        mResizeShadowSize = context.getResources().getDimensionPixelSize(
278                R.dimen.resize_shadow_size);
279        initResizingPaints();
280    }
281
282    void setBackgroundFallback(int resId) {
283        mBackgroundFallback.setDrawable(resId != 0 ? getContext().getDrawable(resId) : null);
284        setWillNotDraw(getBackground() == null && !mBackgroundFallback.hasFallback());
285    }
286
287    @Override
288    public boolean gatherTransparentRegion(Region region) {
289        boolean statusOpaque = gatherTransparentRegion(mStatusColorViewState, region);
290        boolean navOpaque = gatherTransparentRegion(mNavigationColorViewState, region);
291        boolean decorOpaque = super.gatherTransparentRegion(region);
292
293        // combine bools after computation, so each method above always executes
294        return statusOpaque || navOpaque || decorOpaque;
295    }
296
297    boolean gatherTransparentRegion(ColorViewState colorViewState, Region region) {
298        if (colorViewState.view != null && colorViewState.visible && isResizing()) {
299            // If a visible ColorViewState is in a resizing host DecorView, forcibly register its
300            // opaque area, since it's drawn by a different root RenderNode. It would otherwise be
301            // rejected by ViewGroup#gatherTransparentRegion() for the view not being VISIBLE.
302            return colorViewState.view.gatherTransparentRegion(region);
303        }
304        return false; // no opaque area added
305    }
306
307    @Override
308    public void onDraw(Canvas c) {
309        super.onDraw(c);
310
311        // When we are resizing, we need the fallback background to cover the area where we have our
312        // system bar background views as the navigation bar will be hidden during resizing.
313        mBackgroundFallback.draw(isResizing() ? this : mContentRoot, mContentRoot, c,
314                mWindow.mContentParent);
315    }
316
317    @Override
318    public boolean dispatchKeyEvent(KeyEvent event) {
319        final int keyCode = event.getKeyCode();
320        final int action = event.getAction();
321        final boolean isDown = action == KeyEvent.ACTION_DOWN;
322
323        if (isDown && (event.getRepeatCount() == 0)) {
324            // First handle chording of panel key: if a panel key is held
325            // but not released, try to execute a shortcut in it.
326            if ((mWindow.mPanelChordingKey > 0) && (mWindow.mPanelChordingKey != keyCode)) {
327                boolean handled = dispatchKeyShortcutEvent(event);
328                if (handled) {
329                    return true;
330                }
331            }
332
333            // If a panel is open, perform a shortcut on it without the
334            // chorded panel key
335            if ((mWindow.mPreparedPanel != null) && mWindow.mPreparedPanel.isOpen) {
336                if (mWindow.performPanelShortcut(mWindow.mPreparedPanel, keyCode, event, 0)) {
337                    return true;
338                }
339            }
340        }
341
342        if (!mWindow.isDestroyed()) {
343            final Window.Callback cb = mWindow.getCallback();
344            final boolean handled = cb != null && mFeatureId < 0 ? cb.dispatchKeyEvent(event)
345                    : super.dispatchKeyEvent(event);
346            if (handled) {
347                return true;
348            }
349        }
350
351        return isDown ? mWindow.onKeyDown(mFeatureId, event.getKeyCode(), event)
352                : mWindow.onKeyUp(mFeatureId, event.getKeyCode(), event);
353    }
354
355    @Override
356    public boolean dispatchKeyShortcutEvent(KeyEvent ev) {
357        // If the panel is already prepared, then perform the shortcut using it.
358        boolean handled;
359        if (mWindow.mPreparedPanel != null) {
360            handled = mWindow.performPanelShortcut(mWindow.mPreparedPanel, ev.getKeyCode(), ev,
361                    Menu.FLAG_PERFORM_NO_CLOSE);
362            if (handled) {
363                if (mWindow.mPreparedPanel != null) {
364                    mWindow.mPreparedPanel.isHandled = true;
365                }
366                return true;
367            }
368        }
369
370        // Shortcut not handled by the panel.  Dispatch to the view hierarchy.
371        final Window.Callback cb = mWindow.getCallback();
372        handled = cb != null && !mWindow.isDestroyed() && mFeatureId < 0
373                ? cb.dispatchKeyShortcutEvent(ev) : super.dispatchKeyShortcutEvent(ev);
374        if (handled) {
375            return true;
376        }
377
378        // If the panel is not prepared, then we may be trying to handle a shortcut key
379        // combination such as Control+C.  Temporarily prepare the panel then mark it
380        // unprepared again when finished to ensure that the panel will again be prepared
381        // the next time it is shown for real.
382        PhoneWindow.PanelFeatureState st =
383                mWindow.getPanelState(Window.FEATURE_OPTIONS_PANEL, false);
384        if (st != null && mWindow.mPreparedPanel == null) {
385            mWindow.preparePanel(st, ev);
386            handled = mWindow.performPanelShortcut(st, ev.getKeyCode(), ev,
387                    Menu.FLAG_PERFORM_NO_CLOSE);
388            st.isPrepared = false;
389            if (handled) {
390                return true;
391            }
392        }
393        return false;
394    }
395
396    @Override
397    public boolean dispatchTouchEvent(MotionEvent ev) {
398        final Window.Callback cb = mWindow.getCallback();
399        return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
400                ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
401    }
402
403    @Override
404    public boolean dispatchTrackballEvent(MotionEvent ev) {
405        final Window.Callback cb = mWindow.getCallback();
406        return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
407                ? cb.dispatchTrackballEvent(ev) : super.dispatchTrackballEvent(ev);
408    }
409
410    @Override
411    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
412        final Window.Callback cb = mWindow.getCallback();
413        return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
414                ? cb.dispatchGenericMotionEvent(ev) : super.dispatchGenericMotionEvent(ev);
415    }
416
417    public boolean superDispatchKeyEvent(KeyEvent event) {
418        // Give priority to closing action modes if applicable.
419        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
420            final int action = event.getAction();
421            // Back cancels action modes first.
422            if (mPrimaryActionMode != null) {
423                if (action == KeyEvent.ACTION_UP) {
424                    mPrimaryActionMode.finish();
425                }
426                return true;
427            }
428        }
429
430        if (super.dispatchKeyEvent(event)) {
431            return true;
432        }
433
434        return (getViewRootImpl() != null) && getViewRootImpl().dispatchKeyFallbackEvent(event);
435    }
436
437    public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
438        return super.dispatchKeyShortcutEvent(event);
439    }
440
441    public boolean superDispatchTouchEvent(MotionEvent event) {
442        return super.dispatchTouchEvent(event);
443    }
444
445    public boolean superDispatchTrackballEvent(MotionEvent event) {
446        return super.dispatchTrackballEvent(event);
447    }
448
449    public boolean superDispatchGenericMotionEvent(MotionEvent event) {
450        return super.dispatchGenericMotionEvent(event);
451    }
452
453    @Override
454    public boolean onTouchEvent(MotionEvent event) {
455        return onInterceptTouchEvent(event);
456    }
457
458    private boolean isOutOfInnerBounds(int x, int y) {
459        return x < 0 || y < 0 || x > getWidth() || y > getHeight();
460    }
461
462    private boolean isOutOfBounds(int x, int y) {
463        return x < -5 || y < -5 || x > (getWidth() + 5)
464                || y > (getHeight() + 5);
465    }
466
467    @Override
468    public boolean onInterceptTouchEvent(MotionEvent event) {
469        int action = event.getAction();
470        if (mHasCaption && isShowingCaption()) {
471            // Don't dispatch ACTION_DOWN to the captionr if the window is resizable and the event
472            // was (starting) outside the window. Window resizing events should be handled by
473            // WindowManager.
474            // TODO: Investigate how to handle the outside touch in window manager
475            //       without generating these events.
476            //       Currently we receive these because we need to enlarge the window's
477            //       touch region so that the monitor channel receives the events
478            //       in the outside touch area.
479            if (action == MotionEvent.ACTION_DOWN) {
480                final int x = (int) event.getX();
481                final int y = (int) event.getY();
482                if (isOutOfInnerBounds(x, y)) {
483                    return true;
484                }
485            }
486        }
487
488        if (mFeatureId >= 0) {
489            if (action == MotionEvent.ACTION_DOWN) {
490                int x = (int)event.getX();
491                int y = (int)event.getY();
492                if (isOutOfBounds(x, y)) {
493                    mWindow.closePanel(mFeatureId);
494                    return true;
495                }
496            }
497        }
498
499        if (!SWEEP_OPEN_MENU) {
500            return false;
501        }
502
503        if (mFeatureId >= 0) {
504            if (action == MotionEvent.ACTION_DOWN) {
505                Log.i(mLogTag, "Watchiing!");
506                mWatchingForMenu = true;
507                mDownY = (int) event.getY();
508                return false;
509            }
510
511            if (!mWatchingForMenu) {
512                return false;
513            }
514
515            int y = (int)event.getY();
516            if (action == MotionEvent.ACTION_MOVE) {
517                if (y > (mDownY+30)) {
518                    Log.i(mLogTag, "Closing!");
519                    mWindow.closePanel(mFeatureId);
520                    mWatchingForMenu = false;
521                    return true;
522                }
523            } else if (action == MotionEvent.ACTION_UP) {
524                mWatchingForMenu = false;
525            }
526
527            return false;
528        }
529
530        //Log.i(mLogTag, "Intercept: action=" + action + " y=" + event.getY()
531        //        + " (in " + getHeight() + ")");
532
533        if (action == MotionEvent.ACTION_DOWN) {
534            int y = (int)event.getY();
535            if (y >= (getHeight()-5) && !mWindow.hasChildren()) {
536                Log.i(mLogTag, "Watching!");
537                mWatchingForMenu = true;
538            }
539            return false;
540        }
541
542        if (!mWatchingForMenu) {
543            return false;
544        }
545
546        int y = (int)event.getY();
547        if (action == MotionEvent.ACTION_MOVE) {
548            if (y < (getHeight()-30)) {
549                Log.i(mLogTag, "Opening!");
550                mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, new KeyEvent(
551                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MENU));
552                mWatchingForMenu = false;
553                return true;
554            }
555        } else if (action == MotionEvent.ACTION_UP) {
556            mWatchingForMenu = false;
557        }
558
559        return false;
560    }
561
562    @Override
563    public void sendAccessibilityEvent(int eventType) {
564        if (!AccessibilityManager.getInstance(mContext).isEnabled()) {
565            return;
566        }
567
568        // if we are showing a feature that should be announced and one child
569        // make this child the event source since this is the feature itself
570        // otherwise the callback will take over and announce its client
571        if ((mFeatureId == Window.FEATURE_OPTIONS_PANEL ||
572                mFeatureId == Window.FEATURE_CONTEXT_MENU ||
573                mFeatureId == Window.FEATURE_PROGRESS ||
574                mFeatureId == Window.FEATURE_INDETERMINATE_PROGRESS)
575                && getChildCount() == 1) {
576            getChildAt(0).sendAccessibilityEvent(eventType);
577        } else {
578            super.sendAccessibilityEvent(eventType);
579        }
580    }
581
582    @Override
583    public boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
584        final Window.Callback cb = mWindow.getCallback();
585        if (cb != null && !mWindow.isDestroyed()) {
586            if (cb.dispatchPopulateAccessibilityEvent(event)) {
587                return true;
588            }
589        }
590        return super.dispatchPopulateAccessibilityEventInternal(event);
591    }
592
593    @Override
594    protected boolean setFrame(int l, int t, int r, int b) {
595        boolean changed = super.setFrame(l, t, r, b);
596        if (changed) {
597            final Rect drawingBounds = mDrawingBounds;
598            getDrawingRect(drawingBounds);
599
600            Drawable fg = getForeground();
601            if (fg != null) {
602                final Rect frameOffsets = mFrameOffsets;
603                drawingBounds.left += frameOffsets.left;
604                drawingBounds.top += frameOffsets.top;
605                drawingBounds.right -= frameOffsets.right;
606                drawingBounds.bottom -= frameOffsets.bottom;
607                fg.setBounds(drawingBounds);
608                final Rect framePadding = mFramePadding;
609                drawingBounds.left += framePadding.left - frameOffsets.left;
610                drawingBounds.top += framePadding.top - frameOffsets.top;
611                drawingBounds.right -= framePadding.right - frameOffsets.right;
612                drawingBounds.bottom -= framePadding.bottom - frameOffsets.bottom;
613            }
614
615            Drawable bg = getBackground();
616            if (bg != null) {
617                bg.setBounds(drawingBounds);
618            }
619
620            if (SWEEP_OPEN_MENU) {
621                if (mMenuBackground == null && mFeatureId < 0
622                        && mWindow.getAttributes().height
623                        == WindowManager.LayoutParams.MATCH_PARENT) {
624                    mMenuBackground = getContext().getDrawable(
625                            R.drawable.menu_background);
626                }
627                if (mMenuBackground != null) {
628                    mMenuBackground.setBounds(drawingBounds.left,
629                            drawingBounds.bottom-6, drawingBounds.right,
630                            drawingBounds.bottom+20);
631                }
632            }
633        }
634        return changed;
635    }
636
637    @Override
638    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
639        final DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
640        final boolean isPortrait =
641                getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT;
642
643        final int widthMode = getMode(widthMeasureSpec);
644        final int heightMode = getMode(heightMeasureSpec);
645
646        boolean fixedWidth = false;
647        mApplyFloatingHorizontalInsets = false;
648        if (widthMode == AT_MOST) {
649            final TypedValue tvw = isPortrait ? mWindow.mFixedWidthMinor : mWindow.mFixedWidthMajor;
650            if (tvw != null && tvw.type != TypedValue.TYPE_NULL) {
651                final int w;
652                if (tvw.type == TypedValue.TYPE_DIMENSION) {
653                    w = (int) tvw.getDimension(metrics);
654                } else if (tvw.type == TypedValue.TYPE_FRACTION) {
655                    w = (int) tvw.getFraction(metrics.widthPixels, metrics.widthPixels);
656                } else {
657                    w = 0;
658                }
659                if (DEBUG_MEASURE) Log.d(mLogTag, "Fixed width: " + w);
660                final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
661                if (w > 0) {
662                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(
663                            Math.min(w, widthSize), EXACTLY);
664                    fixedWidth = true;
665                } else {
666                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(
667                            widthSize - mFloatingInsets.left - mFloatingInsets.right,
668                            AT_MOST);
669                    mApplyFloatingHorizontalInsets = true;
670                }
671            }
672        }
673
674        mApplyFloatingVerticalInsets = false;
675        if (heightMode == AT_MOST) {
676            final TypedValue tvh = isPortrait ? mWindow.mFixedHeightMajor
677                    : mWindow.mFixedHeightMinor;
678            if (tvh != null && tvh.type != TypedValue.TYPE_NULL) {
679                final int h;
680                if (tvh.type == TypedValue.TYPE_DIMENSION) {
681                    h = (int) tvh.getDimension(metrics);
682                } else if (tvh.type == TypedValue.TYPE_FRACTION) {
683                    h = (int) tvh.getFraction(metrics.heightPixels, metrics.heightPixels);
684                } else {
685                    h = 0;
686                }
687                if (DEBUG_MEASURE) Log.d(mLogTag, "Fixed height: " + h);
688                final int heightSize = MeasureSpec.getSize(heightMeasureSpec);
689                if (h > 0) {
690                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(
691                            Math.min(h, heightSize), EXACTLY);
692                } else if ((mWindow.getAttributes().flags & FLAG_LAYOUT_IN_SCREEN) == 0) {
693                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(
694                            heightSize - mFloatingInsets.top - mFloatingInsets.bottom, AT_MOST);
695                    mApplyFloatingVerticalInsets = true;
696                }
697            }
698        }
699
700        getOutsets(mOutsets);
701        if (mOutsets.top > 0 || mOutsets.bottom > 0) {
702            int mode = MeasureSpec.getMode(heightMeasureSpec);
703            if (mode != MeasureSpec.UNSPECIFIED) {
704                int height = MeasureSpec.getSize(heightMeasureSpec);
705                heightMeasureSpec = MeasureSpec.makeMeasureSpec(
706                        height + mOutsets.top + mOutsets.bottom, mode);
707            }
708        }
709        if (mOutsets.left > 0 || mOutsets.right > 0) {
710            int mode = MeasureSpec.getMode(widthMeasureSpec);
711            if (mode != MeasureSpec.UNSPECIFIED) {
712                int width = MeasureSpec.getSize(widthMeasureSpec);
713                widthMeasureSpec = MeasureSpec.makeMeasureSpec(
714                        width + mOutsets.left + mOutsets.right, mode);
715            }
716        }
717
718        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
719
720        int width = getMeasuredWidth();
721        boolean measure = false;
722
723        widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, EXACTLY);
724
725        if (!fixedWidth && widthMode == AT_MOST) {
726            final TypedValue tv = isPortrait ? mWindow.mMinWidthMinor : mWindow.mMinWidthMajor;
727            if (tv.type != TypedValue.TYPE_NULL) {
728                final int min;
729                if (tv.type == TypedValue.TYPE_DIMENSION) {
730                    min = (int)tv.getDimension(metrics);
731                } else if (tv.type == TypedValue.TYPE_FRACTION) {
732                    min = (int)tv.getFraction(mAvailableWidth, mAvailableWidth);
733                } else {
734                    min = 0;
735                }
736                if (DEBUG_MEASURE) Log.d(mLogTag, "Adjust for min width: " + min + ", value::"
737                        + tv.coerceToString() + ", mAvailableWidth=" + mAvailableWidth);
738
739                if (width < min) {
740                    widthMeasureSpec = MeasureSpec.makeMeasureSpec(min, EXACTLY);
741                    measure = true;
742                }
743            }
744        }
745
746        // TODO: Support height?
747
748        if (measure) {
749            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
750        }
751    }
752
753    @Override
754    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
755        super.onLayout(changed, left, top, right, bottom);
756        getOutsets(mOutsets);
757        if (mOutsets.left > 0) {
758            offsetLeftAndRight(-mOutsets.left);
759        }
760        if (mOutsets.top > 0) {
761            offsetTopAndBottom(-mOutsets.top);
762        }
763        if (mApplyFloatingVerticalInsets) {
764            offsetTopAndBottom(mFloatingInsets.top);
765        }
766        if (mApplyFloatingHorizontalInsets) {
767            offsetLeftAndRight(mFloatingInsets.left);
768        }
769
770        // If the application changed its SystemUI metrics, we might also have to adapt
771        // our shadow elevation.
772        updateElevation();
773        mAllowUpdateElevation = true;
774
775        if (changed && mResizeMode == RESIZE_MODE_DOCKED_DIVIDER) {
776            getViewRootImpl().requestInvalidateRootRenderNode();
777        }
778    }
779
780    @Override
781    public void draw(Canvas canvas) {
782        super.draw(canvas);
783
784        if (mMenuBackground != null) {
785            mMenuBackground.draw(canvas);
786        }
787    }
788
789    @Override
790    public boolean showContextMenuForChild(View originalView) {
791        return showContextMenuForChildInternal(originalView, Float.NaN, Float.NaN);
792    }
793
794    @Override
795    public boolean showContextMenuForChild(View originalView, float x, float y) {
796        return showContextMenuForChildInternal(originalView, x, y);
797    }
798
799    private boolean showContextMenuForChildInternal(View originalView,
800            float x, float y) {
801        // Only allow one context menu at a time.
802        if (mWindow.mContextMenuHelper != null) {
803            mWindow.mContextMenuHelper.dismiss();
804            mWindow.mContextMenuHelper = null;
805        }
806
807        // Reuse the context menu builder.
808        final PhoneWindowMenuCallback callback = mWindow.mContextMenuCallback;
809        if (mWindow.mContextMenu == null) {
810            mWindow.mContextMenu = new ContextMenuBuilder(getContext());
811            mWindow.mContextMenu.setCallback(callback);
812        } else {
813            mWindow.mContextMenu.clearAll();
814        }
815
816        final MenuHelper helper;
817        final boolean isPopup = !Float.isNaN(x) && !Float.isNaN(y);
818        if (isPopup) {
819            helper = mWindow.mContextMenu.showPopup(getContext(), originalView, x, y);
820        } else {
821            helper = mWindow.mContextMenu.showDialog(originalView, originalView.getWindowToken());
822        }
823
824        if (helper != null) {
825            // If it's a dialog, the callback needs to handle showing
826            // sub-menus. Either way, the callback is required for propagating
827            // selection to Context.onContextMenuItemSelected().
828            callback.setShowDialogForSubmenu(!isPopup);
829            helper.setPresenterCallback(callback);
830        }
831
832        mWindow.mContextMenuHelper = helper;
833        return helper != null;
834    }
835
836    @Override
837    public ActionMode startActionModeForChild(View originalView,
838            ActionMode.Callback callback) {
839        return startActionModeForChild(originalView, callback, ActionMode.TYPE_PRIMARY);
840    }
841
842    @Override
843    public ActionMode startActionModeForChild(
844            View child, ActionMode.Callback callback, int type) {
845        return startActionMode(child, callback, type);
846    }
847
848    @Override
849    public ActionMode startActionMode(ActionMode.Callback callback) {
850        return startActionMode(callback, ActionMode.TYPE_PRIMARY);
851    }
852
853    @Override
854    public ActionMode startActionMode(ActionMode.Callback callback, int type) {
855        return startActionMode(this, callback, type);
856    }
857
858    private ActionMode startActionMode(
859            View originatingView, ActionMode.Callback callback, int type) {
860        ActionMode.Callback2 wrappedCallback = new ActionModeCallback2Wrapper(callback);
861        ActionMode mode = null;
862        if (mWindow.getCallback() != null && !mWindow.isDestroyed()) {
863            try {
864                mode = mWindow.getCallback().onWindowStartingActionMode(wrappedCallback, type);
865            } catch (AbstractMethodError ame) {
866                // Older apps might not implement the typed version of this method.
867                if (type == ActionMode.TYPE_PRIMARY) {
868                    try {
869                        mode = mWindow.getCallback().onWindowStartingActionMode(
870                                wrappedCallback);
871                    } catch (AbstractMethodError ame2) {
872                        // Older apps might not implement this callback method at all.
873                    }
874                }
875            }
876        }
877        if (mode != null) {
878            if (mode.getType() == ActionMode.TYPE_PRIMARY) {
879                cleanupPrimaryActionMode();
880                mPrimaryActionMode = mode;
881            } else if (mode.getType() == ActionMode.TYPE_FLOATING) {
882                if (mFloatingActionMode != null) {
883                    mFloatingActionMode.finish();
884                }
885                mFloatingActionMode = mode;
886            }
887        } else {
888            mode = createActionMode(type, wrappedCallback, originatingView);
889            if (mode != null && wrappedCallback.onCreateActionMode(mode, mode.getMenu())) {
890                setHandledActionMode(mode);
891            } else {
892                mode = null;
893            }
894        }
895        if (mode != null && mWindow.getCallback() != null && !mWindow.isDestroyed()) {
896            try {
897                mWindow.getCallback().onActionModeStarted(mode);
898            } catch (AbstractMethodError ame) {
899                // Older apps might not implement this callback method.
900            }
901        }
902        return mode;
903    }
904
905    private void cleanupPrimaryActionMode() {
906        if (mPrimaryActionMode != null) {
907            mPrimaryActionMode.finish();
908            mPrimaryActionMode = null;
909        }
910        if (mPrimaryActionModeView != null) {
911            mPrimaryActionModeView.killMode();
912        }
913    }
914
915    private void cleanupFloatingActionModeViews() {
916        if (mFloatingToolbar != null) {
917            mFloatingToolbar.dismiss();
918            mFloatingToolbar = null;
919        }
920        if (mFloatingActionModeOriginatingView != null) {
921            if (mFloatingToolbarPreDrawListener != null) {
922                mFloatingActionModeOriginatingView.getViewTreeObserver()
923                    .removeOnPreDrawListener(mFloatingToolbarPreDrawListener);
924                mFloatingToolbarPreDrawListener = null;
925            }
926            mFloatingActionModeOriginatingView = null;
927        }
928    }
929
930    void startChanging() {
931        mChanging = true;
932    }
933
934    void finishChanging() {
935        mChanging = false;
936        drawableChanged();
937    }
938
939    public void setWindowBackground(Drawable drawable) {
940        if (getBackground() != drawable) {
941            setBackgroundDrawable(drawable);
942            if (drawable != null) {
943                mResizingBackgroundDrawable = enforceNonTranslucentBackground(drawable,
944                        mWindow.isTranslucent() || mWindow.isShowingWallpaper());
945            } else {
946                mResizingBackgroundDrawable = getResizingBackgroundDrawable(
947                        getContext(), 0, mWindow.mBackgroundFallbackResource,
948                        mWindow.isTranslucent() || mWindow.isShowingWallpaper());
949            }
950            if (mResizingBackgroundDrawable != null) {
951                mResizingBackgroundDrawable.getPadding(mBackgroundPadding);
952            } else {
953                mBackgroundPadding.setEmpty();
954            }
955            drawableChanged();
956        }
957    }
958
959    public void setWindowFrame(Drawable drawable) {
960        if (getForeground() != drawable) {
961            setForeground(drawable);
962            if (drawable != null) {
963                drawable.getPadding(mFramePadding);
964            } else {
965                mFramePadding.setEmpty();
966            }
967            drawableChanged();
968        }
969    }
970
971    @Override
972    public void onWindowSystemUiVisibilityChanged(int visible) {
973        updateColorViews(null /* insets */, true /* animate */);
974    }
975
976    @Override
977    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
978        final WindowManager.LayoutParams attrs = mWindow.getAttributes();
979        mFloatingInsets.setEmpty();
980        if ((attrs.flags & FLAG_LAYOUT_IN_SCREEN) == 0) {
981            // For dialog windows we want to make sure they don't go over the status bar or nav bar.
982            // We consume the system insets and we will reuse them later during the measure phase.
983            // We allow the app to ignore this and handle insets itself by using
984            // FLAG_LAYOUT_IN_SCREEN.
985            if (attrs.height == WindowManager.LayoutParams.WRAP_CONTENT) {
986                mFloatingInsets.top = insets.getSystemWindowInsetTop();
987                mFloatingInsets.bottom = insets.getSystemWindowInsetBottom();
988                insets = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0,
989                        insets.getSystemWindowInsetRight(), 0);
990            }
991            if (mWindow.getAttributes().width == WindowManager.LayoutParams.WRAP_CONTENT) {
992                mFloatingInsets.left = insets.getSystemWindowInsetTop();
993                mFloatingInsets.right = insets.getSystemWindowInsetBottom();
994                insets = insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(),
995                        0, insets.getSystemWindowInsetBottom());
996            }
997        }
998        mFrameOffsets.set(insets.getSystemWindowInsets());
999        insets = updateColorViews(insets, true /* animate */);
1000        insets = updateStatusGuard(insets);
1001        if (getForeground() != null) {
1002            drawableChanged();
1003        }
1004        return insets;
1005    }
1006
1007    @Override
1008    public boolean isTransitionGroup() {
1009        return false;
1010    }
1011
1012    public static int getColorViewTopInset(int stableTop, int systemTop) {
1013        return Math.min(stableTop, systemTop);
1014    }
1015
1016    public static int getColorViewBottomInset(int stableBottom, int systemBottom) {
1017        return Math.min(stableBottom, systemBottom);
1018    }
1019
1020    public static int getColorViewRightInset(int stableRight, int systemRight) {
1021        return Math.min(stableRight, systemRight);
1022    }
1023
1024    public static int getColorViewLeftInset(int stableLeft, int systemLeft) {
1025        return Math.min(stableLeft, systemLeft);
1026    }
1027
1028    public static boolean isNavBarToRightEdge(int bottomInset, int rightInset) {
1029        return bottomInset == 0 && rightInset > 0;
1030    }
1031
1032    public static boolean isNavBarToLeftEdge(int bottomInset, int leftInset) {
1033        return bottomInset == 0 && leftInset > 0;
1034    }
1035
1036    public static int getNavBarSize(int bottomInset, int rightInset, int leftInset) {
1037        return isNavBarToRightEdge(bottomInset, rightInset) ? rightInset
1038                : isNavBarToLeftEdge(bottomInset, leftInset) ? leftInset : bottomInset;
1039    }
1040
1041    public static void getNavigationBarRect(int canvasWidth, int canvasHeight, Rect stableInsets,
1042            Rect contentInsets, Rect outRect) {
1043        final int bottomInset = getColorViewBottomInset(stableInsets.bottom, contentInsets.bottom);
1044        final int leftInset = getColorViewLeftInset(stableInsets.left, contentInsets.left);
1045        final int rightInset = getColorViewLeftInset(stableInsets.right, contentInsets.right);
1046        final int size = getNavBarSize(bottomInset, rightInset, leftInset);
1047        if (isNavBarToRightEdge(bottomInset, rightInset)) {
1048            outRect.set(canvasWidth - size, 0, canvasWidth, canvasHeight);
1049        } else if (isNavBarToLeftEdge(bottomInset, leftInset)) {
1050            outRect.set(0, 0, size, canvasHeight);
1051        } else {
1052            outRect.set(0, canvasHeight - size, canvasWidth, canvasHeight);
1053        }
1054    }
1055
1056    WindowInsets updateColorViews(WindowInsets insets, boolean animate) {
1057        WindowManager.LayoutParams attrs = mWindow.getAttributes();
1058        int sysUiVisibility = attrs.systemUiVisibility | getWindowSystemUiVisibility();
1059
1060        // IME is an exceptional floating window that requires color view.
1061        final boolean isImeWindow =
1062                mWindow.getAttributes().type == WindowManager.LayoutParams.TYPE_INPUT_METHOD;
1063        if (!mWindow.mIsFloating || isImeWindow) {
1064            boolean disallowAnimate = !isLaidOut();
1065            disallowAnimate |= ((mLastWindowFlags ^ attrs.flags)
1066                    & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0;
1067            mLastWindowFlags = attrs.flags;
1068
1069            if (insets != null) {
1070                mLastTopInset = getColorViewTopInset(insets.getStableInsetTop(),
1071                        insets.getSystemWindowInsetTop());
1072                mLastBottomInset = getColorViewBottomInset(insets.getStableInsetBottom(),
1073                        insets.getSystemWindowInsetBottom());
1074                mLastRightInset = getColorViewRightInset(insets.getStableInsetRight(),
1075                        insets.getSystemWindowInsetRight());
1076                mLastLeftInset = getColorViewRightInset(insets.getStableInsetLeft(),
1077                        insets.getSystemWindowInsetLeft());
1078
1079                // Don't animate if the presence of stable insets has changed, because that
1080                // indicates that the window was either just added and received them for the
1081                // first time, or the window size or position has changed.
1082                boolean hasTopStableInset = insets.getStableInsetTop() != 0;
1083                disallowAnimate |= (hasTopStableInset != mLastHasTopStableInset);
1084                mLastHasTopStableInset = hasTopStableInset;
1085
1086                boolean hasBottomStableInset = insets.getStableInsetBottom() != 0;
1087                disallowAnimate |= (hasBottomStableInset != mLastHasBottomStableInset);
1088                mLastHasBottomStableInset = hasBottomStableInset;
1089
1090                boolean hasRightStableInset = insets.getStableInsetRight() != 0;
1091                disallowAnimate |= (hasRightStableInset != mLastHasRightStableInset);
1092                mLastHasRightStableInset = hasRightStableInset;
1093
1094                boolean hasLeftStableInset = insets.getStableInsetLeft() != 0;
1095                disallowAnimate |= (hasLeftStableInset != mLastHasLeftStableInset);
1096                mLastHasLeftStableInset = hasLeftStableInset;
1097
1098                mLastShouldAlwaysConsumeNavBar = insets.shouldAlwaysConsumeNavBar();
1099            }
1100
1101            boolean navBarToRightEdge = isNavBarToRightEdge(mLastBottomInset, mLastRightInset);
1102            boolean navBarToLeftEdge = isNavBarToLeftEdge(mLastBottomInset, mLastLeftInset);
1103            int navBarSize = getNavBarSize(mLastBottomInset, mLastRightInset, mLastLeftInset);
1104            updateColorViewInt(mNavigationColorViewState, sysUiVisibility,
1105                    mWindow.mNavigationBarColor, mWindow.mNavigationBarDividerColor, navBarSize,
1106                    navBarToRightEdge || navBarToLeftEdge, navBarToLeftEdge,
1107                    0 /* sideInset */, animate && !disallowAnimate, false /* force */);
1108
1109            boolean statusBarNeedsRightInset = navBarToRightEdge
1110                    && mNavigationColorViewState.present;
1111            boolean statusBarNeedsLeftInset = navBarToLeftEdge
1112                    && mNavigationColorViewState.present;
1113            int statusBarSideInset = statusBarNeedsRightInset ? mLastRightInset
1114                    : statusBarNeedsLeftInset ? mLastLeftInset : 0;
1115            updateColorViewInt(mStatusColorViewState, sysUiVisibility,
1116                    calculateStatusBarColor(), 0, mLastTopInset,
1117                    false /* matchVertical */, statusBarNeedsLeftInset, statusBarSideInset,
1118                    animate && !disallowAnimate,
1119                    mForceWindowDrawsStatusBarBackground);
1120        }
1121
1122        // When we expand the window with FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS, we still need
1123        // to ensure that the rest of the view hierarchy doesn't notice it, unless they've
1124        // explicitly asked for it.
1125        boolean consumingNavBar =
1126                (attrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
1127                        && (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION) == 0
1128                        && (sysUiVisibility & SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0
1129                || mLastShouldAlwaysConsumeNavBar;
1130
1131        // If we didn't request fullscreen layout, but we still got it because of the
1132        // mForceWindowDrawsStatusBarBackground flag, also consume top inset.
1133        boolean consumingStatusBar = (sysUiVisibility & SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) == 0
1134                && (sysUiVisibility & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) == 0
1135                && (attrs.flags & FLAG_LAYOUT_IN_SCREEN) == 0
1136                && (attrs.flags & FLAG_LAYOUT_INSET_DECOR) == 0
1137                && mForceWindowDrawsStatusBarBackground
1138                && mLastTopInset != 0;
1139
1140        int consumedTop = consumingStatusBar ? mLastTopInset : 0;
1141        int consumedRight = consumingNavBar ? mLastRightInset : 0;
1142        int consumedBottom = consumingNavBar ? mLastBottomInset : 0;
1143        int consumedLeft = consumingNavBar ? mLastLeftInset : 0;
1144
1145        if (mContentRoot != null
1146                && mContentRoot.getLayoutParams() instanceof MarginLayoutParams) {
1147            MarginLayoutParams lp = (MarginLayoutParams) mContentRoot.getLayoutParams();
1148            if (lp.topMargin != consumedTop || lp.rightMargin != consumedRight
1149                    || lp.bottomMargin != consumedBottom || lp.leftMargin != consumedLeft) {
1150                lp.topMargin = consumedTop;
1151                lp.rightMargin = consumedRight;
1152                lp.bottomMargin = consumedBottom;
1153                lp.leftMargin = consumedLeft;
1154                mContentRoot.setLayoutParams(lp);
1155
1156                if (insets == null) {
1157                    // The insets have changed, but we're not currently in the process
1158                    // of dispatching them.
1159                    requestApplyInsets();
1160                }
1161            }
1162            if (insets != null) {
1163                insets = insets.replaceSystemWindowInsets(
1164                        insets.getSystemWindowInsetLeft() - consumedLeft,
1165                        insets.getSystemWindowInsetTop() - consumedTop,
1166                        insets.getSystemWindowInsetRight() - consumedRight,
1167                        insets.getSystemWindowInsetBottom() - consumedBottom);
1168            }
1169        }
1170
1171        if (insets != null) {
1172            insets = insets.consumeStableInsets();
1173        }
1174        return insets;
1175    }
1176
1177    private int calculateStatusBarColor() {
1178        return calculateStatusBarColor(mWindow.getAttributes().flags,
1179                mSemiTransparentStatusBarColor, mWindow.mStatusBarColor);
1180    }
1181
1182    public static int calculateStatusBarColor(int flags, int semiTransparentStatusBarColor,
1183            int statusBarColor) {
1184        return (flags & FLAG_TRANSLUCENT_STATUS) != 0 ? semiTransparentStatusBarColor
1185                : (flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0 ? statusBarColor
1186                : Color.BLACK;
1187    }
1188
1189    private int getCurrentColor(ColorViewState state) {
1190        if (state.visible) {
1191            return state.color;
1192        } else {
1193            return 0;
1194        }
1195    }
1196
1197    /**
1198     * Update a color view
1199     *
1200     * @param state the color view to update.
1201     * @param sysUiVis the current systemUiVisibility to apply.
1202     * @param color the current color to apply.
1203     * @param dividerColor the current divider color to apply.
1204     * @param size the current size in the non-parent-matching dimension.
1205     * @param verticalBar if true the view is attached to a vertical edge, otherwise to a
1206     *                    horizontal edge,
1207     * @param sideMargin sideMargin for the color view.
1208     * @param animate if true, the change will be animated.
1209     */
1210    private void updateColorViewInt(final ColorViewState state, int sysUiVis, int color,
1211            int dividerColor, int size, boolean verticalBar, boolean seascape, int sideMargin,
1212            boolean animate, boolean force) {
1213        state.present = state.attributes.isPresent(sysUiVis, mWindow.getAttributes().flags, force);
1214        boolean show = state.attributes.isVisible(state.present, color,
1215                mWindow.getAttributes().flags, force);
1216        boolean showView = show && !isResizing() && size > 0;
1217
1218        boolean visibilityChanged = false;
1219        View view = state.view;
1220
1221        int resolvedHeight = verticalBar ? LayoutParams.MATCH_PARENT : size;
1222        int resolvedWidth = verticalBar ? size : LayoutParams.MATCH_PARENT;
1223        int resolvedGravity = verticalBar
1224                ? (seascape ? state.attributes.seascapeGravity : state.attributes.horizontalGravity)
1225                : state.attributes.verticalGravity;
1226
1227        if (view == null) {
1228            if (showView) {
1229                state.view = view = new View(mContext);
1230                setColor(view, color, dividerColor, verticalBar, seascape);
1231                view.setTransitionName(state.attributes.transitionName);
1232                view.setId(state.attributes.id);
1233                visibilityChanged = true;
1234                view.setVisibility(INVISIBLE);
1235                state.targetVisibility = VISIBLE;
1236
1237                LayoutParams lp = new LayoutParams(resolvedWidth, resolvedHeight,
1238                        resolvedGravity);
1239                if (seascape) {
1240                    lp.leftMargin = sideMargin;
1241                } else {
1242                    lp.rightMargin = sideMargin;
1243                }
1244                addView(view, lp);
1245                updateColorViewTranslations();
1246            }
1247        } else {
1248            int vis = showView ? VISIBLE : INVISIBLE;
1249            visibilityChanged = state.targetVisibility != vis;
1250            state.targetVisibility = vis;
1251            LayoutParams lp = (LayoutParams) view.getLayoutParams();
1252            int rightMargin = seascape ? 0 : sideMargin;
1253            int leftMargin = seascape ? sideMargin : 0;
1254            if (lp.height != resolvedHeight || lp.width != resolvedWidth
1255                    || lp.gravity != resolvedGravity || lp.rightMargin != rightMargin
1256                    || lp.leftMargin != leftMargin) {
1257                lp.height = resolvedHeight;
1258                lp.width = resolvedWidth;
1259                lp.gravity = resolvedGravity;
1260                lp.rightMargin = rightMargin;
1261                lp.leftMargin = leftMargin;
1262                view.setLayoutParams(lp);
1263            }
1264            if (showView) {
1265                setColor(view, color, dividerColor, verticalBar, seascape);
1266            }
1267        }
1268        if (visibilityChanged) {
1269            view.animate().cancel();
1270            if (animate && !isResizing()) {
1271                if (showView) {
1272                    if (view.getVisibility() != VISIBLE) {
1273                        view.setVisibility(VISIBLE);
1274                        view.setAlpha(0.0f);
1275                    }
1276                    view.animate().alpha(1.0f).setInterpolator(mShowInterpolator).
1277                            setDuration(mBarEnterExitDuration);
1278                } else {
1279                    view.animate().alpha(0.0f).setInterpolator(mHideInterpolator)
1280                            .setDuration(mBarEnterExitDuration)
1281                            .withEndAction(new Runnable() {
1282                                @Override
1283                                public void run() {
1284                                    state.view.setAlpha(1.0f);
1285                                    state.view.setVisibility(INVISIBLE);
1286                                }
1287                            });
1288                }
1289            } else {
1290                view.setAlpha(1.0f);
1291                view.setVisibility(showView ? VISIBLE : INVISIBLE);
1292            }
1293        }
1294        state.visible = show;
1295        state.color = color;
1296    }
1297
1298    private static void setColor(View v, int color, int dividerColor, boolean verticalBar,
1299            boolean seascape) {
1300        if (dividerColor != 0) {
1301            final Pair<Boolean, Boolean> dir = (Pair<Boolean, Boolean>) v.getTag();
1302            if (dir == null || dir.first != verticalBar || dir.second != seascape) {
1303                final int size = Math.round(
1304                        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
1305                                v.getContext().getResources().getDisplayMetrics()));
1306                // Use an inset to make the divider line on the side that faces the app.
1307                final InsetDrawable d = new InsetDrawable(new ColorDrawable(color),
1308                        verticalBar && !seascape ? size : 0,
1309                        !verticalBar ? size : 0,
1310                        verticalBar && seascape ? size : 0, 0);
1311                v.setBackground(new LayerDrawable(new Drawable[] {
1312                        new ColorDrawable(dividerColor), d }));
1313                v.setTag(new Pair<>(verticalBar, seascape));
1314            } else {
1315                final LayerDrawable d = (LayerDrawable) v.getBackground();
1316                final InsetDrawable inset = ((InsetDrawable) d.getDrawable(1));
1317                ((ColorDrawable) inset.getDrawable()).setColor(color);
1318                ((ColorDrawable) d.getDrawable(0)).setColor(dividerColor);
1319            }
1320        } else {
1321            v.setTag(null);
1322            v.setBackgroundColor(color);
1323        }
1324    }
1325
1326    private void updateColorViewTranslations() {
1327        // Put the color views back in place when they get moved off the screen
1328        // due to the the ViewRootImpl panning.
1329        int rootScrollY = mRootScrollY;
1330        if (mStatusColorViewState.view != null) {
1331            mStatusColorViewState.view.setTranslationY(rootScrollY > 0 ? rootScrollY : 0);
1332        }
1333        if (mNavigationColorViewState.view != null) {
1334            mNavigationColorViewState.view.setTranslationY(rootScrollY < 0 ? rootScrollY : 0);
1335        }
1336    }
1337
1338    private WindowInsets updateStatusGuard(WindowInsets insets) {
1339        boolean showStatusGuard = false;
1340        // Show the status guard when the non-overlay contextual action bar is showing
1341        if (mPrimaryActionModeView != null) {
1342            if (mPrimaryActionModeView.getLayoutParams() instanceof MarginLayoutParams) {
1343                // Insets are magic!
1344                final MarginLayoutParams mlp = (MarginLayoutParams)
1345                        mPrimaryActionModeView.getLayoutParams();
1346                boolean mlpChanged = false;
1347                if (mPrimaryActionModeView.isShown()) {
1348                    if (mTempRect == null) {
1349                        mTempRect = new Rect();
1350                    }
1351                    final Rect rect = mTempRect;
1352
1353                    // If the parent doesn't consume the insets, manually
1354                    // apply the default system window insets.
1355                    mWindow.mContentParent.computeSystemWindowInsets(insets, rect);
1356                    final int newMargin = rect.top == 0 ? insets.getSystemWindowInsetTop() : 0;
1357                    if (mlp.topMargin != newMargin) {
1358                        mlpChanged = true;
1359                        mlp.topMargin = insets.getSystemWindowInsetTop();
1360
1361                        if (mStatusGuard == null) {
1362                            mStatusGuard = new View(mContext);
1363                            mStatusGuard.setBackgroundColor(mContext.getColor(
1364                                    R.color.decor_view_status_guard));
1365                            addView(mStatusGuard, indexOfChild(mStatusColorViewState.view),
1366                                    new LayoutParams(LayoutParams.MATCH_PARENT,
1367                                            mlp.topMargin, Gravity.START | Gravity.TOP));
1368                        } else {
1369                            final LayoutParams lp = (LayoutParams)
1370                                    mStatusGuard.getLayoutParams();
1371                            if (lp.height != mlp.topMargin) {
1372                                lp.height = mlp.topMargin;
1373                                mStatusGuard.setLayoutParams(lp);
1374                            }
1375                        }
1376                    }
1377
1378                    // The action mode's theme may differ from the app, so
1379                    // always show the status guard above it if we have one.
1380                    showStatusGuard = mStatusGuard != null;
1381
1382                    // We only need to consume the insets if the action
1383                    // mode is overlaid on the app content (e.g. it's
1384                    // sitting in a FrameLayout, see
1385                    // screen_simple_overlay_action_mode.xml).
1386                    final boolean nonOverlay = (mWindow.getLocalFeaturesPrivate()
1387                            & (1 << Window.FEATURE_ACTION_MODE_OVERLAY)) == 0;
1388                    insets = insets.consumeSystemWindowInsets(
1389                            false, nonOverlay && showStatusGuard /* top */, false, false);
1390                } else {
1391                    // reset top margin
1392                    if (mlp.topMargin != 0) {
1393                        mlpChanged = true;
1394                        mlp.topMargin = 0;
1395                    }
1396                }
1397                if (mlpChanged) {
1398                    mPrimaryActionModeView.setLayoutParams(mlp);
1399                }
1400            }
1401        }
1402        if (mStatusGuard != null) {
1403            mStatusGuard.setVisibility(showStatusGuard ? View.VISIBLE : View.GONE);
1404        }
1405        return insets;
1406    }
1407
1408    /**
1409     * Overrides the view outline when the activity enters picture-in-picture to ensure that it has
1410     * an opaque shadow even if the window background is completely transparent. This only applies
1411     * to activities that are currently the task root.
1412     */
1413    public void updatePictureInPictureOutlineProvider(boolean isInPictureInPictureMode) {
1414        if (mIsInPictureInPictureMode == isInPictureInPictureMode) {
1415            return;
1416        }
1417
1418        if (isInPictureInPictureMode) {
1419            final Window.WindowControllerCallback callback =
1420                    mWindow.getWindowControllerCallback();
1421            if (callback != null && callback.isTaskRoot()) {
1422                // Call super implementation directly as we don't want to save the PIP outline
1423                // provider to be restored
1424                super.setOutlineProvider(PIP_OUTLINE_PROVIDER);
1425            }
1426        } else {
1427            // Restore the previous outline provider
1428            if (getOutlineProvider() != mLastOutlineProvider) {
1429                setOutlineProvider(mLastOutlineProvider);
1430            }
1431        }
1432        mIsInPictureInPictureMode = isInPictureInPictureMode;
1433    }
1434
1435    @Override
1436    public void setOutlineProvider(ViewOutlineProvider provider) {
1437        super.setOutlineProvider(provider);
1438
1439        // Save the outline provider set to ensure that we can restore when the activity leaves PiP
1440        mLastOutlineProvider = provider;
1441    }
1442
1443    private void drawableChanged() {
1444        if (mChanging) {
1445            return;
1446        }
1447
1448        setPadding(mFramePadding.left + mBackgroundPadding.left,
1449                mFramePadding.top + mBackgroundPadding.top,
1450                mFramePadding.right + mBackgroundPadding.right,
1451                mFramePadding.bottom + mBackgroundPadding.bottom);
1452        requestLayout();
1453        invalidate();
1454
1455        int opacity = PixelFormat.OPAQUE;
1456        final WindowConfiguration winConfig = getResources().getConfiguration().windowConfiguration;
1457        if (winConfig.hasWindowShadow()) {
1458            // If the window has a shadow, it must be translucent.
1459            opacity = PixelFormat.TRANSLUCENT;
1460        } else{
1461            // Note: If there is no background, we will assume opaque. The
1462            // common case seems to be that an application sets there to be
1463            // no background so it can draw everything itself. For that,
1464            // we would like to assume OPAQUE and let the app force it to
1465            // the slower TRANSLUCENT mode if that is really what it wants.
1466            Drawable bg = getBackground();
1467            Drawable fg = getForeground();
1468            if (bg != null) {
1469                if (fg == null) {
1470                    opacity = bg.getOpacity();
1471                } else if (mFramePadding.left <= 0 && mFramePadding.top <= 0
1472                        && mFramePadding.right <= 0 && mFramePadding.bottom <= 0) {
1473                    // If the frame padding is zero, then we can be opaque
1474                    // if either the frame -or- the background is opaque.
1475                    int fop = fg.getOpacity();
1476                    int bop = bg.getOpacity();
1477                    if (false)
1478                        Log.v(mLogTag, "Background opacity: " + bop + ", Frame opacity: " + fop);
1479                    if (fop == PixelFormat.OPAQUE || bop == PixelFormat.OPAQUE) {
1480                        opacity = PixelFormat.OPAQUE;
1481                    } else if (fop == PixelFormat.UNKNOWN) {
1482                        opacity = bop;
1483                    } else if (bop == PixelFormat.UNKNOWN) {
1484                        opacity = fop;
1485                    } else {
1486                        opacity = Drawable.resolveOpacity(fop, bop);
1487                    }
1488                } else {
1489                    // For now we have to assume translucent if there is a
1490                    // frame with padding... there is no way to tell if the
1491                    // frame and background together will draw all pixels.
1492                    if (false)
1493                        Log.v(mLogTag, "Padding: " + mFramePadding);
1494                    opacity = PixelFormat.TRANSLUCENT;
1495                }
1496            }
1497            if (false)
1498                Log.v(mLogTag, "Background: " + bg + ", Frame: " + fg);
1499        }
1500
1501        if (false)
1502            Log.v(mLogTag, "Selected default opacity: " + opacity);
1503
1504        mDefaultOpacity = opacity;
1505        if (mFeatureId < 0) {
1506            mWindow.setDefaultWindowFormat(opacity);
1507        }
1508    }
1509
1510    @Override
1511    public void onWindowFocusChanged(boolean hasWindowFocus) {
1512        super.onWindowFocusChanged(hasWindowFocus);
1513
1514        // If the user is chording a menu shortcut, release the chord since
1515        // this window lost focus
1516        if (mWindow.hasFeature(Window.FEATURE_OPTIONS_PANEL) && !hasWindowFocus
1517                && mWindow.mPanelChordingKey != 0) {
1518            mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
1519        }
1520
1521        final Window.Callback cb = mWindow.getCallback();
1522        if (cb != null && !mWindow.isDestroyed() && mFeatureId < 0) {
1523            cb.onWindowFocusChanged(hasWindowFocus);
1524        }
1525
1526        if (mPrimaryActionMode != null) {
1527            mPrimaryActionMode.onWindowFocusChanged(hasWindowFocus);
1528        }
1529        if (mFloatingActionMode != null) {
1530            mFloatingActionMode.onWindowFocusChanged(hasWindowFocus);
1531        }
1532
1533        updateElevation();
1534    }
1535
1536    @Override
1537    protected void onAttachedToWindow() {
1538        super.onAttachedToWindow();
1539
1540        final Window.Callback cb = mWindow.getCallback();
1541        if (cb != null && !mWindow.isDestroyed() && mFeatureId < 0) {
1542            cb.onAttachedToWindow();
1543        }
1544
1545        if (mFeatureId == -1) {
1546            /*
1547             * The main window has been attached, try to restore any panels
1548             * that may have been open before. This is called in cases where
1549             * an activity is being killed for configuration change and the
1550             * menu was open. When the activity is recreated, the menu
1551             * should be shown again.
1552             */
1553            mWindow.openPanelsAfterRestore();
1554        }
1555
1556        if (!mWindowResizeCallbacksAdded) {
1557            // If there is no window callback installed there was no window set before. Set it now.
1558            // Note that our ViewRootImpl object will not change.
1559            getViewRootImpl().addWindowCallbacks(this);
1560            mWindowResizeCallbacksAdded = true;
1561        } else if (mBackdropFrameRenderer != null) {
1562            // We are resizing and this call happened due to a configuration change. Tell the
1563            // renderer about it.
1564            mBackdropFrameRenderer.onConfigurationChange();
1565        }
1566        mWindow.onViewRootImplSet(getViewRootImpl());
1567    }
1568
1569    @Override
1570    protected void onDetachedFromWindow() {
1571        super.onDetachedFromWindow();
1572
1573        final Window.Callback cb = mWindow.getCallback();
1574        if (cb != null && mFeatureId < 0) {
1575            cb.onDetachedFromWindow();
1576        }
1577
1578        if (mWindow.mDecorContentParent != null) {
1579            mWindow.mDecorContentParent.dismissPopups();
1580        }
1581
1582        if (mPrimaryActionModePopup != null) {
1583            removeCallbacks(mShowPrimaryActionModePopup);
1584            if (mPrimaryActionModePopup.isShowing()) {
1585                mPrimaryActionModePopup.dismiss();
1586            }
1587            mPrimaryActionModePopup = null;
1588        }
1589        if (mFloatingToolbar != null) {
1590            mFloatingToolbar.dismiss();
1591            mFloatingToolbar = null;
1592        }
1593
1594        PhoneWindow.PanelFeatureState st = mWindow.getPanelState(Window.FEATURE_OPTIONS_PANEL, false);
1595        if (st != null && st.menu != null && mFeatureId < 0) {
1596            st.menu.close();
1597        }
1598
1599        releaseThreadedRenderer();
1600
1601        if (mWindowResizeCallbacksAdded) {
1602            getViewRootImpl().removeWindowCallbacks(this);
1603            mWindowResizeCallbacksAdded = false;
1604        }
1605    }
1606
1607    @Override
1608    public void onCloseSystemDialogs(String reason) {
1609        if (mFeatureId >= 0) {
1610            mWindow.closeAllPanels();
1611        }
1612    }
1613
1614    public android.view.SurfaceHolder.Callback2 willYouTakeTheSurface() {
1615        return mFeatureId < 0 ? mWindow.mTakeSurfaceCallback : null;
1616    }
1617
1618    public InputQueue.Callback willYouTakeTheInputQueue() {
1619        return mFeatureId < 0 ? mWindow.mTakeInputQueueCallback : null;
1620    }
1621
1622    public void setSurfaceType(int type) {
1623        mWindow.setType(type);
1624    }
1625
1626    public void setSurfaceFormat(int format) {
1627        mWindow.setFormat(format);
1628    }
1629
1630    public void setSurfaceKeepScreenOn(boolean keepOn) {
1631        if (keepOn) mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1632        else mWindow.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
1633    }
1634
1635    @Override
1636    public void onRootViewScrollYChanged(int rootScrollY) {
1637        mRootScrollY = rootScrollY;
1638        updateColorViewTranslations();
1639    }
1640
1641    private ActionMode createActionMode(
1642            int type, ActionMode.Callback2 callback, View originatingView) {
1643        switch (type) {
1644            case ActionMode.TYPE_PRIMARY:
1645            default:
1646                return createStandaloneActionMode(callback);
1647            case ActionMode.TYPE_FLOATING:
1648                return createFloatingActionMode(originatingView, callback);
1649        }
1650    }
1651
1652    private void setHandledActionMode(ActionMode mode) {
1653        if (mode.getType() == ActionMode.TYPE_PRIMARY) {
1654            setHandledPrimaryActionMode(mode);
1655        } else if (mode.getType() == ActionMode.TYPE_FLOATING) {
1656            setHandledFloatingActionMode(mode);
1657        }
1658    }
1659
1660    private ActionMode createStandaloneActionMode(ActionMode.Callback callback) {
1661        endOnGoingFadeAnimation();
1662        cleanupPrimaryActionMode();
1663        // We want to create new mPrimaryActionModeView in two cases: if there is no existing
1664        // instance at all, or if there is one, but it is detached from window. The latter case
1665        // might happen when app is resized in multi-window mode and decor view is preserved
1666        // along with the main app window. Keeping mPrimaryActionModeView reference doesn't cause
1667        // app memory leaks because killMode() is called when the dismiss animation ends and from
1668        // cleanupPrimaryActionMode() invocation above.
1669        if (mPrimaryActionModeView == null || !mPrimaryActionModeView.isAttachedToWindow()) {
1670            if (mWindow.isFloating()) {
1671                // Use the action bar theme.
1672                final TypedValue outValue = new TypedValue();
1673                final Resources.Theme baseTheme = mContext.getTheme();
1674                baseTheme.resolveAttribute(R.attr.actionBarTheme, outValue, true);
1675
1676                final Context actionBarContext;
1677                if (outValue.resourceId != 0) {
1678                    final Resources.Theme actionBarTheme = mContext.getResources().newTheme();
1679                    actionBarTheme.setTo(baseTheme);
1680                    actionBarTheme.applyStyle(outValue.resourceId, true);
1681
1682                    actionBarContext = new ContextThemeWrapper(mContext, 0);
1683                    actionBarContext.getTheme().setTo(actionBarTheme);
1684                } else {
1685                    actionBarContext = mContext;
1686                }
1687
1688                mPrimaryActionModeView = new ActionBarContextView(actionBarContext);
1689                mPrimaryActionModePopup = new PopupWindow(actionBarContext, null,
1690                        R.attr.actionModePopupWindowStyle);
1691                mPrimaryActionModePopup.setWindowLayoutType(
1692                        WindowManager.LayoutParams.TYPE_APPLICATION);
1693                mPrimaryActionModePopup.setContentView(mPrimaryActionModeView);
1694                mPrimaryActionModePopup.setWidth(MATCH_PARENT);
1695
1696                actionBarContext.getTheme().resolveAttribute(
1697                        R.attr.actionBarSize, outValue, true);
1698                final int height = TypedValue.complexToDimensionPixelSize(outValue.data,
1699                        actionBarContext.getResources().getDisplayMetrics());
1700                mPrimaryActionModeView.setContentHeight(height);
1701                mPrimaryActionModePopup.setHeight(WRAP_CONTENT);
1702                mShowPrimaryActionModePopup = new Runnable() {
1703                    public void run() {
1704                        mPrimaryActionModePopup.showAtLocation(
1705                                mPrimaryActionModeView.getApplicationWindowToken(),
1706                                Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
1707                        endOnGoingFadeAnimation();
1708
1709                        if (shouldAnimatePrimaryActionModeView()) {
1710                            mFadeAnim = ObjectAnimator.ofFloat(mPrimaryActionModeView, View.ALPHA,
1711                                    0f, 1f);
1712                            mFadeAnim.addListener(new AnimatorListenerAdapter() {
1713                                @Override
1714                                public void onAnimationStart(Animator animation) {
1715                                    mPrimaryActionModeView.setVisibility(VISIBLE);
1716                                }
1717
1718                                @Override
1719                                public void onAnimationEnd(Animator animation) {
1720                                    mPrimaryActionModeView.setAlpha(1f);
1721                                    mFadeAnim = null;
1722                                }
1723                            });
1724                            mFadeAnim.start();
1725                        } else {
1726                            mPrimaryActionModeView.setAlpha(1f);
1727                            mPrimaryActionModeView.setVisibility(VISIBLE);
1728                        }
1729                    }
1730                };
1731            } else {
1732                ViewStub stub = findViewById(R.id.action_mode_bar_stub);
1733                if (stub != null) {
1734                    mPrimaryActionModeView = (ActionBarContextView) stub.inflate();
1735                    mPrimaryActionModePopup = null;
1736                }
1737            }
1738        }
1739        if (mPrimaryActionModeView != null) {
1740            mPrimaryActionModeView.killMode();
1741            ActionMode mode = new StandaloneActionMode(
1742                    mPrimaryActionModeView.getContext(), mPrimaryActionModeView,
1743                    callback, mPrimaryActionModePopup == null);
1744            return mode;
1745        }
1746        return null;
1747    }
1748
1749    private void endOnGoingFadeAnimation() {
1750        if (mFadeAnim != null) {
1751            mFadeAnim.end();
1752        }
1753    }
1754
1755    private void setHandledPrimaryActionMode(ActionMode mode) {
1756        endOnGoingFadeAnimation();
1757        mPrimaryActionMode = mode;
1758        mPrimaryActionMode.invalidate();
1759        mPrimaryActionModeView.initForMode(mPrimaryActionMode);
1760        if (mPrimaryActionModePopup != null) {
1761            post(mShowPrimaryActionModePopup);
1762        } else {
1763            if (shouldAnimatePrimaryActionModeView()) {
1764                mFadeAnim = ObjectAnimator.ofFloat(mPrimaryActionModeView, View.ALPHA, 0f, 1f);
1765                mFadeAnim.addListener(new AnimatorListenerAdapter() {
1766                    @Override
1767                    public void onAnimationStart(Animator animation) {
1768                        mPrimaryActionModeView.setVisibility(View.VISIBLE);
1769                    }
1770
1771                    @Override
1772                    public void onAnimationEnd(Animator animation) {
1773                        mPrimaryActionModeView.setAlpha(1f);
1774                        mFadeAnim = null;
1775                    }
1776                });
1777                mFadeAnim.start();
1778            } else {
1779                mPrimaryActionModeView.setAlpha(1f);
1780                mPrimaryActionModeView.setVisibility(View.VISIBLE);
1781            }
1782        }
1783        mPrimaryActionModeView.sendAccessibilityEvent(
1784                AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
1785    }
1786
1787    boolean shouldAnimatePrimaryActionModeView() {
1788        // We only to animate the action mode in if the decor has already been laid out.
1789        // If it hasn't been laid out, it hasn't been drawn to screen yet.
1790        return isLaidOut();
1791    }
1792
1793    private ActionMode createFloatingActionMode(
1794            View originatingView, ActionMode.Callback2 callback) {
1795        if (mFloatingActionMode != null) {
1796            mFloatingActionMode.finish();
1797        }
1798        cleanupFloatingActionModeViews();
1799        mFloatingToolbar = new FloatingToolbar(mWindow);
1800        final FloatingActionMode mode =
1801                new FloatingActionMode(mContext, callback, originatingView, mFloatingToolbar);
1802        mFloatingActionModeOriginatingView = originatingView;
1803        mFloatingToolbarPreDrawListener =
1804            new ViewTreeObserver.OnPreDrawListener() {
1805                @Override
1806                public boolean onPreDraw() {
1807                    mode.updateViewLocationInWindow();
1808                    return true;
1809                }
1810            };
1811        return mode;
1812    }
1813
1814    private void setHandledFloatingActionMode(ActionMode mode) {
1815        mFloatingActionMode = mode;
1816        mFloatingActionMode.invalidate();  // Will show the floating toolbar if necessary.
1817        mFloatingActionModeOriginatingView.getViewTreeObserver()
1818            .addOnPreDrawListener(mFloatingToolbarPreDrawListener);
1819    }
1820
1821    /**
1822     * Informs the decor if the caption is attached and visible.
1823     * @param attachedAndVisible true when the decor is visible.
1824     * Note that this will even be called if there is no caption.
1825     **/
1826    void enableCaption(boolean attachedAndVisible) {
1827        if (mHasCaption != attachedAndVisible) {
1828            mHasCaption = attachedAndVisible;
1829            if (getForeground() != null) {
1830                drawableChanged();
1831            }
1832        }
1833    }
1834
1835    void setWindow(PhoneWindow phoneWindow) {
1836        mWindow = phoneWindow;
1837        Context context = getContext();
1838        if (context instanceof DecorContext) {
1839            DecorContext decorContext = (DecorContext) context;
1840            decorContext.setPhoneWindow(mWindow);
1841        }
1842    }
1843
1844    @Override
1845    public Resources getResources() {
1846        // Make sure the Resources object is propogated from the Context since it can be updated in
1847        // the Context object.
1848        return getContext().getResources();
1849    }
1850
1851    @Override
1852    protected void onConfigurationChanged(Configuration newConfig) {
1853        super.onConfigurationChanged(newConfig);
1854
1855        final boolean displayWindowDecor =
1856                newConfig.windowConfiguration.hasWindowDecorCaption();
1857        if (mDecorCaptionView == null && displayWindowDecor) {
1858            // Configuration now requires a caption.
1859            final LayoutInflater inflater = mWindow.getLayoutInflater();
1860            mDecorCaptionView = createDecorCaptionView(inflater);
1861            if (mDecorCaptionView != null) {
1862                if (mDecorCaptionView.getParent() == null) {
1863                    addView(mDecorCaptionView, 0,
1864                            new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1865                }
1866                removeView(mContentRoot);
1867                mDecorCaptionView.addView(mContentRoot,
1868                        new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
1869            }
1870        } else if (mDecorCaptionView != null) {
1871            // We might have to change the kind of surface before we do anything else.
1872            mDecorCaptionView.onConfigurationChanged(displayWindowDecor);
1873            enableCaption(displayWindowDecor);
1874        }
1875
1876        updateAvailableWidth();
1877        initializeElevation();
1878    }
1879
1880    void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
1881        if (mBackdropFrameRenderer != null) {
1882            loadBackgroundDrawablesIfNeeded();
1883            mBackdropFrameRenderer.onResourcesLoaded(
1884                    this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
1885                    mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
1886                    getCurrentColor(mNavigationColorViewState));
1887        }
1888
1889        mDecorCaptionView = createDecorCaptionView(inflater);
1890        final View root = inflater.inflate(layoutResource, null);
1891        if (mDecorCaptionView != null) {
1892            if (mDecorCaptionView.getParent() == null) {
1893                addView(mDecorCaptionView,
1894                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1895            }
1896            mDecorCaptionView.addView(root,
1897                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
1898        } else {
1899
1900            // Put it below the color views.
1901            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1902        }
1903        mContentRoot = (ViewGroup) root;
1904        initializeElevation();
1905    }
1906
1907    private void loadBackgroundDrawablesIfNeeded() {
1908        if (mResizingBackgroundDrawable == null) {
1909            mResizingBackgroundDrawable = getResizingBackgroundDrawable(getContext(),
1910                    mWindow.mBackgroundResource, mWindow.mBackgroundFallbackResource,
1911                    mWindow.isTranslucent() || mWindow.isShowingWallpaper());
1912            if (mResizingBackgroundDrawable == null) {
1913                // We shouldn't really get here as the background fallback should be always
1914                // available since it is defaulted by the system.
1915                Log.w(mLogTag, "Failed to find background drawable for PhoneWindow=" + mWindow);
1916            }
1917        }
1918        if (mCaptionBackgroundDrawable == null) {
1919            mCaptionBackgroundDrawable = getContext().getDrawable(
1920                    R.drawable.decor_caption_title_focused);
1921        }
1922        if (mResizingBackgroundDrawable != null) {
1923            mLastBackgroundDrawableCb = mResizingBackgroundDrawable.getCallback();
1924            mResizingBackgroundDrawable.setCallback(null);
1925        }
1926    }
1927
1928    // Free floating overlapping windows require a caption.
1929    private DecorCaptionView createDecorCaptionView(LayoutInflater inflater) {
1930        DecorCaptionView decorCaptionView = null;
1931        for (int i = getChildCount() - 1; i >= 0 && decorCaptionView == null; i--) {
1932            View view = getChildAt(i);
1933            if (view instanceof DecorCaptionView) {
1934                // The decor was most likely saved from a relaunch - so reuse it.
1935                decorCaptionView = (DecorCaptionView) view;
1936                removeViewAt(i);
1937            }
1938        }
1939        final WindowManager.LayoutParams attrs = mWindow.getAttributes();
1940        final boolean isApplication = attrs.type == TYPE_BASE_APPLICATION ||
1941                attrs.type == TYPE_APPLICATION || attrs.type == TYPE_DRAWN_APPLICATION;
1942        final WindowConfiguration winConfig = getResources().getConfiguration().windowConfiguration;
1943        // Only a non floating application window on one of the allowed workspaces can get a caption
1944        if (!mWindow.isFloating() && isApplication && winConfig.hasWindowDecorCaption()) {
1945            // Dependent on the brightness of the used title we either use the
1946            // dark or the light button frame.
1947            if (decorCaptionView == null) {
1948                decorCaptionView = inflateDecorCaptionView(inflater);
1949            }
1950            decorCaptionView.setPhoneWindow(mWindow, true /*showDecor*/);
1951        } else {
1952            decorCaptionView = null;
1953        }
1954
1955        // Tell the decor if it has a visible caption.
1956        enableCaption(decorCaptionView != null);
1957        return decorCaptionView;
1958    }
1959
1960    private DecorCaptionView inflateDecorCaptionView(LayoutInflater inflater) {
1961        final Context context = getContext();
1962        // We make a copy of the inflater, so it has the right context associated with it.
1963        inflater = inflater.from(context);
1964        final DecorCaptionView view = (DecorCaptionView) inflater.inflate(R.layout.decor_caption,
1965                null);
1966        setDecorCaptionShade(context, view);
1967        return view;
1968    }
1969
1970    private void setDecorCaptionShade(Context context, DecorCaptionView view) {
1971        final int shade = mWindow.getDecorCaptionShade();
1972        switch (shade) {
1973            case DECOR_CAPTION_SHADE_LIGHT:
1974                setLightDecorCaptionShade(view);
1975                break;
1976            case DECOR_CAPTION_SHADE_DARK:
1977                setDarkDecorCaptionShade(view);
1978                break;
1979            default: {
1980                TypedValue value = new TypedValue();
1981                context.getTheme().resolveAttribute(R.attr.colorPrimary, value, true);
1982                // We invert the shade depending on brightness of the theme. Dark shade for light
1983                // theme and vice versa. Thanks to this the buttons should be visible on the
1984                // background.
1985                if (Color.luminance(value.data) < 0.5) {
1986                    setLightDecorCaptionShade(view);
1987                } else {
1988                    setDarkDecorCaptionShade(view);
1989                }
1990                break;
1991            }
1992        }
1993    }
1994
1995    void updateDecorCaptionShade() {
1996        if (mDecorCaptionView != null) {
1997            setDecorCaptionShade(getContext(), mDecorCaptionView);
1998        }
1999    }
2000
2001    private void setLightDecorCaptionShade(DecorCaptionView view) {
2002        view.findViewById(R.id.maximize_window).setBackgroundResource(
2003                R.drawable.decor_maximize_button_light);
2004        view.findViewById(R.id.close_window).setBackgroundResource(
2005                R.drawable.decor_close_button_light);
2006    }
2007
2008    private void setDarkDecorCaptionShade(DecorCaptionView view) {
2009        view.findViewById(R.id.maximize_window).setBackgroundResource(
2010                R.drawable.decor_maximize_button_dark);
2011        view.findViewById(R.id.close_window).setBackgroundResource(
2012                R.drawable.decor_close_button_dark);
2013    }
2014
2015    /**
2016     * Returns the color used to fill areas the app has not rendered content to yet when the
2017     * user is resizing the window of an activity in multi-window mode.
2018     */
2019    public static Drawable getResizingBackgroundDrawable(Context context, int backgroundRes,
2020            int backgroundFallbackRes, boolean windowTranslucent) {
2021        if (backgroundRes != 0) {
2022            final Drawable drawable = context.getDrawable(backgroundRes);
2023            if (drawable != null) {
2024                return enforceNonTranslucentBackground(drawable, windowTranslucent);
2025            }
2026        }
2027
2028        if (backgroundFallbackRes != 0) {
2029            final Drawable fallbackDrawable = context.getDrawable(backgroundFallbackRes);
2030            if (fallbackDrawable != null) {
2031                return enforceNonTranslucentBackground(fallbackDrawable, windowTranslucent);
2032            }
2033        }
2034        return new ColorDrawable(Color.BLACK);
2035    }
2036
2037    /**
2038     * Enforces a drawable to be non-translucent to act as a background if needed, i.e. if the
2039     * window is not translucent.
2040     */
2041    private static Drawable enforceNonTranslucentBackground(Drawable drawable,
2042            boolean windowTranslucent) {
2043        if (!windowTranslucent && drawable instanceof ColorDrawable) {
2044            ColorDrawable colorDrawable = (ColorDrawable) drawable;
2045            int color = colorDrawable.getColor();
2046            if (Color.alpha(color) != 255) {
2047                ColorDrawable copy = (ColorDrawable) colorDrawable.getConstantState().newDrawable()
2048                        .mutate();
2049                copy.setColor(
2050                        Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)));
2051                return copy;
2052            }
2053        }
2054        return drawable;
2055    }
2056
2057    void clearContentView() {
2058        if (mDecorCaptionView != null) {
2059            mDecorCaptionView.removeContentView();
2060        } else {
2061            // This window doesn't have caption, so we need to remove everything except our views
2062            // we might have added.
2063            for (int i = getChildCount() - 1; i >= 0; i--) {
2064                View v = getChildAt(i);
2065                if (v != mStatusColorViewState.view && v != mNavigationColorViewState.view
2066                        && v != mStatusGuard) {
2067                    removeViewAt(i);
2068                }
2069            }
2070        }
2071    }
2072
2073    @Override
2074    public void onWindowSizeIsChanging(Rect newBounds, boolean fullscreen, Rect systemInsets,
2075            Rect stableInsets) {
2076        if (mBackdropFrameRenderer != null) {
2077            mBackdropFrameRenderer.setTargetRect(newBounds, fullscreen, systemInsets, stableInsets);
2078        }
2079    }
2080
2081    @Override
2082    public void onWindowDragResizeStart(Rect initialBounds, boolean fullscreen, Rect systemInsets,
2083            Rect stableInsets, int resizeMode) {
2084        if (mWindow.isDestroyed()) {
2085            // If the owner's window is gone, we should not be able to come here anymore.
2086            releaseThreadedRenderer();
2087            return;
2088        }
2089        if (mBackdropFrameRenderer != null) {
2090            return;
2091        }
2092        final ThreadedRenderer renderer = getThreadedRenderer();
2093        if (renderer != null) {
2094            loadBackgroundDrawablesIfNeeded();
2095            mBackdropFrameRenderer = new BackdropFrameRenderer(this, renderer,
2096                    initialBounds, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
2097                    mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
2098                    getCurrentColor(mNavigationColorViewState), fullscreen, systemInsets,
2099                    stableInsets, resizeMode);
2100
2101            // Get rid of the shadow while we are resizing. Shadow drawing takes considerable time.
2102            // If we want to get the shadow shown while resizing, we would need to elevate a new
2103            // element which owns the caption and has the elevation.
2104            updateElevation();
2105
2106            updateColorViews(null /* insets */, false);
2107        }
2108        mResizeMode = resizeMode;
2109        getViewRootImpl().requestInvalidateRootRenderNode();
2110    }
2111
2112    @Override
2113    public void onWindowDragResizeEnd() {
2114        releaseThreadedRenderer();
2115        updateColorViews(null /* insets */, false);
2116        mResizeMode = RESIZE_MODE_INVALID;
2117        getViewRootImpl().requestInvalidateRootRenderNode();
2118    }
2119
2120    @Override
2121    public boolean onContentDrawn(int offsetX, int offsetY, int sizeX, int sizeY) {
2122        if (mBackdropFrameRenderer == null) {
2123            return false;
2124        }
2125        return mBackdropFrameRenderer.onContentDrawn(offsetX, offsetY, sizeX, sizeY);
2126    }
2127
2128    @Override
2129    public void onRequestDraw(boolean reportNextDraw) {
2130        if (mBackdropFrameRenderer != null) {
2131            mBackdropFrameRenderer.onRequestDraw(reportNextDraw);
2132        } else if (reportNextDraw) {
2133            // If render thread is gone, just report immediately.
2134            if (isAttachedToWindow()) {
2135                getViewRootImpl().reportDrawFinish();
2136            }
2137        }
2138    }
2139
2140    @Override
2141    public void onPostDraw(DisplayListCanvas canvas) {
2142        drawResizingShadowIfNeeded(canvas);
2143    }
2144
2145    private void initResizingPaints() {
2146        final int startColor = mContext.getResources().getColor(
2147                R.color.resize_shadow_start_color, null);
2148        final int endColor = mContext.getResources().getColor(
2149                R.color.resize_shadow_end_color, null);
2150        final int middleColor = (startColor + endColor) / 2;
2151        mHorizontalResizeShadowPaint.setShader(new LinearGradient(
2152                0, 0, 0, mResizeShadowSize, new int[] { startColor, middleColor, endColor },
2153                new float[] { 0f, 0.3f, 1f }, Shader.TileMode.CLAMP));
2154        mVerticalResizeShadowPaint.setShader(new LinearGradient(
2155                0, 0, mResizeShadowSize, 0, new int[] { startColor, middleColor, endColor },
2156                new float[] { 0f, 0.3f, 1f }, Shader.TileMode.CLAMP));
2157    }
2158
2159    private void drawResizingShadowIfNeeded(DisplayListCanvas canvas) {
2160        if (mResizeMode != RESIZE_MODE_DOCKED_DIVIDER || mWindow.mIsFloating
2161                || mWindow.isTranslucent()
2162                || mWindow.isShowingWallpaper()) {
2163            return;
2164        }
2165        canvas.save();
2166        canvas.translate(0, getHeight() - mFrameOffsets.bottom);
2167        canvas.drawRect(0, 0, getWidth(), mResizeShadowSize, mHorizontalResizeShadowPaint);
2168        canvas.restore();
2169        canvas.save();
2170        canvas.translate(getWidth() - mFrameOffsets.right, 0);
2171        canvas.drawRect(0, 0, mResizeShadowSize, getHeight(), mVerticalResizeShadowPaint);
2172        canvas.restore();
2173    }
2174
2175    /** Release the renderer thread which is usually done when the user stops resizing. */
2176    private void releaseThreadedRenderer() {
2177        if (mResizingBackgroundDrawable != null && mLastBackgroundDrawableCb != null) {
2178            mResizingBackgroundDrawable.setCallback(mLastBackgroundDrawableCb);
2179            mLastBackgroundDrawableCb = null;
2180        }
2181
2182        if (mBackdropFrameRenderer != null) {
2183            mBackdropFrameRenderer.releaseRenderer();
2184            mBackdropFrameRenderer = null;
2185            // Bring the shadow back.
2186            updateElevation();
2187        }
2188    }
2189
2190    private boolean isResizing() {
2191        return mBackdropFrameRenderer != null;
2192    }
2193
2194    /**
2195     * The elevation gets set for the first time and the framework needs to be informed that
2196     * the surface layer gets created with the shadow size in mind.
2197     */
2198    private void initializeElevation() {
2199        // TODO(skuhne): Call setMaxElevation here accordingly after b/22668382 got fixed.
2200        mAllowUpdateElevation = false;
2201        updateElevation();
2202    }
2203
2204    private void updateElevation() {
2205        float elevation = 0;
2206        final boolean wasAdjustedForStack = mElevationAdjustedForStack;
2207        // Do not use a shadow when we are in resizing mode (mBackdropFrameRenderer not null)
2208        // since the shadow is bound to the content size and not the target size.
2209        final int windowingMode =
2210                getResources().getConfiguration().windowConfiguration.getWindowingMode();
2211        if ((windowingMode == WINDOWING_MODE_FREEFORM) && !isResizing()) {
2212            elevation = hasWindowFocus() ?
2213                    DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP : DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP;
2214            // Add a maximum shadow height value to the top level view.
2215            // Note that pinned stack doesn't have focus
2216            // so maximum shadow height adjustment isn't needed.
2217            // TODO(skuhne): Remove this if clause once b/22668382 got fixed.
2218            if (!mAllowUpdateElevation) {
2219                elevation = DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP;
2220            }
2221            // Convert the DP elevation into physical pixels.
2222            elevation = dipToPx(elevation);
2223            mElevationAdjustedForStack = true;
2224        } else if (windowingMode == WINDOWING_MODE_PINNED) {
2225            elevation = dipToPx(PINNED_WINDOWING_MODE_ELEVATION_IN_DIP);
2226            mElevationAdjustedForStack = true;
2227        } else {
2228            mElevationAdjustedForStack = false;
2229        }
2230
2231        // Don't change the elevation if we didn't previously adjust it for the stack it was in
2232        // or it didn't change.
2233        if ((wasAdjustedForStack || mElevationAdjustedForStack)
2234                && getElevation() != elevation) {
2235            mWindow.setElevation(elevation);
2236        }
2237    }
2238
2239    boolean isShowingCaption() {
2240        return mDecorCaptionView != null && mDecorCaptionView.isCaptionShowing();
2241    }
2242
2243    int getCaptionHeight() {
2244        return isShowingCaption() ? mDecorCaptionView.getCaptionHeight() : 0;
2245    }
2246
2247    /**
2248     * Converts a DIP measure into physical pixels.
2249     * @param dip The dip value.
2250     * @return Returns the number of pixels.
2251     */
2252    private float dipToPx(float dip) {
2253        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
2254                getResources().getDisplayMetrics());
2255    }
2256
2257    /**
2258     * Provide an override of the caption background drawable.
2259     */
2260    void setUserCaptionBackgroundDrawable(Drawable drawable) {
2261        mUserCaptionBackgroundDrawable = drawable;
2262        if (mBackdropFrameRenderer != null) {
2263            mBackdropFrameRenderer.setUserCaptionBackgroundDrawable(drawable);
2264        }
2265    }
2266
2267    private static String getTitleSuffix(WindowManager.LayoutParams params) {
2268        if (params == null) {
2269            return "";
2270        }
2271        final String[] split = params.getTitle().toString().split("\\.");
2272        if (split.length > 0) {
2273            return split[split.length - 1];
2274        } else {
2275            return "";
2276        }
2277    }
2278
2279    void updateLogTag(WindowManager.LayoutParams params) {
2280        mLogTag = TAG + "[" + getTitleSuffix(params) + "]";
2281    }
2282
2283    private void updateAvailableWidth() {
2284        Resources res = getResources();
2285        mAvailableWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2286                res.getConfiguration().screenWidthDp, res.getDisplayMetrics());
2287    }
2288
2289    /**
2290     * @hide
2291     */
2292    @Override
2293    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> list, int deviceId) {
2294        final PanelFeatureState st = mWindow.getPanelState(FEATURE_OPTIONS_PANEL, false);
2295        final Menu menu = st != null ? st.menu : null;
2296        if (!mWindow.isDestroyed() && mWindow.getCallback() != null) {
2297            mWindow.getCallback().onProvideKeyboardShortcuts(list, menu, deviceId);
2298        }
2299    }
2300
2301    @Override
2302    public void dispatchPointerCaptureChanged(boolean hasCapture) {
2303        super.dispatchPointerCaptureChanged(hasCapture);
2304        if (!mWindow.isDestroyed() && mWindow.getCallback() != null) {
2305            mWindow.getCallback().onPointerCaptureChanged(hasCapture);
2306        }
2307    }
2308
2309    @Override
2310    public int getAccessibilityViewId() {
2311        return AccessibilityNodeInfo.ROOT_ITEM_ID;
2312    }
2313
2314    @Override
2315    public String toString() {
2316        return "DecorView@" + Integer.toHexString(this.hashCode()) + "["
2317                + getTitleSuffix(mWindow.getAttributes()) + "]";
2318    }
2319
2320    private static class ColorViewState {
2321        View view = null;
2322        int targetVisibility = View.INVISIBLE;
2323        boolean present = false;
2324        boolean visible;
2325        int color;
2326
2327        final ColorViewAttributes attributes;
2328
2329        ColorViewState(ColorViewAttributes attributes) {
2330            this.attributes = attributes;
2331        }
2332    }
2333
2334    public static class ColorViewAttributes {
2335
2336        final int id;
2337        final int systemUiHideFlag;
2338        final int translucentFlag;
2339        final int verticalGravity;
2340        final int horizontalGravity;
2341        final int seascapeGravity;
2342        final String transitionName;
2343        final int hideWindowFlag;
2344
2345        private ColorViewAttributes(int systemUiHideFlag, int translucentFlag, int verticalGravity,
2346                int horizontalGravity, int seascapeGravity, String transitionName, int id,
2347                int hideWindowFlag) {
2348            this.id = id;
2349            this.systemUiHideFlag = systemUiHideFlag;
2350            this.translucentFlag = translucentFlag;
2351            this.verticalGravity = verticalGravity;
2352            this.horizontalGravity = horizontalGravity;
2353            this.seascapeGravity = seascapeGravity;
2354            this.transitionName = transitionName;
2355            this.hideWindowFlag = hideWindowFlag;
2356        }
2357
2358        public boolean isPresent(int sysUiVis, int windowFlags, boolean force) {
2359            return (sysUiVis & systemUiHideFlag) == 0
2360                    && (windowFlags & hideWindowFlag) == 0
2361                    && ((windowFlags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
2362                    || force);
2363        }
2364
2365        public boolean isVisible(boolean present, int color, int windowFlags, boolean force) {
2366            return present
2367                    && (color & Color.BLACK) != 0
2368                    && ((windowFlags & translucentFlag) == 0  || force);
2369        }
2370
2371        public boolean isVisible(int sysUiVis, int color, int windowFlags, boolean force) {
2372            final boolean present = isPresent(sysUiVis, windowFlags, force);
2373            return isVisible(present, color, windowFlags, force);
2374        }
2375    }
2376
2377    /**
2378     * Clears out internal references when the action mode is destroyed.
2379     */
2380    private class ActionModeCallback2Wrapper extends ActionMode.Callback2 {
2381        private final ActionMode.Callback mWrapped;
2382
2383        public ActionModeCallback2Wrapper(ActionMode.Callback wrapped) {
2384            mWrapped = wrapped;
2385        }
2386
2387        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2388            return mWrapped.onCreateActionMode(mode, menu);
2389        }
2390
2391        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2392            requestFitSystemWindows();
2393            return mWrapped.onPrepareActionMode(mode, menu);
2394        }
2395
2396        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2397            return mWrapped.onActionItemClicked(mode, item);
2398        }
2399
2400        public void onDestroyActionMode(ActionMode mode) {
2401            mWrapped.onDestroyActionMode(mode);
2402            final boolean isMncApp = mContext.getApplicationInfo().targetSdkVersion
2403                    >= M;
2404            final boolean isPrimary;
2405            final boolean isFloating;
2406            if (isMncApp) {
2407                isPrimary = mode == mPrimaryActionMode;
2408                isFloating = mode == mFloatingActionMode;
2409                if (!isPrimary && mode.getType() == ActionMode.TYPE_PRIMARY) {
2410                    Log.e(mLogTag, "Destroying unexpected ActionMode instance of TYPE_PRIMARY; "
2411                            + mode + " was not the current primary action mode! Expected "
2412                            + mPrimaryActionMode);
2413                }
2414                if (!isFloating && mode.getType() == ActionMode.TYPE_FLOATING) {
2415                    Log.e(mLogTag, "Destroying unexpected ActionMode instance of TYPE_FLOATING; "
2416                            + mode + " was not the current floating action mode! Expected "
2417                            + mFloatingActionMode);
2418                }
2419            } else {
2420                isPrimary = mode.getType() == ActionMode.TYPE_PRIMARY;
2421                isFloating = mode.getType() == ActionMode.TYPE_FLOATING;
2422            }
2423            if (isPrimary) {
2424                if (mPrimaryActionModePopup != null) {
2425                    removeCallbacks(mShowPrimaryActionModePopup);
2426                }
2427                if (mPrimaryActionModeView != null) {
2428                    endOnGoingFadeAnimation();
2429                    // Store action mode view reference, so we can access it safely when animation
2430                    // ends. mPrimaryActionModePopup is set together with mPrimaryActionModeView,
2431                    // so no need to store reference to it in separate variable.
2432                    final ActionBarContextView lastActionModeView = mPrimaryActionModeView;
2433                    mFadeAnim = ObjectAnimator.ofFloat(mPrimaryActionModeView, View.ALPHA,
2434                            1f, 0f);
2435                    mFadeAnim.addListener(new Animator.AnimatorListener() {
2436
2437                                @Override
2438                                public void onAnimationStart(Animator animation) {
2439
2440                                }
2441
2442                                @Override
2443                                public void onAnimationEnd(Animator animation) {
2444                                    // If mPrimaryActionModeView has changed - it means that we've
2445                                    // cleared the content while preserving decor view. We don't
2446                                    // want to change the state of new instances accidentally here.
2447                                    if (lastActionModeView == mPrimaryActionModeView) {
2448                                        lastActionModeView.setVisibility(GONE);
2449                                        if (mPrimaryActionModePopup != null) {
2450                                            mPrimaryActionModePopup.dismiss();
2451                                        }
2452                                        lastActionModeView.killMode();
2453                                        mFadeAnim = null;
2454                                    }
2455                                }
2456
2457                                @Override
2458                                public void onAnimationCancel(Animator animation) {
2459
2460                                }
2461
2462                                @Override
2463                                public void onAnimationRepeat(Animator animation) {
2464
2465                                }
2466                            });
2467                    mFadeAnim.start();
2468                }
2469
2470                mPrimaryActionMode = null;
2471            } else if (isFloating) {
2472                cleanupFloatingActionModeViews();
2473                mFloatingActionMode = null;
2474            }
2475            if (mWindow.getCallback() != null && !mWindow.isDestroyed()) {
2476                try {
2477                    mWindow.getCallback().onActionModeFinished(mode);
2478                } catch (AbstractMethodError ame) {
2479                    // Older apps might not implement this callback method.
2480                }
2481            }
2482            requestFitSystemWindows();
2483        }
2484
2485        @Override
2486        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
2487            if (mWrapped instanceof ActionMode.Callback2) {
2488                ((ActionMode.Callback2) mWrapped).onGetContentRect(mode, view, outRect);
2489            } else {
2490                super.onGetContentRect(mode, view, outRect);
2491            }
2492        }
2493    }
2494}
2495