DecorView.java revision 786ea783ea109c67a50871b9a35dfb3c485b9585
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.app.ActivityManager;
45import android.content.Context;
46import android.content.res.Configuration;
47import android.content.res.Resources;
48import android.graphics.Canvas;
49import android.graphics.Color;
50import android.graphics.LinearGradient;
51import android.graphics.Paint;
52import android.graphics.PixelFormat;
53import android.graphics.Rect;
54import android.graphics.Region;
55import android.graphics.Shader;
56import android.graphics.drawable.ColorDrawable;
57import android.graphics.drawable.Drawable;
58import android.os.RemoteException;
59import android.util.DisplayMetrics;
60import android.util.Log;
61import android.util.TypedValue;
62import android.view.ActionMode;
63import android.view.ContextThemeWrapper;
64import android.view.DisplayListCanvas;
65import android.view.Gravity;
66import android.view.InputQueue;
67import android.view.KeyEvent;
68import android.view.KeyboardShortcutGroup;
69import android.view.LayoutInflater;
70import android.view.Menu;
71import android.view.MenuItem;
72import android.view.MotionEvent;
73import android.view.ThreadedRenderer;
74import android.view.View;
75import android.view.ViewGroup;
76import android.view.ViewStub;
77import android.view.ViewTreeObserver;
78import android.view.Window;
79import android.view.WindowCallbacks;
80import android.view.WindowInsets;
81import android.view.WindowManager;
82import android.view.accessibility.AccessibilityEvent;
83import android.view.accessibility.AccessibilityManager;
84import android.view.animation.AnimationUtils;
85import android.view.animation.Interpolator;
86import android.widget.FrameLayout;
87import android.widget.PopupWindow;
88
89import static android.app.WindowConfiguration.PINNED_WINDOWING_MODE_ELEVATION_IN_DIP;
90import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
91import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
92import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
93import static android.os.Build.VERSION_CODES.M;
94import static android.os.Build.VERSION_CODES.N;
95import static android.view.View.MeasureSpec.AT_MOST;
96import static android.view.View.MeasureSpec.EXACTLY;
97import static android.view.View.MeasureSpec.getMode;
98import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
99import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
100import static android.view.Window.DECOR_CAPTION_SHADE_DARK;
101import static android.view.Window.DECOR_CAPTION_SHADE_LIGHT;
102import static android.view.WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
103import static android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN;
104import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR;
105import static android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
106import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
107import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
108import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
109import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
110import static android.view.WindowManager.LayoutParams.TYPE_DRAWN_APPLICATION;
111import static com.android.internal.policy.PhoneWindow.FEATURE_OPTIONS_PANEL;
112
113/** @hide */
114public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {
115    private static final String TAG = "DecorView";
116
117    private static final boolean DEBUG_MEASURE = false;
118
119    private static final boolean SWEEP_OPEN_MENU = false;
120
121    // The height of a window which has focus in DIP.
122    private final static int DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP = 20;
123    // The height of a window which has not in DIP.
124    private final static int DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP = 5;
125
126    public static final ColorViewAttributes STATUS_BAR_COLOR_VIEW_ATTRIBUTES =
127            new ColorViewAttributes(SYSTEM_UI_FLAG_FULLSCREEN, FLAG_TRANSLUCENT_STATUS,
128                    Gravity.TOP, Gravity.LEFT, Gravity.RIGHT,
129                    Window.STATUS_BAR_BACKGROUND_TRANSITION_NAME,
130                    com.android.internal.R.id.statusBarBackground,
131                    FLAG_FULLSCREEN);
132
133    public static final ColorViewAttributes NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES =
134            new ColorViewAttributes(
135                    SYSTEM_UI_FLAG_HIDE_NAVIGATION, FLAG_TRANSLUCENT_NAVIGATION,
136                    Gravity.BOTTOM, Gravity.RIGHT, Gravity.LEFT,
137                    Window.NAVIGATION_BAR_BACKGROUND_TRANSITION_NAME,
138                    com.android.internal.R.id.navigationBarBackground,
139                    0 /* hideWindowFlag */);
140
141    // This is used to workaround an issue where the PiP shadow can be transparent if the window
142    // background is transparent
143    private static final ViewOutlineProvider PIP_OUTLINE_PROVIDER = new ViewOutlineProvider() {
144        @Override
145        public void getOutline(View view, Outline outline) {
146            outline.setRect(0, 0, view.getWidth(), view.getHeight());
147            outline.setAlpha(1f);
148        }
149    };
150
151    // Cludge to address b/22668382: Set the shadow size to the maximum so that the layer
152    // size calculation takes the shadow size into account. We set the elevation currently
153    // to max until the first layout command has been executed.
154    private boolean mAllowUpdateElevation = false;
155
156    private boolean mElevationAdjustedForStack = false;
157
158    // Keeps track of the picture-in-picture mode for the view shadow
159    private boolean mIsInPictureInPictureMode;
160
161    // Stores the previous outline provider prior to applying PIP_OUTLINE_PROVIDER
162    private ViewOutlineProvider mLastOutlineProvider;
163
164    int mDefaultOpacity = PixelFormat.OPAQUE;
165
166    /** The feature ID of the panel, or -1 if this is the application's DecorView */
167    private final int mFeatureId;
168
169    private final Rect mDrawingBounds = new Rect();
170
171    private final Rect mBackgroundPadding = new Rect();
172
173    private final Rect mFramePadding = new Rect();
174
175    private final Rect mFrameOffsets = new Rect();
176
177    private boolean mHasCaption = false;
178
179    private boolean mChanging;
180
181    private Drawable mMenuBackground;
182    private boolean mWatchingForMenu;
183    private int mDownY;
184
185    ActionMode mPrimaryActionMode;
186    private ActionMode mFloatingActionMode;
187    private ActionBarContextView mPrimaryActionModeView;
188    private PopupWindow mPrimaryActionModePopup;
189    private Runnable mShowPrimaryActionModePopup;
190    private ViewTreeObserver.OnPreDrawListener mFloatingToolbarPreDrawListener;
191    private View mFloatingActionModeOriginatingView;
192    private FloatingToolbar mFloatingToolbar;
193    private ObjectAnimator mFadeAnim;
194
195    // View added at runtime to draw under the status bar area
196    private View mStatusGuard;
197
198    private final ColorViewState mStatusColorViewState =
199            new ColorViewState(STATUS_BAR_COLOR_VIEW_ATTRIBUTES);
200    private final ColorViewState mNavigationColorViewState =
201            new ColorViewState(NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES);
202
203    private final Interpolator mShowInterpolator;
204    private final Interpolator mHideInterpolator;
205    private final int mBarEnterExitDuration;
206    final boolean mForceWindowDrawsStatusBarBackground;
207    private final int mSemiTransparentStatusBarColor;
208
209    private final BackgroundFallback mBackgroundFallback = new BackgroundFallback();
210
211    private int mLastTopInset = 0;
212    private int mLastBottomInset = 0;
213    private int mLastRightInset = 0;
214    private int mLastLeftInset = 0;
215    private boolean mLastHasTopStableInset = false;
216    private boolean mLastHasBottomStableInset = false;
217    private boolean mLastHasRightStableInset = false;
218    private boolean mLastHasLeftStableInset = false;
219    private int mLastWindowFlags = 0;
220    private boolean mLastShouldAlwaysConsumeNavBar = false;
221
222    private int mRootScrollY = 0;
223
224    private PhoneWindow mWindow;
225
226    ViewGroup mContentRoot;
227
228    private Rect mTempRect;
229    private Rect mOutsets = new Rect();
230
231    // This is the caption view for the window, containing the caption and window control
232    // buttons. The visibility of this decor depends on the workspace and the window type.
233    // If the window type does not require such a view, this member might be null.
234    DecorCaptionView mDecorCaptionView;
235
236    private boolean mWindowResizeCallbacksAdded = false;
237    private Drawable.Callback mLastBackgroundDrawableCb = null;
238    private BackdropFrameRenderer mBackdropFrameRenderer = null;
239    private Drawable mResizingBackgroundDrawable;
240    private Drawable mCaptionBackgroundDrawable;
241    private Drawable mUserCaptionBackgroundDrawable;
242
243    private float mAvailableWidth;
244
245    String mLogTag = TAG;
246    private final Rect mFloatingInsets = new Rect();
247    private boolean mApplyFloatingVerticalInsets = false;
248    private boolean mApplyFloatingHorizontalInsets = false;
249
250    private int mResizeMode = RESIZE_MODE_INVALID;
251    private final int mResizeShadowSize;
252    private final Paint mVerticalResizeShadowPaint = new Paint();
253    private final Paint mHorizontalResizeShadowPaint = new Paint();
254
255    DecorView(Context context, int featureId, PhoneWindow window,
256            WindowManager.LayoutParams params) {
257        super(context);
258        mFeatureId = featureId;
259
260        mShowInterpolator = AnimationUtils.loadInterpolator(context,
261                android.R.interpolator.linear_out_slow_in);
262        mHideInterpolator = AnimationUtils.loadInterpolator(context,
263                android.R.interpolator.fast_out_linear_in);
264
265        mBarEnterExitDuration = context.getResources().getInteger(
266                R.integer.dock_enter_exit_duration);
267        mForceWindowDrawsStatusBarBackground = context.getResources().getBoolean(
268                R.bool.config_forceWindowDrawsStatusBarBackground)
269                && context.getApplicationInfo().targetSdkVersion >= N;
270        mSemiTransparentStatusBarColor = context.getResources().getColor(
271                R.color.system_bar_background_semi_transparent, null /* theme */);
272
273        updateAvailableWidth();
274
275        setWindow(window);
276
277        updateLogTag(params);
278
279        mResizeShadowSize = context.getResources().getDimensionPixelSize(
280                R.dimen.resize_shadow_size);
281        initResizingPaints();
282    }
283
284    void setBackgroundFallback(int resId) {
285        mBackgroundFallback.setDrawable(resId != 0 ? getContext().getDrawable(resId) : null);
286        setWillNotDraw(getBackground() == null && !mBackgroundFallback.hasFallback());
287    }
288
289    @Override
290    public boolean gatherTransparentRegion(Region region) {
291        boolean statusOpaque = gatherTransparentRegion(mStatusColorViewState, region);
292        boolean navOpaque = gatherTransparentRegion(mNavigationColorViewState, region);
293        boolean decorOpaque = super.gatherTransparentRegion(region);
294
295        // combine bools after computation, so each method above always executes
296        return statusOpaque || navOpaque || decorOpaque;
297    }
298
299    boolean gatherTransparentRegion(ColorViewState colorViewState, Region region) {
300        if (colorViewState.view != null && colorViewState.visible && isResizing()) {
301            // If a visible ColorViewState is in a resizing host DecorView, forcibly register its
302            // opaque area, since it's drawn by a different root RenderNode. It would otherwise be
303            // rejected by ViewGroup#gatherTransparentRegion() for the view not being VISIBLE.
304            return colorViewState.view.gatherTransparentRegion(region);
305        }
306        return false; // no opaque area added
307    }
308
309    @Override
310    public void onDraw(Canvas c) {
311        super.onDraw(c);
312
313        mBackgroundFallback.draw(this, mContentRoot, c, mWindow.mContentParent,
314                mStatusColorViewState.view, mNavigationColorViewState.view);
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    protected void onConfigurationChanged(Configuration newConfig) {
1846        super.onConfigurationChanged(newConfig);
1847
1848        final boolean displayWindowDecor =
1849                newConfig.windowConfiguration.hasWindowDecorCaption();
1850        if (mDecorCaptionView == null && displayWindowDecor) {
1851            // Configuration now requires a caption.
1852            final LayoutInflater inflater = mWindow.getLayoutInflater();
1853            mDecorCaptionView = createDecorCaptionView(inflater);
1854            if (mDecorCaptionView != null) {
1855                if (mDecorCaptionView.getParent() == null) {
1856                    addView(mDecorCaptionView, 0,
1857                            new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1858                }
1859                removeView(mContentRoot);
1860                mDecorCaptionView.addView(mContentRoot,
1861                        new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
1862            }
1863        } else if (mDecorCaptionView != null) {
1864            // We might have to change the kind of surface before we do anything else.
1865            mDecorCaptionView.onConfigurationChanged(displayWindowDecor);
1866            enableCaption(displayWindowDecor);
1867        }
1868
1869        updateAvailableWidth();
1870        initializeElevation();
1871    }
1872
1873    void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
1874        if (mBackdropFrameRenderer != null) {
1875            loadBackgroundDrawablesIfNeeded();
1876            mBackdropFrameRenderer.onResourcesLoaded(
1877                    this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
1878                    mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
1879                    getCurrentColor(mNavigationColorViewState));
1880        }
1881
1882        mDecorCaptionView = createDecorCaptionView(inflater);
1883        final View root = inflater.inflate(layoutResource, null);
1884        if (mDecorCaptionView != null) {
1885            if (mDecorCaptionView.getParent() == null) {
1886                addView(mDecorCaptionView,
1887                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1888            }
1889            mDecorCaptionView.addView(root,
1890                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
1891        } else {
1892
1893            // Put it below the color views.
1894            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
1895        }
1896        mContentRoot = (ViewGroup) root;
1897        initializeElevation();
1898    }
1899
1900    private void loadBackgroundDrawablesIfNeeded() {
1901        if (mResizingBackgroundDrawable == null) {
1902            mResizingBackgroundDrawable = getResizingBackgroundDrawable(getContext(),
1903                    mWindow.mBackgroundResource, mWindow.mBackgroundFallbackResource,
1904                    mWindow.isTranslucent() || mWindow.isShowingWallpaper());
1905            if (mResizingBackgroundDrawable == null) {
1906                // We shouldn't really get here as the background fallback should be always
1907                // available since it is defaulted by the system.
1908                Log.w(mLogTag, "Failed to find background drawable for PhoneWindow=" + mWindow);
1909            }
1910        }
1911        if (mCaptionBackgroundDrawable == null) {
1912            mCaptionBackgroundDrawable = getContext().getDrawable(
1913                    R.drawable.decor_caption_title_focused);
1914        }
1915        if (mResizingBackgroundDrawable != null) {
1916            mLastBackgroundDrawableCb = mResizingBackgroundDrawable.getCallback();
1917            mResizingBackgroundDrawable.setCallback(null);
1918        }
1919    }
1920
1921    // Free floating overlapping windows require a caption.
1922    private DecorCaptionView createDecorCaptionView(LayoutInflater inflater) {
1923        DecorCaptionView decorCaptionView = null;
1924        for (int i = getChildCount() - 1; i >= 0 && decorCaptionView == null; i--) {
1925            View view = getChildAt(i);
1926            if (view instanceof DecorCaptionView) {
1927                // The decor was most likely saved from a relaunch - so reuse it.
1928                decorCaptionView = (DecorCaptionView) view;
1929                removeViewAt(i);
1930            }
1931        }
1932        final WindowManager.LayoutParams attrs = mWindow.getAttributes();
1933        final boolean isApplication = attrs.type == TYPE_BASE_APPLICATION ||
1934                attrs.type == TYPE_APPLICATION || attrs.type == TYPE_DRAWN_APPLICATION;
1935        final WindowConfiguration winConfig = getResources().getConfiguration().windowConfiguration;
1936        // Only a non floating application window on one of the allowed workspaces can get a caption
1937        if (!mWindow.isFloating() && isApplication && winConfig.hasWindowDecorCaption()) {
1938            // Dependent on the brightness of the used title we either use the
1939            // dark or the light button frame.
1940            if (decorCaptionView == null) {
1941                decorCaptionView = inflateDecorCaptionView(inflater);
1942            }
1943            decorCaptionView.setPhoneWindow(mWindow, true /*showDecor*/);
1944        } else {
1945            decorCaptionView = null;
1946        }
1947
1948        // Tell the decor if it has a visible caption.
1949        enableCaption(decorCaptionView != null);
1950        return decorCaptionView;
1951    }
1952
1953    private DecorCaptionView inflateDecorCaptionView(LayoutInflater inflater) {
1954        final Context context = getContext();
1955        // We make a copy of the inflater, so it has the right context associated with it.
1956        inflater = inflater.from(context);
1957        final DecorCaptionView view = (DecorCaptionView) inflater.inflate(R.layout.decor_caption,
1958                null);
1959        setDecorCaptionShade(context, view);
1960        return view;
1961    }
1962
1963    private void setDecorCaptionShade(Context context, DecorCaptionView view) {
1964        final int shade = mWindow.getDecorCaptionShade();
1965        switch (shade) {
1966            case DECOR_CAPTION_SHADE_LIGHT:
1967                setLightDecorCaptionShade(view);
1968                break;
1969            case DECOR_CAPTION_SHADE_DARK:
1970                setDarkDecorCaptionShade(view);
1971                break;
1972            default: {
1973                TypedValue value = new TypedValue();
1974                context.getTheme().resolveAttribute(R.attr.colorPrimary, value, true);
1975                // We invert the shade depending on brightness of the theme. Dark shade for light
1976                // theme and vice versa. Thanks to this the buttons should be visible on the
1977                // background.
1978                if (Color.luminance(value.data) < 0.5) {
1979                    setLightDecorCaptionShade(view);
1980                } else {
1981                    setDarkDecorCaptionShade(view);
1982                }
1983                break;
1984            }
1985        }
1986    }
1987
1988    void updateDecorCaptionShade() {
1989        if (mDecorCaptionView != null) {
1990            setDecorCaptionShade(getContext(), mDecorCaptionView);
1991        }
1992    }
1993
1994    private void setLightDecorCaptionShade(DecorCaptionView view) {
1995        view.findViewById(R.id.maximize_window).setBackgroundResource(
1996                R.drawable.decor_maximize_button_light);
1997        view.findViewById(R.id.close_window).setBackgroundResource(
1998                R.drawable.decor_close_button_light);
1999    }
2000
2001    private void setDarkDecorCaptionShade(DecorCaptionView view) {
2002        view.findViewById(R.id.maximize_window).setBackgroundResource(
2003                R.drawable.decor_maximize_button_dark);
2004        view.findViewById(R.id.close_window).setBackgroundResource(
2005                R.drawable.decor_close_button_dark);
2006    }
2007
2008    /**
2009     * Returns the color used to fill areas the app has not rendered content to yet when the
2010     * user is resizing the window of an activity in multi-window mode.
2011     */
2012    public static Drawable getResizingBackgroundDrawable(Context context, int backgroundRes,
2013            int backgroundFallbackRes, boolean windowTranslucent) {
2014        if (backgroundRes != 0) {
2015            final Drawable drawable = context.getDrawable(backgroundRes);
2016            if (drawable != null) {
2017                return enforceNonTranslucentBackground(drawable, windowTranslucent);
2018            }
2019        }
2020
2021        if (backgroundFallbackRes != 0) {
2022            final Drawable fallbackDrawable = context.getDrawable(backgroundFallbackRes);
2023            if (fallbackDrawable != null) {
2024                return enforceNonTranslucentBackground(fallbackDrawable, windowTranslucent);
2025            }
2026        }
2027        return new ColorDrawable(Color.BLACK);
2028    }
2029
2030    /**
2031     * Enforces a drawable to be non-translucent to act as a background if needed, i.e. if the
2032     * window is not translucent.
2033     */
2034    private static Drawable enforceNonTranslucentBackground(Drawable drawable,
2035            boolean windowTranslucent) {
2036        if (!windowTranslucent && drawable instanceof ColorDrawable) {
2037            ColorDrawable colorDrawable = (ColorDrawable) drawable;
2038            int color = colorDrawable.getColor();
2039            if (Color.alpha(color) != 255) {
2040                ColorDrawable copy = (ColorDrawable) colorDrawable.getConstantState().newDrawable()
2041                        .mutate();
2042                copy.setColor(
2043                        Color.argb(255, Color.red(color), Color.green(color), Color.blue(color)));
2044                return copy;
2045            }
2046        }
2047        return drawable;
2048    }
2049
2050    void clearContentView() {
2051        if (mDecorCaptionView != null) {
2052            mDecorCaptionView.removeContentView();
2053        } else {
2054            // This window doesn't have caption, so we need to remove everything except our views
2055            // we might have added.
2056            for (int i = getChildCount() - 1; i >= 0; i--) {
2057                View v = getChildAt(i);
2058                if (v != mStatusColorViewState.view && v != mNavigationColorViewState.view
2059                        && v != mStatusGuard) {
2060                    removeViewAt(i);
2061                }
2062            }
2063        }
2064    }
2065
2066    @Override
2067    public void onWindowSizeIsChanging(Rect newBounds, boolean fullscreen, Rect systemInsets,
2068            Rect stableInsets) {
2069        if (mBackdropFrameRenderer != null) {
2070            mBackdropFrameRenderer.setTargetRect(newBounds, fullscreen, systemInsets, stableInsets);
2071        }
2072    }
2073
2074    @Override
2075    public void onWindowDragResizeStart(Rect initialBounds, boolean fullscreen, Rect systemInsets,
2076            Rect stableInsets, int resizeMode) {
2077        if (mWindow.isDestroyed()) {
2078            // If the owner's window is gone, we should not be able to come here anymore.
2079            releaseThreadedRenderer();
2080            return;
2081        }
2082        if (mBackdropFrameRenderer != null) {
2083            return;
2084        }
2085        final ThreadedRenderer renderer = getThreadedRenderer();
2086        if (renderer != null) {
2087            loadBackgroundDrawablesIfNeeded();
2088            mBackdropFrameRenderer = new BackdropFrameRenderer(this, renderer,
2089                    initialBounds, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
2090                    mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
2091                    getCurrentColor(mNavigationColorViewState), fullscreen, systemInsets,
2092                    stableInsets, resizeMode);
2093
2094            // Get rid of the shadow while we are resizing. Shadow drawing takes considerable time.
2095            // If we want to get the shadow shown while resizing, we would need to elevate a new
2096            // element which owns the caption and has the elevation.
2097            updateElevation();
2098
2099            updateColorViews(null /* insets */, false);
2100        }
2101        mResizeMode = resizeMode;
2102        getViewRootImpl().requestInvalidateRootRenderNode();
2103    }
2104
2105    @Override
2106    public void onWindowDragResizeEnd() {
2107        releaseThreadedRenderer();
2108        updateColorViews(null /* insets */, false);
2109        mResizeMode = RESIZE_MODE_INVALID;
2110        getViewRootImpl().requestInvalidateRootRenderNode();
2111    }
2112
2113    @Override
2114    public boolean onContentDrawn(int offsetX, int offsetY, int sizeX, int sizeY) {
2115        if (mBackdropFrameRenderer == null) {
2116            return false;
2117        }
2118        return mBackdropFrameRenderer.onContentDrawn(offsetX, offsetY, sizeX, sizeY);
2119    }
2120
2121    @Override
2122    public void onRequestDraw(boolean reportNextDraw) {
2123        if (mBackdropFrameRenderer != null) {
2124            mBackdropFrameRenderer.onRequestDraw(reportNextDraw);
2125        } else if (reportNextDraw) {
2126            // If render thread is gone, just report immediately.
2127            if (isAttachedToWindow()) {
2128                getViewRootImpl().reportDrawFinish();
2129            }
2130        }
2131    }
2132
2133    @Override
2134    public void onPostDraw(DisplayListCanvas canvas) {
2135        drawResizingShadowIfNeeded(canvas);
2136    }
2137
2138    private void initResizingPaints() {
2139        final int startColor = mContext.getResources().getColor(
2140                R.color.resize_shadow_start_color, null);
2141        final int endColor = mContext.getResources().getColor(
2142                R.color.resize_shadow_end_color, null);
2143        final int middleColor = (startColor + endColor) / 2;
2144        mHorizontalResizeShadowPaint.setShader(new LinearGradient(
2145                0, 0, 0, mResizeShadowSize, new int[] { startColor, middleColor, endColor },
2146                new float[] { 0f, 0.3f, 1f }, Shader.TileMode.CLAMP));
2147        mVerticalResizeShadowPaint.setShader(new LinearGradient(
2148                0, 0, mResizeShadowSize, 0, new int[] { startColor, middleColor, endColor },
2149                new float[] { 0f, 0.3f, 1f }, Shader.TileMode.CLAMP));
2150    }
2151
2152    private void drawResizingShadowIfNeeded(DisplayListCanvas canvas) {
2153        if (mResizeMode != RESIZE_MODE_DOCKED_DIVIDER || mWindow.mIsFloating
2154                || mWindow.isTranslucent()
2155                || mWindow.isShowingWallpaper()) {
2156            return;
2157        }
2158        canvas.save();
2159        canvas.translate(0, getHeight() - mFrameOffsets.bottom);
2160        canvas.drawRect(0, 0, getWidth(), mResizeShadowSize, mHorizontalResizeShadowPaint);
2161        canvas.restore();
2162        canvas.save();
2163        canvas.translate(getWidth() - mFrameOffsets.right, 0);
2164        canvas.drawRect(0, 0, mResizeShadowSize, getHeight(), mVerticalResizeShadowPaint);
2165        canvas.restore();
2166    }
2167
2168    /** Release the renderer thread which is usually done when the user stops resizing. */
2169    private void releaseThreadedRenderer() {
2170        if (mResizingBackgroundDrawable != null && mLastBackgroundDrawableCb != null) {
2171            mResizingBackgroundDrawable.setCallback(mLastBackgroundDrawableCb);
2172            mLastBackgroundDrawableCb = null;
2173        }
2174
2175        if (mBackdropFrameRenderer != null) {
2176            mBackdropFrameRenderer.releaseRenderer();
2177            mBackdropFrameRenderer = null;
2178            // Bring the shadow back.
2179            updateElevation();
2180        }
2181    }
2182
2183    private boolean isResizing() {
2184        return mBackdropFrameRenderer != null;
2185    }
2186
2187    /**
2188     * The elevation gets set for the first time and the framework needs to be informed that
2189     * the surface layer gets created with the shadow size in mind.
2190     */
2191    private void initializeElevation() {
2192        // TODO(skuhne): Call setMaxElevation here accordingly after b/22668382 got fixed.
2193        mAllowUpdateElevation = false;
2194        updateElevation();
2195    }
2196
2197    private void updateElevation() {
2198        float elevation = 0;
2199        final boolean wasAdjustedForStack = mElevationAdjustedForStack;
2200        // Do not use a shadow when we are in resizing mode (mBackdropFrameRenderer not null)
2201        // since the shadow is bound to the content size and not the target size.
2202        final int windowingMode =
2203                getResources().getConfiguration().windowConfiguration.getWindowingMode();
2204        if ((windowingMode == WINDOWING_MODE_FREEFORM) && !isResizing()) {
2205            elevation = hasWindowFocus() ?
2206                    DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP : DECOR_SHADOW_UNFOCUSED_HEIGHT_IN_DIP;
2207            // Add a maximum shadow height value to the top level view.
2208            // Note that pinned stack doesn't have focus
2209            // so maximum shadow height adjustment isn't needed.
2210            // TODO(skuhne): Remove this if clause once b/22668382 got fixed.
2211            if (!mAllowUpdateElevation) {
2212                elevation = DECOR_SHADOW_FOCUSED_HEIGHT_IN_DIP;
2213            }
2214            // Convert the DP elevation into physical pixels.
2215            elevation = dipToPx(elevation);
2216            mElevationAdjustedForStack = true;
2217        } else if (windowingMode == WINDOWING_MODE_PINNED) {
2218            elevation = dipToPx(PINNED_WINDOWING_MODE_ELEVATION_IN_DIP);
2219            mElevationAdjustedForStack = true;
2220        } else {
2221            mElevationAdjustedForStack = false;
2222        }
2223
2224        // Don't change the elevation if we didn't previously adjust it for the stack it was in
2225        // or it didn't change.
2226        if ((wasAdjustedForStack || mElevationAdjustedForStack)
2227                && getElevation() != elevation) {
2228            mWindow.setElevation(elevation);
2229        }
2230    }
2231
2232    boolean isShowingCaption() {
2233        return mDecorCaptionView != null && mDecorCaptionView.isCaptionShowing();
2234    }
2235
2236    int getCaptionHeight() {
2237        return isShowingCaption() ? mDecorCaptionView.getCaptionHeight() : 0;
2238    }
2239
2240    /**
2241     * Converts a DIP measure into physical pixels.
2242     * @param dip The dip value.
2243     * @return Returns the number of pixels.
2244     */
2245    private float dipToPx(float dip) {
2246        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip,
2247                getResources().getDisplayMetrics());
2248    }
2249
2250    /**
2251     * Provide an override of the caption background drawable.
2252     */
2253    void setUserCaptionBackgroundDrawable(Drawable drawable) {
2254        mUserCaptionBackgroundDrawable = drawable;
2255        if (mBackdropFrameRenderer != null) {
2256            mBackdropFrameRenderer.setUserCaptionBackgroundDrawable(drawable);
2257        }
2258    }
2259
2260    private static String getTitleSuffix(WindowManager.LayoutParams params) {
2261        if (params == null) {
2262            return "";
2263        }
2264        final String[] split = params.getTitle().toString().split("\\.");
2265        if (split.length > 0) {
2266            return split[split.length - 1];
2267        } else {
2268            return "";
2269        }
2270    }
2271
2272    void updateLogTag(WindowManager.LayoutParams params) {
2273        mLogTag = TAG + "[" + getTitleSuffix(params) + "]";
2274    }
2275
2276    private void updateAvailableWidth() {
2277        Resources res = getResources();
2278        mAvailableWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
2279                res.getConfiguration().screenWidthDp, res.getDisplayMetrics());
2280    }
2281
2282    /**
2283     * @hide
2284     */
2285    @Override
2286    public void requestKeyboardShortcuts(List<KeyboardShortcutGroup> list, int deviceId) {
2287        final PanelFeatureState st = mWindow.getPanelState(FEATURE_OPTIONS_PANEL, false);
2288        final Menu menu = st != null ? st.menu : null;
2289        if (!mWindow.isDestroyed() && mWindow.getCallback() != null) {
2290            mWindow.getCallback().onProvideKeyboardShortcuts(list, menu, deviceId);
2291        }
2292    }
2293
2294    @Override
2295    public void dispatchPointerCaptureChanged(boolean hasCapture) {
2296        super.dispatchPointerCaptureChanged(hasCapture);
2297        if (!mWindow.isDestroyed() && mWindow.getCallback() != null) {
2298            mWindow.getCallback().onPointerCaptureChanged(hasCapture);
2299        }
2300    }
2301
2302    @Override
2303    public int getAccessibilityViewId() {
2304        return AccessibilityNodeInfo.ROOT_ITEM_ID;
2305    }
2306
2307    @Override
2308    public String toString() {
2309        return "DecorView@" + Integer.toHexString(this.hashCode()) + "["
2310                + getTitleSuffix(mWindow.getAttributes()) + "]";
2311    }
2312
2313    private static class ColorViewState {
2314        View view = null;
2315        int targetVisibility = View.INVISIBLE;
2316        boolean present = false;
2317        boolean visible;
2318        int color;
2319
2320        final ColorViewAttributes attributes;
2321
2322        ColorViewState(ColorViewAttributes attributes) {
2323            this.attributes = attributes;
2324        }
2325    }
2326
2327    public static class ColorViewAttributes {
2328
2329        final int id;
2330        final int systemUiHideFlag;
2331        final int translucentFlag;
2332        final int verticalGravity;
2333        final int horizontalGravity;
2334        final int seascapeGravity;
2335        final String transitionName;
2336        final int hideWindowFlag;
2337
2338        private ColorViewAttributes(int systemUiHideFlag, int translucentFlag, int verticalGravity,
2339                int horizontalGravity, int seascapeGravity, String transitionName, int id,
2340                int hideWindowFlag) {
2341            this.id = id;
2342            this.systemUiHideFlag = systemUiHideFlag;
2343            this.translucentFlag = translucentFlag;
2344            this.verticalGravity = verticalGravity;
2345            this.horizontalGravity = horizontalGravity;
2346            this.seascapeGravity = seascapeGravity;
2347            this.transitionName = transitionName;
2348            this.hideWindowFlag = hideWindowFlag;
2349        }
2350
2351        public boolean isPresent(int sysUiVis, int windowFlags, boolean force) {
2352            return (sysUiVis & systemUiHideFlag) == 0
2353                    && (windowFlags & hideWindowFlag) == 0
2354                    && ((windowFlags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0
2355                    || force);
2356        }
2357
2358        public boolean isVisible(boolean present, int color, int windowFlags, boolean force) {
2359            return present
2360                    && (color & Color.BLACK) != 0
2361                    && ((windowFlags & translucentFlag) == 0  || force);
2362        }
2363
2364        public boolean isVisible(int sysUiVis, int color, int windowFlags, boolean force) {
2365            final boolean present = isPresent(sysUiVis, windowFlags, force);
2366            return isVisible(present, color, windowFlags, force);
2367        }
2368    }
2369
2370    /**
2371     * Clears out internal references when the action mode is destroyed.
2372     */
2373    private class ActionModeCallback2Wrapper extends ActionMode.Callback2 {
2374        private final ActionMode.Callback mWrapped;
2375
2376        public ActionModeCallback2Wrapper(ActionMode.Callback wrapped) {
2377            mWrapped = wrapped;
2378        }
2379
2380        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
2381            return mWrapped.onCreateActionMode(mode, menu);
2382        }
2383
2384        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
2385            requestFitSystemWindows();
2386            return mWrapped.onPrepareActionMode(mode, menu);
2387        }
2388
2389        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
2390            return mWrapped.onActionItemClicked(mode, item);
2391        }
2392
2393        public void onDestroyActionMode(ActionMode mode) {
2394            mWrapped.onDestroyActionMode(mode);
2395            final boolean isMncApp = mContext.getApplicationInfo().targetSdkVersion
2396                    >= M;
2397            final boolean isPrimary;
2398            final boolean isFloating;
2399            if (isMncApp) {
2400                isPrimary = mode == mPrimaryActionMode;
2401                isFloating = mode == mFloatingActionMode;
2402                if (!isPrimary && mode.getType() == ActionMode.TYPE_PRIMARY) {
2403                    Log.e(mLogTag, "Destroying unexpected ActionMode instance of TYPE_PRIMARY; "
2404                            + mode + " was not the current primary action mode! Expected "
2405                            + mPrimaryActionMode);
2406                }
2407                if (!isFloating && mode.getType() == ActionMode.TYPE_FLOATING) {
2408                    Log.e(mLogTag, "Destroying unexpected ActionMode instance of TYPE_FLOATING; "
2409                            + mode + " was not the current floating action mode! Expected "
2410                            + mFloatingActionMode);
2411                }
2412            } else {
2413                isPrimary = mode.getType() == ActionMode.TYPE_PRIMARY;
2414                isFloating = mode.getType() == ActionMode.TYPE_FLOATING;
2415            }
2416            if (isPrimary) {
2417                if (mPrimaryActionModePopup != null) {
2418                    removeCallbacks(mShowPrimaryActionModePopup);
2419                }
2420                if (mPrimaryActionModeView != null) {
2421                    endOnGoingFadeAnimation();
2422                    // Store action mode view reference, so we can access it safely when animation
2423                    // ends. mPrimaryActionModePopup is set together with mPrimaryActionModeView,
2424                    // so no need to store reference to it in separate variable.
2425                    final ActionBarContextView lastActionModeView = mPrimaryActionModeView;
2426                    mFadeAnim = ObjectAnimator.ofFloat(mPrimaryActionModeView, View.ALPHA,
2427                            1f, 0f);
2428                    mFadeAnim.addListener(new Animator.AnimatorListener() {
2429
2430                                @Override
2431                                public void onAnimationStart(Animator animation) {
2432
2433                                }
2434
2435                                @Override
2436                                public void onAnimationEnd(Animator animation) {
2437                                    // If mPrimaryActionModeView has changed - it means that we've
2438                                    // cleared the content while preserving decor view. We don't
2439                                    // want to change the state of new instances accidentally here.
2440                                    if (lastActionModeView == mPrimaryActionModeView) {
2441                                        lastActionModeView.setVisibility(GONE);
2442                                        if (mPrimaryActionModePopup != null) {
2443                                            mPrimaryActionModePopup.dismiss();
2444                                        }
2445                                        lastActionModeView.killMode();
2446                                        mFadeAnim = null;
2447                                    }
2448                                }
2449
2450                                @Override
2451                                public void onAnimationCancel(Animator animation) {
2452
2453                                }
2454
2455                                @Override
2456                                public void onAnimationRepeat(Animator animation) {
2457
2458                                }
2459                            });
2460                    mFadeAnim.start();
2461                }
2462
2463                mPrimaryActionMode = null;
2464            } else if (isFloating) {
2465                cleanupFloatingActionModeViews();
2466                mFloatingActionMode = null;
2467            }
2468            if (mWindow.getCallback() != null && !mWindow.isDestroyed()) {
2469                try {
2470                    mWindow.getCallback().onActionModeFinished(mode);
2471                } catch (AbstractMethodError ame) {
2472                    // Older apps might not implement this callback method.
2473                }
2474            }
2475            requestFitSystemWindows();
2476        }
2477
2478        @Override
2479        public void onGetContentRect(ActionMode mode, View view, Rect outRect) {
2480            if (mWrapped instanceof ActionMode.Callback2) {
2481                ((ActionMode.Callback2) mWrapped).onGetContentRect(mode, view, outRect);
2482            } else {
2483                super.onGetContentRect(mode, view, outRect);
2484            }
2485        }
2486    }
2487}
2488