WindowState.java revision dcdca58cd5eb60a32de583eda5a334eb17f38034
1/*
2 * Copyright (C) 2011 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.server.wm;
18
19import android.app.ActivityManager;
20import android.app.AppOpsManager;
21import android.content.Context;
22import android.content.res.Configuration;
23import android.graphics.Matrix;
24import android.graphics.PixelFormat;
25import android.graphics.Point;
26import android.graphics.Rect;
27import android.graphics.Region;
28import android.os.IBinder;
29import android.os.PowerManager;
30import android.os.RemoteCallbackList;
31import android.os.RemoteException;
32import android.os.SystemClock;
33import android.os.Trace;
34import android.os.UserHandle;
35import android.os.WorkSource;
36import android.util.DisplayMetrics;
37import android.util.Slog;
38import android.util.TimeUtils;
39import android.view.Display;
40import android.view.DisplayInfo;
41import android.view.Gravity;
42import android.view.IApplicationToken;
43import android.view.IWindow;
44import android.view.IWindowFocusObserver;
45import android.view.IWindowId;
46import android.view.InputChannel;
47import android.view.InputEvent;
48import android.view.InputEventReceiver;
49import android.view.View;
50import android.view.ViewTreeObserver;
51import android.view.WindowManager;
52import android.view.WindowManagerPolicy;
53
54import com.android.server.input.InputWindowHandle;
55
56import java.io.PrintWriter;
57import java.util.ArrayList;
58
59import static android.app.ActivityManager.StackId;
60import static android.app.ActivityManager.StackId.DOCKED_STACK_ID;
61import static android.app.ActivityManager.StackId.INVALID_STACK_ID;
62import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER;
63import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT;
64import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
65import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION;
66import static android.view.ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE;
67import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
68import static android.view.WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
69import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND;
70import static android.view.WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
71import static android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
72import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
73import static android.view.WindowManager.LayoutParams.FLAG_SCALED;
74import static android.view.WindowManager.LayoutParams.FLAG_SECURE;
75import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
76import static android.view.WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
77import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
78import static android.view.WindowManager.LayoutParams.MATCH_PARENT;
79import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
80import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
81import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME;
82import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_WILL_NOT_REPLACE_ON_RELAUNCH;
83import static android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE;
84import static android.view.WindowManager.LayoutParams.SOFT_INPUT_MASK_ADJUST;
85import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION;
86import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
87import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
88import static android.view.WindowManager.LayoutParams.TYPE_DOCK_DIVIDER;
89import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
90import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
91import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
92import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_DOCKED_DIVIDER;
93import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_FREEFORM;
94import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
95import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
96import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
97import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_CONFIGURATION;
98import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_FOCUS_LIGHT;
99import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
100import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
101import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_POWER;
102import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_RESIZE;
103import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
104import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
105import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
106
107class WindowList extends ArrayList<WindowState> {
108    WindowList() {}
109    WindowList(WindowList windowList) {
110        super(windowList);
111    }
112}
113
114/**
115 * A window in the window manager.
116 */
117final class WindowState implements WindowManagerPolicy.WindowState {
118    static final String TAG = TAG_WITH_CLASS_NAME ? "WindowState" : TAG_WM;
119
120    // The minimal size of a window within the usable area of the freeform stack.
121    // TODO(multi-window): fix the min sizes when we have mininum width/height support,
122    //                     use hard-coded min sizes for now.
123    static final int MINIMUM_VISIBLE_WIDTH_IN_DP = 48;
124    static final int MINIMUM_VISIBLE_HEIGHT_IN_DP = 32;
125
126    // The thickness of a window resize handle outside the window bounds on the free form workspace
127    // to capture touch events in that area.
128    static final int RESIZE_HANDLE_WIDTH_IN_DP = 30;
129
130    static final boolean DEBUG_DISABLE_SAVING_SURFACES = false;
131
132    final WindowManagerService mService;
133    final WindowManagerPolicy mPolicy;
134    final Context mContext;
135    final Session mSession;
136    final IWindow mClient;
137    final int mAppOp;
138    // UserId and appId of the owner. Don't display windows of non-current user.
139    final int mOwnerUid;
140    final IWindowId mWindowId;
141    WindowToken mToken;
142    WindowToken mRootToken;
143    AppWindowToken mAppToken;
144    AppWindowToken mTargetAppToken;
145
146    // mAttrs.flags is tested in animation without being locked. If the bits tested are ever
147    // modified they will need to be locked.
148    final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
149    final DeathRecipient mDeathRecipient;
150    final WindowState mAttachedWindow;
151    final WindowList mChildWindows = new WindowList();
152    final int mBaseLayer;
153    final int mSubLayer;
154    final boolean mLayoutAttached;
155    final boolean mIsImWindow;
156    final boolean mIsWallpaper;
157    final boolean mIsFloatingLayer;
158    int mSeq;
159    boolean mEnforceSizeCompat;
160    int mViewVisibility;
161    int mSystemUiVisibility;
162    boolean mPolicyVisibility = true;
163    boolean mPolicyVisibilityAfterAnim = true;
164    boolean mAppOpVisibility = true;
165    boolean mAppFreezing;
166    boolean mAttachedHidden;    // is our parent window hidden?
167    boolean mWallpaperVisible;  // for wallpaper, what was last vis report?
168    boolean mDragResizing;
169    boolean mDragResizingChangeReported;
170    int mResizeMode;
171
172    RemoteCallbackList<IWindowFocusObserver> mFocusCallbacks;
173
174    /**
175     * The window size that was requested by the application.  These are in
176     * the application's coordinate space (without compatibility scale applied).
177     */
178    int mRequestedWidth;
179    int mRequestedHeight;
180    int mLastRequestedWidth;
181    int mLastRequestedHeight;
182
183    int mLayer;
184    boolean mHaveFrame;
185    boolean mObscured;
186    boolean mTurnOnScreen;
187
188    int mLayoutSeq = -1;
189
190    private Configuration mConfiguration = Configuration.EMPTY;
191    private Configuration mOverrideConfig = Configuration.EMPTY;
192    // Represents the changes from our override configuration applied
193    // to the global configuration. This is the only form of configuration
194    // which is suitable for delivery to the client.
195    private Configuration mMergedConfiguration = new Configuration();
196    // Sticky answer to isConfigChanged(), remains true until new Configuration is assigned.
197    // Used only on {@link #TYPE_KEYGUARD}.
198    private boolean mConfigHasChanged;
199
200    /**
201     * Actual position of the surface shown on-screen (may be modified by animation). These are
202     * in the screen's coordinate space (WITH the compatibility scale applied).
203     */
204    final Point mShownPosition = new Point();
205
206    /**
207     * Insets that determine the actually visible area.  These are in the application's
208     * coordinate space (without compatibility scale applied).
209     */
210    final Rect mVisibleInsets = new Rect();
211    final Rect mLastVisibleInsets = new Rect();
212    boolean mVisibleInsetsChanged;
213
214    /**
215     * Insets that are covered by system windows (such as the status bar) and
216     * transient docking windows (such as the IME).  These are in the application's
217     * coordinate space (without compatibility scale applied).
218     */
219    final Rect mContentInsets = new Rect();
220    final Rect mLastContentInsets = new Rect();
221    boolean mContentInsetsChanged;
222
223    /**
224     * Insets that determine the area covered by the display overscan region.  These are in the
225     * application's coordinate space (without compatibility scale applied).
226     */
227    final Rect mOverscanInsets = new Rect();
228    final Rect mLastOverscanInsets = new Rect();
229    boolean mOverscanInsetsChanged;
230
231    /**
232     * Insets that determine the area covered by the stable system windows.  These are in the
233     * application's coordinate space (without compatibility scale applied).
234     */
235    final Rect mStableInsets = new Rect();
236    final Rect mLastStableInsets = new Rect();
237    boolean mStableInsetsChanged;
238
239    /**
240     * Outsets determine the area outside of the surface where we want to pretend that it's possible
241     * to draw anyway.
242     */
243    final Rect mOutsets = new Rect();
244    final Rect mLastOutsets = new Rect();
245    boolean mOutsetsChanged = false;
246
247    /**
248     * Set to true if we are waiting for this window to receive its
249     * given internal insets before laying out other windows based on it.
250     */
251    boolean mGivenInsetsPending;
252
253    /**
254     * These are the content insets that were given during layout for
255     * this window, to be applied to windows behind it.
256     */
257    final Rect mGivenContentInsets = new Rect();
258
259    /**
260     * These are the visible insets that were given during layout for
261     * this window, to be applied to windows behind it.
262     */
263    final Rect mGivenVisibleInsets = new Rect();
264
265    /**
266     * This is the given touchable area relative to the window frame, or null if none.
267     */
268    final Region mGivenTouchableRegion = new Region();
269
270    /**
271     * Flag indicating whether the touchable region should be adjusted by
272     * the visible insets; if false the area outside the visible insets is
273     * NOT touchable, so we must use those to adjust the frame during hit
274     * tests.
275     */
276    int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
277
278    // Current transformation being applied.
279    float mGlobalScale=1;
280    float mInvGlobalScale=1;
281    float mHScale=1, mVScale=1;
282    float mLastHScale=1, mLastVScale=1;
283    final Matrix mTmpMatrix = new Matrix();
284
285    // "Real" frame that the application sees, in display coordinate space.
286    final Rect mFrame = new Rect();
287    final Rect mLastFrame = new Rect();
288    // Frame that is scaled to the application's coordinate space when in
289    // screen size compatibility mode.
290    final Rect mCompatFrame = new Rect();
291
292    final Rect mContainingFrame = new Rect();
293
294    final Rect mParentFrame = new Rect();
295
296    // The entire screen area of the {@link TaskStack} this window is in. Usually equal to the
297    // screen area of the device.
298    final Rect mDisplayFrame = new Rect();
299
300    // The region of the display frame that the display type supports displaying content on. This
301    // is mostly a special case for TV where some displays don’t have the entire display usable.
302    // {@link WindowManager.LayoutParams#FLAG_LAYOUT_IN_OVERSCAN} flag can be used to allow
303    // window display contents to extend into the overscan region.
304    final Rect mOverscanFrame = new Rect();
305
306    // The display frame minus the stable insets. This value is always constant regardless of if
307    // the status bar or navigation bar is visible.
308    final Rect mStableFrame = new Rect();
309
310    // The area not occupied by the status and navigation bars. So, if both status and navigation
311    // bars are visible, the decor frame is equal to the stable frame.
312    final Rect mDecorFrame = new Rect();
313
314    // Equal to the decor frame if the IME (e.g. keyboard) is not present. Equal to the decor frame
315    // minus the area occupied by the IME if the IME is present.
316    final Rect mContentFrame = new Rect();
317
318    // Legacy stuff. Generally equal to the content frame expect when the IME for older apps
319    // displays hint text.
320    final Rect mVisibleFrame = new Rect();
321
322    // Frame that includes dead area outside of the surface but where we want to pretend that it's
323    // possible to draw.
324    final Rect mOutsetFrame = new Rect();
325
326    /**
327     * Usually empty. Set to the task's tempInsetFrame. See
328     *{@link android.app.IActivityManager#resizeDockedStack}.
329     */
330    final Rect mInsetFrame = new Rect();
331
332    private static final Rect sTmpRect = new Rect();
333
334    boolean mContentChanged;
335
336    // If a window showing a wallpaper: the requested offset for the
337    // wallpaper; if a wallpaper window: the currently applied offset.
338    float mWallpaperX = -1;
339    float mWallpaperY = -1;
340
341    // If a window showing a wallpaper: what fraction of the offset
342    // range corresponds to a full virtual screen.
343    float mWallpaperXStep = -1;
344    float mWallpaperYStep = -1;
345
346    // If a window showing a wallpaper: a raw pixel offset to forcibly apply
347    // to its window; if a wallpaper window: not used.
348    int mWallpaperDisplayOffsetX = Integer.MIN_VALUE;
349    int mWallpaperDisplayOffsetY = Integer.MIN_VALUE;
350
351    // Wallpaper windows: pixels offset based on above variables.
352    int mXOffset;
353    int mYOffset;
354
355    /**
356     * This is set after IWindowSession.relayout() has been called at
357     * least once for the window.  It allows us to detect the situation
358     * where we don't yet have a surface, but should have one soon, so
359     * we can give the window focus before waiting for the relayout.
360     */
361    boolean mRelayoutCalled;
362
363    /**
364     * If the application has called relayout() with changes that can
365     * impact its window's size, we need to perform a layout pass on it
366     * even if it is not currently visible for layout.  This is set
367     * when in that case until the layout is done.
368     */
369    boolean mLayoutNeeded;
370
371    /** Currently running an exit animation? */
372    boolean mAnimatingExit;
373
374    /** Currently on the mDestroySurface list? */
375    boolean mDestroying;
376
377    /** Completely remove from window manager after exit animation? */
378    boolean mRemoveOnExit;
379
380    /**
381     * Whether the app died while it was visible, if true we might need
382     * to continue to show it until it's restarted.
383     */
384    boolean mAppDied;
385
386    /**
387     * Set when the orientation is changing and this window has not yet
388     * been updated for the new orientation.
389     */
390    boolean mOrientationChanging;
391
392    /**
393     * How long we last kept the screen frozen.
394     */
395    int mLastFreezeDuration;
396
397    /** Is this window now (or just being) removed? */
398    boolean mRemoved;
399
400    /**
401     * It is save to remove the window and destroy the surface because the client requested removal
402     * or some other higher level component said so (e.g. activity manager).
403     * TODO: We should either have different booleans for the removal reason or use a bit-field.
404     */
405    boolean mWindowRemovalAllowed;
406
407    /**
408     * Temp for keeping track of windows that have been removed when
409     * rebuilding window list.
410     */
411    boolean mRebuilding;
412
413    // Input channel and input window handle used by the input dispatcher.
414    final InputWindowHandle mInputWindowHandle;
415    InputChannel mInputChannel;
416    InputChannel mClientChannel;
417
418    // Used to improve performance of toString()
419    String mStringNameCache;
420    CharSequence mLastTitle;
421    boolean mWasExiting;
422
423    final WindowStateAnimator mWinAnimator;
424
425    boolean mHasSurface = false;
426
427    boolean mNotOnAppsDisplay = false;
428    DisplayContent  mDisplayContent;
429
430    /** When true this window can be displayed on screens owther than mOwnerUid's */
431    private boolean mShowToOwnerOnly;
432
433    // Whether the window has a saved surface from last pause, which can be
434    // used to start an entering animation earlier.
435    public boolean mSurfaceSaved = false;
436
437    // This window will be replaced due to relaunch. This allows window manager
438    // to differentiate between simple removal of a window and replacement. In the latter case it
439    // will preserve the old window until the new one is drawn.
440    boolean mWillReplaceWindow = false;
441    // If true, the replaced window was already requested to be removed.
442    boolean mReplacingRemoveRequested = false;
443    // Whether the replacement of the window should trigger app transition animation.
444    boolean mAnimateReplacingWindow = false;
445    // If not null, the window that will be used to replace the old one. This is being set when
446    // the window is added and unset when this window reports its first draw.
447    WindowState mReplacingWindow = null;
448    // For the new window in the replacement transition, if we have
449    // requested to replace without animation, then we should
450    // make sure we also don't apply an enter animation for
451    // the new window.
452    boolean mSkipEnterAnimationForSeamlessReplacement = false;
453    // Whether this window is being moved via the resize API
454    boolean mMovedByResize;
455
456    /**
457     * Wake lock for drawing.
458     * Even though it's slightly more expensive to do so, we will use a separate wake lock
459     * for each app that is requesting to draw while dozing so that we can accurately track
460     * who is preventing the system from suspending.
461     * This lock is only acquired on first use.
462     */
463    PowerManager.WakeLock mDrawLock;
464
465    final private Rect mTmpRect = new Rect();
466
467    /**
468     * See {@link #notifyMovedInStack}.
469     */
470    private boolean mJustMovedInStack;
471
472    /**
473     * Whether the window was resized by us while it was gone for layout.
474     */
475    boolean mResizedWhileGone = false;
476
477    /**
478     * Indicates whether we got resized but drag resizing flag was false. In this case, we also
479     * need to recreate the surface and defer surface bound updates in order to make sure the
480     * buffer contents and the positioning/size stay in sync.
481     */
482    boolean mResizedWhileNotDragResizing;
483
484    WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,
485           WindowState attachedWindow, int appOp, int seq, WindowManager.LayoutParams a,
486           int viewVisibility, final DisplayContent displayContent) {
487        mService = service;
488        mSession = s;
489        mClient = c;
490        mAppOp = appOp;
491        mToken = token;
492        mOwnerUid = s.mUid;
493        mWindowId = new IWindowId.Stub() {
494            @Override
495            public void registerFocusObserver(IWindowFocusObserver observer) {
496                WindowState.this.registerFocusObserver(observer);
497            }
498            @Override
499            public void unregisterFocusObserver(IWindowFocusObserver observer) {
500                WindowState.this.unregisterFocusObserver(observer);
501            }
502            @Override
503            public boolean isFocused() {
504                return WindowState.this.isFocused();
505            }
506        };
507        mAttrs.copyFrom(a);
508        mViewVisibility = viewVisibility;
509        mDisplayContent = displayContent;
510        mPolicy = mService.mPolicy;
511        mContext = mService.mContext;
512        DeathRecipient deathRecipient = new DeathRecipient();
513        mSeq = seq;
514        mEnforceSizeCompat = (mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0;
515        if (WindowManagerService.localLOGV) Slog.v(
516            TAG, "Window " + this + " client=" + c.asBinder()
517            + " token=" + token + " (" + mAttrs.token + ")" + " params=" + a);
518        try {
519            c.asBinder().linkToDeath(deathRecipient, 0);
520        } catch (RemoteException e) {
521            mDeathRecipient = null;
522            mAttachedWindow = null;
523            mLayoutAttached = false;
524            mIsImWindow = false;
525            mIsWallpaper = false;
526            mIsFloatingLayer = false;
527            mBaseLayer = 0;
528            mSubLayer = 0;
529            mInputWindowHandle = null;
530            mWinAnimator = null;
531            return;
532        }
533        mDeathRecipient = deathRecipient;
534
535        if ((mAttrs.type >= FIRST_SUB_WINDOW &&
536                mAttrs.type <= LAST_SUB_WINDOW)) {
537            // The multiplier here is to reserve space for multiple
538            // windows in the same type layer.
539            mBaseLayer = mPolicy.windowTypeToLayerLw(
540                    attachedWindow.mAttrs.type) * WindowManagerService.TYPE_LAYER_MULTIPLIER
541                    + WindowManagerService.TYPE_LAYER_OFFSET;
542            mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
543            mAttachedWindow = attachedWindow;
544            if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + mAttachedWindow);
545
546            final WindowList childWindows = mAttachedWindow.mChildWindows;
547            final int numChildWindows = childWindows.size();
548            if (numChildWindows == 0) {
549                childWindows.add(this);
550            } else {
551                boolean added = false;
552                for (int i = 0; i < numChildWindows; i++) {
553                    final int childSubLayer = childWindows.get(i).mSubLayer;
554                    if (mSubLayer < childSubLayer
555                            || (mSubLayer == childSubLayer && childSubLayer < 0)) {
556                        // We insert the child window into the list ordered by the sub-layer. For
557                        // same sub-layers, the negative one should go below others; the positive
558                        // one should go above others.
559                        childWindows.add(i, this);
560                        added = true;
561                        break;
562                    }
563                }
564                if (!added) {
565                    childWindows.add(this);
566                }
567            }
568
569            mLayoutAttached = mAttrs.type !=
570                    WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
571            mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
572                    || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
573            mIsWallpaper = attachedWindow.mAttrs.type == TYPE_WALLPAPER;
574            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
575        } else {
576            // The multiplier here is to reserve space for multiple
577            // windows in the same type layer.
578            mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
579                    * WindowManagerService.TYPE_LAYER_MULTIPLIER
580                    + WindowManagerService.TYPE_LAYER_OFFSET;
581            mSubLayer = 0;
582            mAttachedWindow = null;
583            mLayoutAttached = false;
584            mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
585                    || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
586            mIsWallpaper = mAttrs.type == TYPE_WALLPAPER;
587            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
588        }
589
590        WindowState appWin = this;
591        while (appWin.isChildWindow()) {
592            appWin = appWin.mAttachedWindow;
593        }
594        WindowToken appToken = appWin.mToken;
595        while (appToken.appWindowToken == null) {
596            WindowToken parent = mService.mTokenMap.get(appToken.token);
597            if (parent == null || appToken == parent) {
598                break;
599            }
600            appToken = parent;
601        }
602        mRootToken = appToken;
603        mAppToken = appToken.appWindowToken;
604        if (mAppToken != null) {
605            final DisplayContent appDisplay = getDisplayContent();
606            mNotOnAppsDisplay = displayContent != appDisplay;
607
608            if (mAppToken.showForAllUsers) {
609                // Windows for apps that can show for all users should also show when the
610                // device is locked.
611                mAttrs.flags |= FLAG_SHOW_WHEN_LOCKED;
612            }
613        }
614
615        mWinAnimator = new WindowStateAnimator(this);
616        mWinAnimator.mAlpha = a.alpha;
617
618        mRequestedWidth = 0;
619        mRequestedHeight = 0;
620        mLastRequestedWidth = 0;
621        mLastRequestedHeight = 0;
622        mXOffset = 0;
623        mYOffset = 0;
624        mLayer = 0;
625        mInputWindowHandle = new InputWindowHandle(
626                mAppToken != null ? mAppToken.mInputApplicationHandle : null, this,
627                displayContent.getDisplayId());
628    }
629
630    void attach() {
631        if (WindowManagerService.localLOGV) Slog.v(
632            TAG, "Attaching " + this + " token=" + mToken
633            + ", list=" + mToken.windows);
634        mSession.windowAddedLocked();
635    }
636
637    @Override
638    public int getOwningUid() {
639        return mOwnerUid;
640    }
641
642    @Override
643    public String getOwningPackage() {
644        return mAttrs.packageName;
645    }
646
647    /**
648     * Subtracts the insets calculated by intersecting {@param layoutFrame} with {@param insetFrame}
649     * from {@param frame}. In other words, it applies the insets that would result if
650     * {@param frame} would be shifted to {@param layoutFrame} and then applying the insets from
651     * {@param insetFrame}. Also it respects {@param displayFrame} in case window has minimum
652     * width/height applied and insets should be overridden.
653     */
654    private void subtractInsets(Rect frame, Rect layoutFrame, Rect insetFrame, Rect displayFrame) {
655        final int left = Math.max(0, insetFrame.left - Math.max(layoutFrame.left, displayFrame.left));
656        final int top = Math.max(0, insetFrame.top - Math.max(layoutFrame.top, displayFrame.top));
657        final int right = Math.max(0, Math.min(layoutFrame.right, displayFrame.right) - insetFrame.right);
658        final int bottom = Math.max(0, Math.min(layoutFrame.bottom, displayFrame.bottom) - insetFrame.bottom);
659        frame.inset(left, top, right, bottom);
660    }
661
662    @Override
663    public void computeFrameLw(Rect pf, Rect df, Rect of, Rect cf, Rect vf, Rect dcf, Rect sf,
664            Rect osf) {
665        if (mWillReplaceWindow && (mAnimatingExit || !mReplacingRemoveRequested)) {
666            // This window is being replaced and either already got information that it's being
667            // removed or we are still waiting for some information. Because of this we don't
668            // want to apply any more changes to it, so it remains in this state until new window
669            // appears.
670            return;
671        }
672        mHaveFrame = true;
673
674        final Task task = getTask();
675        final boolean fullscreenTask = !isInMultiWindowMode();
676        final boolean windowsAreFloating = task != null && task.isFloating();
677
678        // If the task has temp inset bounds set, we have to make sure all its windows uses
679        // the temp inset frame. Otherwise different display frames get applied to the main
680        // window and the child window, making them misaligned.
681        if (fullscreenTask) {
682            mInsetFrame.setEmpty();
683        } else {
684            task.getTempInsetBounds(mInsetFrame);
685        }
686
687        // Denotes the actual frame used to calculate the insets and to perform the layout. When
688        // resizing in docked mode, we'd like to freeze the layout, so we also need to freeze the
689        // insets temporarily. By the notion of a task having a different layout frame, we can
690        // achieve that while still moving the task around.
691        final Rect layoutContainingFrame;
692        final Rect layoutDisplayFrame;
693
694        // The offset from the layout containing frame to the actual containing frame.
695        final int layoutXDiff;
696        final int layoutYDiff;
697        if (mInsetFrame.isEmpty() && (fullscreenTask || layoutInParentFrame())) {
698            // We use the parent frame as the containing frame for fullscreen and child windows
699            mContainingFrame.set(pf);
700            mDisplayFrame.set(df);
701            layoutDisplayFrame = df;
702            layoutContainingFrame = pf;
703            layoutXDiff = 0;
704            layoutYDiff = 0;
705        } else {
706            task.getBounds(mContainingFrame);
707            if (mAppToken != null && !mAppToken.mFrozenBounds.isEmpty()) {
708
709                // If the bounds are frozen, we still want to translate the window freely and only
710                // freeze the size.
711                Rect frozen = mAppToken.mFrozenBounds.peek();
712                mContainingFrame.right = mContainingFrame.left + frozen.width();
713                mContainingFrame.bottom = mContainingFrame.top + frozen.height();
714            }
715            final WindowState imeWin = mService.mInputMethodWindow;
716            // IME is up and obscuring this window. Adjust the window position so it is visible.
717            if (imeWin != null && imeWin.isVisibleNow() && mService.mInputMethodTarget == this) {
718                    if (windowsAreFloating && mContainingFrame.bottom > cf.bottom) {
719                        // In freeform we want to move the top up directly.
720                        // TODO: Investigate why this is cf not pf.
721                        mContainingFrame.top -= mContainingFrame.bottom - cf.bottom;
722                    } else if (mContainingFrame.bottom > pf.bottom) {
723                        // But in docked we want to behave like fullscreen
724                        // and behave as if the task were given smaller bounds
725                        // for the purposes of layout.
726                        mContainingFrame.bottom = pf.bottom;
727                    }
728            }
729
730            if (windowsAreFloating) {
731                // In floating modes (e.g. freeform, pinned) we have only to set the rectangle
732                // if it wasn't set already. No need to intersect it with the (visible)
733                // "content frame" since it is allowed to be outside the visible desktop.
734                if (mContainingFrame.isEmpty()) {
735                    mContainingFrame.set(cf);
736                }
737            }
738            mDisplayFrame.set(mContainingFrame);
739            layoutXDiff = !mInsetFrame.isEmpty() ? mInsetFrame.left - mContainingFrame.left : 0;
740            layoutYDiff = !mInsetFrame.isEmpty() ? mInsetFrame.top - mContainingFrame.top : 0;
741            layoutContainingFrame = !mInsetFrame.isEmpty() ? mInsetFrame : mContainingFrame;
742            mTmpRect.set(0, 0, mDisplayContent.getDisplayInfo().logicalWidth,
743                    mDisplayContent.getDisplayInfo().logicalHeight);
744            subtractInsets(mDisplayFrame, layoutContainingFrame, df, mTmpRect);
745            if (!layoutInParentFrame()) {
746                subtractInsets(mContainingFrame, layoutContainingFrame, pf, mTmpRect);
747                subtractInsets(mInsetFrame, layoutContainingFrame, pf, mTmpRect);
748            }
749            layoutDisplayFrame = df;
750            layoutDisplayFrame.intersect(layoutContainingFrame);
751        }
752
753        final int pw = mContainingFrame.width();
754        final int ph = mContainingFrame.height();
755
756        if (!mParentFrame.equals(pf)) {
757            //Slog.i(TAG_WM, "Window " + this + " content frame from " + mParentFrame
758            //        + " to " + pf);
759            mParentFrame.set(pf);
760            mContentChanged = true;
761        }
762        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
763            mLastRequestedWidth = mRequestedWidth;
764            mLastRequestedHeight = mRequestedHeight;
765            mContentChanged = true;
766        }
767
768        mOverscanFrame.set(of);
769        mContentFrame.set(cf);
770        mVisibleFrame.set(vf);
771        mDecorFrame.set(dcf);
772        mStableFrame.set(sf);
773        final boolean hasOutsets = osf != null;
774        if (hasOutsets) {
775            mOutsetFrame.set(osf);
776        }
777
778        final int fw = mFrame.width();
779        final int fh = mFrame.height();
780
781        applyGravityAndUpdateFrame(layoutContainingFrame, layoutDisplayFrame);
782
783        // Offset the actual frame by the amount layout frame is off.
784        mFrame.offset(-layoutXDiff, -layoutYDiff);
785        mCompatFrame.offset(-layoutXDiff, -layoutYDiff);
786
787        // Calculate the outsets before the content frame gets shrinked to the window frame.
788        if (hasOutsets) {
789            mOutsets.set(Math.max(mContentFrame.left - mOutsetFrame.left, 0),
790                    Math.max(mContentFrame.top - mOutsetFrame.top, 0),
791                    Math.max(mOutsetFrame.right - mContentFrame.right, 0),
792                    Math.max(mOutsetFrame.bottom - mContentFrame.bottom, 0));
793        } else {
794            mOutsets.set(0, 0, 0, 0);
795        }
796
797        // Make sure the content and visible frames are inside of the
798        // final window frame.
799        if (windowsAreFloating && !mFrame.isEmpty()) {
800            // Keep the frame out of the blocked system area, limit it in size to the content area
801            // and make sure that there is always a minimum visible so that the user can drag it
802            // into a usable area..
803            final int height = Math.min(mFrame.height(), mContentFrame.height());
804            final int width = Math.min(mContentFrame.width(), mFrame.width());
805            final DisplayMetrics displayMetrics = getDisplayContent().getDisplayMetrics();
806            final int minVisibleHeight = WindowManagerService.dipToPixel(
807                    MINIMUM_VISIBLE_HEIGHT_IN_DP, displayMetrics);
808            final int minVisibleWidth = WindowManagerService.dipToPixel(
809                    MINIMUM_VISIBLE_WIDTH_IN_DP, displayMetrics);
810            final int top = Math.max(mContentFrame.top,
811                    Math.min(mFrame.top, mContentFrame.bottom - minVisibleHeight));
812            final int left = Math.max(mContentFrame.left + minVisibleWidth - width,
813                    Math.min(mFrame.left, mContentFrame.right - minVisibleWidth));
814            mFrame.set(left, top, left + width, top + height);
815            mContentFrame.set(mFrame);
816            mVisibleFrame.set(mContentFrame);
817            mStableFrame.set(mContentFrame);
818        } else if (mAttrs.type == TYPE_DOCK_DIVIDER) {
819            mDisplayContent.getDockedDividerController().positionDockedStackedDivider(mFrame);
820            mContentFrame.set(mFrame);
821            if (!mFrame.equals(mLastFrame)) {
822                mMovedByResize = true;
823            }
824        } else {
825            mContentFrame.set(Math.max(mContentFrame.left, layoutContainingFrame.left),
826                    Math.max(mContentFrame.top, layoutContainingFrame.top),
827                    Math.min(mContentFrame.right, layoutContainingFrame.right),
828                    Math.min(mContentFrame.bottom, layoutContainingFrame.bottom));
829
830            mVisibleFrame.set(Math.max(mVisibleFrame.left, layoutContainingFrame.left),
831                    Math.max(mVisibleFrame.top, layoutContainingFrame.top),
832                    Math.min(mVisibleFrame.right, layoutContainingFrame.right),
833                    Math.min(mVisibleFrame.bottom, layoutContainingFrame.bottom));
834
835            mStableFrame.set(Math.max(mStableFrame.left, layoutContainingFrame.left),
836                    Math.max(mStableFrame.top, layoutContainingFrame.top),
837                    Math.min(mStableFrame.right, layoutContainingFrame.right),
838                    Math.min(mStableFrame.bottom, layoutContainingFrame.bottom));
839        }
840
841        if (fullscreenTask && !windowsAreFloating) {
842            // Windows that are not fullscreen can be positioned outside of the display frame,
843            // but that is not a reason to provide them with overscan insets.
844            mOverscanInsets.set(Math.max(mOverscanFrame.left - layoutContainingFrame.left, 0),
845                    Math.max(mOverscanFrame.top - layoutContainingFrame.top, 0),
846                    Math.max(layoutContainingFrame.right - mOverscanFrame.right, 0),
847                    Math.max(layoutContainingFrame.bottom - mOverscanFrame.bottom, 0));
848        }
849
850        if (mAttrs.type == TYPE_DOCK_DIVIDER) {
851            // For the docked divider, we calculate the stable insets like a full-screen window
852            // so it can use it to calculate the snap positions.
853            mStableInsets.set(Math.max(mStableFrame.left - mDisplayFrame.left, 0),
854                    Math.max(mStableFrame.top - mDisplayFrame.top, 0),
855                    Math.max(mDisplayFrame.right - mStableFrame.right, 0),
856                    Math.max(mDisplayFrame.bottom - mStableFrame.bottom, 0));
857
858            // The divider doesn't care about insets in any case, so set it to empty so we don't
859            // trigger a relayout when moving it.
860            mContentInsets.setEmpty();
861            mVisibleInsets.setEmpty();
862        } else {
863            getDisplayContent().getLogicalDisplayRect(mTmpRect);
864            // Override right and/or bottom insets in case if the frame doesn't fit the screen in
865            // non-fullscreen mode.
866            boolean overrideRightInset = !fullscreenTask && layoutContainingFrame.right > mTmpRect.right;
867            boolean overrideBottomInset = !fullscreenTask && layoutContainingFrame.bottom > mTmpRect.bottom;
868            mContentInsets.set(mContentFrame.left - layoutContainingFrame.left,
869                    mContentFrame.top - layoutContainingFrame.top,
870                    overrideRightInset ? mTmpRect.right - mContentFrame.right
871                            : layoutContainingFrame.right - mContentFrame.right,
872                    overrideBottomInset ? mTmpRect.bottom - mContentFrame.bottom
873                            : layoutContainingFrame.bottom - mContentFrame.bottom);
874
875            mVisibleInsets.set(mVisibleFrame.left - layoutContainingFrame.left,
876                    mVisibleFrame.top - layoutContainingFrame.top,
877                    overrideRightInset ? mTmpRect.right - mVisibleFrame.right
878                            : layoutContainingFrame.right - mVisibleFrame.right,
879                    overrideBottomInset ? mTmpRect.bottom - mVisibleFrame.bottom
880                            : layoutContainingFrame.bottom - mVisibleFrame.bottom);
881
882            mStableInsets.set(Math.max(mStableFrame.left - layoutContainingFrame.left, 0),
883                    Math.max(mStableFrame.top - layoutContainingFrame.top, 0),
884                    overrideRightInset ? Math.max(mTmpRect.right - mStableFrame.right, 0)
885                            : Math.max(layoutContainingFrame.right - mStableFrame.right, 0),
886                    overrideBottomInset ? Math.max(mTmpRect.bottom - mStableFrame.bottom, 0)
887                            :  Math.max(layoutContainingFrame.bottom - mStableFrame.bottom, 0));
888        }
889
890        mContentFrame.offset(-layoutXDiff, -layoutYDiff);
891        mVisibleFrame.offset(-layoutXDiff, -layoutYDiff);
892        mStableFrame.offset(-layoutXDiff, -layoutYDiff);
893
894        mCompatFrame.set(mFrame);
895        if (mEnforceSizeCompat) {
896            // If there is a size compatibility scale being applied to the
897            // window, we need to apply this to its insets so that they are
898            // reported to the app in its coordinate space.
899            mOverscanInsets.scale(mInvGlobalScale);
900            mContentInsets.scale(mInvGlobalScale);
901            mVisibleInsets.scale(mInvGlobalScale);
902            mStableInsets.scale(mInvGlobalScale);
903            mOutsets.scale(mInvGlobalScale);
904
905            // Also the scaled frame that we report to the app needs to be
906            // adjusted to be in its coordinate space.
907            mCompatFrame.scale(mInvGlobalScale);
908        }
909
910        if (mIsWallpaper && (fw != mFrame.width() || fh != mFrame.height())) {
911            final DisplayContent displayContent = getDisplayContent();
912            if (displayContent != null) {
913                final DisplayInfo displayInfo = displayContent.getDisplayInfo();
914                mService.mWallpaperControllerLocked.updateWallpaperOffset(
915                        this, displayInfo.logicalWidth, displayInfo.logicalHeight, false);
916            }
917        }
918
919        if (DEBUG_LAYOUT || WindowManagerService.localLOGV) Slog.v(TAG,
920                "Resolving (mRequestedWidth="
921                + mRequestedWidth + ", mRequestedheight="
922                + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
923                + "): frame=" + mFrame.toShortString()
924                + " ci=" + mContentInsets.toShortString()
925                + " vi=" + mVisibleInsets.toShortString()
926                + " si=" + mStableInsets.toShortString()
927                + " of=" + mOutsets.toShortString());
928    }
929
930    @Override
931    public Rect getFrameLw() {
932        return mFrame;
933    }
934
935    @Override
936    public Point getShownPositionLw() {
937        return mShownPosition;
938    }
939
940    @Override
941    public Rect getDisplayFrameLw() {
942        return mDisplayFrame;
943    }
944
945    @Override
946    public Rect getOverscanFrameLw() {
947        return mOverscanFrame;
948    }
949
950    @Override
951    public Rect getContentFrameLw() {
952        return mContentFrame;
953    }
954
955    @Override
956    public Rect getVisibleFrameLw() {
957        return mVisibleFrame;
958    }
959
960    @Override
961    public boolean getGivenInsetsPendingLw() {
962        return mGivenInsetsPending;
963    }
964
965    @Override
966    public Rect getGivenContentInsetsLw() {
967        return mGivenContentInsets;
968    }
969
970    @Override
971    public Rect getGivenVisibleInsetsLw() {
972        return mGivenVisibleInsets;
973    }
974
975    @Override
976    public WindowManager.LayoutParams getAttrs() {
977        return mAttrs;
978    }
979
980    @Override
981    public boolean getNeedsMenuLw(WindowManagerPolicy.WindowState bottom) {
982        int index = -1;
983        WindowState ws = this;
984        WindowList windows = getWindowList();
985        while (true) {
986            if (ws.mAttrs.needsMenuKey != WindowManager.LayoutParams.NEEDS_MENU_UNSET) {
987                return ws.mAttrs.needsMenuKey == WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE;
988            }
989            // If we reached the bottom of the range of windows we are considering,
990            // assume no menu is needed.
991            if (ws == bottom) {
992                return false;
993            }
994            // The current window hasn't specified whether menu key is needed;
995            // look behind it.
996            // First, we may need to determine the starting position.
997            if (index < 0) {
998                index = windows.indexOf(ws);
999            }
1000            index--;
1001            if (index < 0) {
1002                return false;
1003            }
1004            ws = windows.get(index);
1005        }
1006    }
1007
1008    @Override
1009    public int getSystemUiVisibility() {
1010        return mSystemUiVisibility;
1011    }
1012
1013    @Override
1014    public int getSurfaceLayer() {
1015        return mLayer;
1016    }
1017
1018    @Override
1019    public int getBaseType() {
1020        WindowState win = this;
1021        while (win.isChildWindow()) {
1022            win = win.mAttachedWindow;
1023        }
1024        return win.mAttrs.type;
1025    }
1026
1027    @Override
1028    public IApplicationToken getAppToken() {
1029        return mAppToken != null ? mAppToken.appToken : null;
1030    }
1031
1032    @Override
1033    public boolean isVoiceInteraction() {
1034        return mAppToken != null && mAppToken.voiceInteraction;
1035    }
1036
1037    boolean setInsetsChanged() {
1038        mOverscanInsetsChanged |= !mLastOverscanInsets.equals(mOverscanInsets);
1039        mContentInsetsChanged |= !mLastContentInsets.equals(mContentInsets);
1040        mVisibleInsetsChanged |= !mLastVisibleInsets.equals(mVisibleInsets);
1041        mStableInsetsChanged |= !mLastStableInsets.equals(mStableInsets);
1042        mOutsetsChanged |= !mLastOutsets.equals(mOutsets);
1043        return mOverscanInsetsChanged || mContentInsetsChanged || mVisibleInsetsChanged
1044                || mOutsetsChanged;
1045    }
1046
1047    public DisplayContent getDisplayContent() {
1048        if (mAppToken == null || mNotOnAppsDisplay) {
1049            return mDisplayContent;
1050        }
1051        final TaskStack stack = getStack();
1052        return stack == null ? mDisplayContent : stack.getDisplayContent();
1053    }
1054
1055    public DisplayInfo getDisplayInfo() {
1056        final DisplayContent displayContent = getDisplayContent();
1057        return displayContent != null ? displayContent.getDisplayInfo() : null;
1058    }
1059
1060    public int getDisplayId() {
1061        final DisplayContent displayContent = getDisplayContent();
1062        if (displayContent == null) {
1063            return -1;
1064        }
1065        return displayContent.getDisplayId();
1066    }
1067
1068    Task getTask() {
1069        return mAppToken != null ? mAppToken.mTask : null;
1070    }
1071
1072    TaskStack getStack() {
1073        Task task = getTask();
1074        if (task != null) {
1075            if (task.mStack != null) {
1076                return task.mStack;
1077            }
1078        }
1079        // Some system windows (e.g. "Power off" dialog) don't have a task, but we would still
1080        // associate them with some stack to enable dimming.
1081        return mAttrs.type >= WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1082                && mDisplayContent != null ? mDisplayContent.getHomeStack() : null;
1083    }
1084
1085    /**
1086     * Retrieves the visible bounds of the window.
1087     * @param bounds The rect which gets the bounds.
1088     */
1089    void getVisibleBounds(Rect bounds) {
1090        final Task task = getTask();
1091        boolean intersectWithStackBounds = task != null && task.cropWindowsToStackBounds();
1092        bounds.setEmpty();
1093        mTmpRect.setEmpty();
1094        if (intersectWithStackBounds) {
1095            final TaskStack stack = task.mStack;
1096            if (stack != null) {
1097                stack.getDimBounds(mTmpRect);
1098            } else {
1099                intersectWithStackBounds = false;
1100            }
1101        }
1102
1103        bounds.set(mVisibleFrame);
1104        if (intersectWithStackBounds) {
1105            bounds.intersect(mTmpRect);
1106        }
1107
1108        if (bounds.isEmpty()) {
1109            bounds.set(mFrame);
1110            if (intersectWithStackBounds) {
1111                bounds.intersect(mTmpRect);
1112            }
1113            return;
1114        }
1115    }
1116
1117    public long getInputDispatchingTimeoutNanos() {
1118        return mAppToken != null
1119                ? mAppToken.inputDispatchingTimeoutNanos
1120                : WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
1121    }
1122
1123    @Override
1124    public boolean hasAppShownWindows() {
1125        return mAppToken != null && (mAppToken.firstWindowDrawn || mAppToken.startingDisplayed);
1126    }
1127
1128    boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
1129        if (dsdx < .99999f || dsdx > 1.00001f) return false;
1130        if (dtdy < .99999f || dtdy > 1.00001f) return false;
1131        if (dtdx < -.000001f || dtdx > .000001f) return false;
1132        if (dsdy < -.000001f || dsdy > .000001f) return false;
1133        return true;
1134    }
1135
1136    void prelayout() {
1137        if (mEnforceSizeCompat) {
1138            mGlobalScale = mService.mCompatibleScreenScale;
1139            mInvGlobalScale = 1/mGlobalScale;
1140        } else {
1141            mGlobalScale = mInvGlobalScale = 1;
1142        }
1143    }
1144
1145    /**
1146     * Does the minimal check for visibility. Callers generally want to use one of the public
1147     * methods as they perform additional checks on the app token.
1148     * TODO: See if there are other places we can use this check below instead of duplicating...
1149     */
1150    private boolean isVisibleUnchecked() {
1151        return mHasSurface && mPolicyVisibility && !mAttachedHidden
1152                && !mAnimatingExit && !mDestroying && (!mIsWallpaper || mWallpaperVisible);
1153    }
1154
1155    /**
1156     * Is this window visible?  It is not visible if there is no surface, or we are in the process
1157     * of running an exit animation that will remove the surface, or its app token has been hidden.
1158     */
1159    @Override
1160    public boolean isVisibleLw() {
1161        return (mAppToken == null || !mAppToken.hiddenRequested) && isVisibleUnchecked();
1162    }
1163
1164    /**
1165     * Like {@link #isVisibleLw}, but also counts a window that is currently "hidden" behind the
1166     * keyguard as visible.  This allows us to apply things like window flags that impact the
1167     * keyguard. XXX I am starting to think we need to have ANOTHER visibility flag for this
1168     * "hidden behind keyguard" state rather than overloading mPolicyVisibility.  Ungh.
1169     */
1170    @Override
1171    public boolean isVisibleOrBehindKeyguardLw() {
1172        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
1173            return false;
1174        }
1175        final AppWindowToken atoken = mAppToken;
1176        final boolean animating = atoken != null && atoken.mAppAnimator.animation != null;
1177        return mHasSurface && !mDestroying && !mAnimatingExit
1178                && (atoken == null ? mPolicyVisibility : !atoken.hiddenRequested)
1179                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE && !mRootToken.hidden)
1180                        || mWinAnimator.mAnimation != null || animating);
1181    }
1182
1183    /**
1184     * Is this window visible, ignoring its app token? It is not visible if there is no surface,
1185     * or we are in the process of running an exit animation that will remove the surface.
1186     */
1187    public boolean isWinVisibleLw() {
1188        return (mAppToken == null || !mAppToken.hiddenRequested || mAppToken.mAppAnimator.animating)
1189                && isVisibleUnchecked();
1190    }
1191
1192    /**
1193     * The same as isVisible(), but follows the current hidden state of the associated app token,
1194     * not the pending requested hidden state.
1195     */
1196    boolean isVisibleNow() {
1197        return (!mRootToken.hidden || mAttrs.type == TYPE_APPLICATION_STARTING)
1198                && isVisibleUnchecked();
1199    }
1200
1201    /**
1202     * Can this window possibly be a drag/drop target?  The test here is
1203     * a combination of the above "visible now" with the check that the
1204     * Input Manager uses when discarding windows from input consideration.
1205     */
1206    boolean isPotentialDragTarget() {
1207        return isVisibleNow() && !mRemoved
1208                && mInputChannel != null && mInputWindowHandle != null;
1209    }
1210
1211    /**
1212     * Same as isVisible(), but we also count it as visible between the
1213     * call to IWindowSession.add() and the first relayout().
1214     */
1215    boolean isVisibleOrAdding() {
1216        final AppWindowToken atoken = mAppToken;
1217        return (mHasSurface || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
1218                && mPolicyVisibility && !mAttachedHidden
1219                && (atoken == null || !atoken.hiddenRequested)
1220                && !mAnimatingExit && !mDestroying;
1221    }
1222
1223    /**
1224     * Is this window currently on-screen?  It is on-screen either if it
1225     * is visible or it is currently running an animation before no longer
1226     * being visible.
1227     */
1228    boolean isOnScreen() {
1229        return mPolicyVisibility && isOnScreenIgnoringKeyguard();
1230    }
1231
1232    /**
1233     * Like isOnScreen(), but ignores any force hiding of the window due
1234     * to the keyguard.
1235     */
1236    boolean isOnScreenIgnoringKeyguard() {
1237        if (!mHasSurface || mDestroying) {
1238            return false;
1239        }
1240        final AppWindowToken atoken = mAppToken;
1241        if (atoken != null) {
1242            return ((!mAttachedHidden && !atoken.hiddenRequested)
1243                    || mWinAnimator.mAnimation != null || atoken.mAppAnimator.animation != null);
1244        }
1245        return !mAttachedHidden || mWinAnimator.mAnimation != null;
1246    }
1247
1248    /**
1249     * Like isOnScreen(), but we don't return true if the window is part
1250     * of a transition that has not yet been started.
1251     */
1252    boolean isReadyForDisplay() {
1253        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
1254            return false;
1255        }
1256        return mHasSurface && mPolicyVisibility && !mDestroying
1257                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE && !mRootToken.hidden)
1258                        || mWinAnimator.mAnimation != null
1259                        || ((mAppToken != null) && (mAppToken.mAppAnimator.animation != null)));
1260    }
1261
1262    /**
1263     * Like isReadyForDisplay(), but ignores any force hiding of the window due
1264     * to the keyguard.
1265     */
1266    boolean isReadyForDisplayIgnoringKeyguard() {
1267        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
1268            return false;
1269        }
1270        final AppWindowToken atoken = mAppToken;
1271        if (atoken == null && !mPolicyVisibility) {
1272            // If this is not an app window, and the policy has asked to force
1273            // hide, then we really do want to hide.
1274            return false;
1275        }
1276        return mHasSurface && !mDestroying
1277                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE && !mRootToken.hidden)
1278                        || mWinAnimator.mAnimation != null
1279                        || ((atoken != null) && (atoken.mAppAnimator.animation != null)
1280                                && !mWinAnimator.isDummyAnimation()));
1281    }
1282
1283    /**
1284     * Like isOnScreen, but returns false if the surface hasn't yet
1285     * been drawn.
1286     */
1287    @Override
1288    public boolean isDisplayedLw() {
1289        final AppWindowToken atoken = mAppToken;
1290        return isDrawnLw() && mPolicyVisibility
1291            && ((!mAttachedHidden &&
1292                    (atoken == null || !atoken.hiddenRequested))
1293                        || mWinAnimator.mAnimating
1294                        || (atoken != null && atoken.mAppAnimator.animation != null));
1295    }
1296
1297    /**
1298     * Return true if this window or its app token is currently animating.
1299     */
1300    @Override
1301    public boolean isAnimatingLw() {
1302        return mWinAnimator.mAnimation != null
1303                || (mAppToken != null && mAppToken.mAppAnimator.animation != null);
1304    }
1305
1306    @Override
1307    public boolean isGoneForLayoutLw() {
1308        final AppWindowToken atoken = mAppToken;
1309        return mViewVisibility == View.GONE
1310                || !mRelayoutCalled
1311                || (atoken == null && mRootToken.hidden)
1312                || (atoken != null && atoken.hiddenRequested)
1313                || mAttachedHidden
1314                || (mAnimatingExit && !isAnimatingLw())
1315                || mDestroying;
1316    }
1317
1318    /**
1319     * Returns true if the window has a surface that it has drawn a
1320     * complete UI in to.
1321     */
1322    public boolean isDrawFinishedLw() {
1323        return mHasSurface && !mDestroying &&
1324                (mWinAnimator.mDrawState == WindowStateAnimator.COMMIT_DRAW_PENDING
1325                || mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1326                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1327    }
1328
1329    /**
1330     * Returns true if the window has a surface that it has drawn a
1331     * complete UI in to.
1332     */
1333    @Override
1334    public boolean isDrawnLw() {
1335        return mHasSurface && !mDestroying &&
1336                (mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1337                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1338    }
1339
1340    /**
1341     * Return true if the window is opaque and fully drawn.  This indicates
1342     * it may obscure windows behind it.
1343     */
1344    boolean isOpaqueDrawn() {
1345        // When there is keyguard, wallpaper could be placed over the secure app
1346        // window but invisible. We need to check wallpaper visibility explicitly
1347        // to determine if it's occluding apps.
1348        return ((!mIsWallpaper && mAttrs.format == PixelFormat.OPAQUE)
1349                || (mIsWallpaper && mWallpaperVisible))
1350                && isDrawnLw() && mWinAnimator.mAnimation == null
1351                && (mAppToken == null || mAppToken.mAppAnimator.animation == null);
1352    }
1353
1354    /**
1355     * Return whether this window has moved. (Only makes
1356     * sense to call from performLayoutAndPlaceSurfacesLockedInner().)
1357     */
1358    boolean hasMoved() {
1359        return mHasSurface && (mContentChanged || mMovedByResize)
1360                && !mAnimatingExit && mService.okToDisplay()
1361                && (mFrame.top != mLastFrame.top || mFrame.left != mLastFrame.left)
1362                && (mAttachedWindow == null || !mAttachedWindow.hasMoved());
1363    }
1364
1365    boolean isObscuringFullscreen(final DisplayInfo displayInfo) {
1366        Task task = getTask();
1367        if (task != null && task.mStack != null && !task.mStack.isFullscreen()) {
1368            return false;
1369        }
1370        if (!isOpaqueDrawn() || !isFrameFullscreen(displayInfo)) {
1371            return false;
1372        }
1373        return true;
1374    }
1375
1376    boolean isFrameFullscreen(final DisplayInfo displayInfo) {
1377        return mFrame.left <= 0 && mFrame.top <= 0
1378                && mFrame.right >= displayInfo.appWidth && mFrame.bottom >= displayInfo.appHeight;
1379    }
1380
1381    boolean isConfigChanged() {
1382        final Task task = getTask();
1383        final Configuration overrideConfig =
1384                (task != null) ? task.mOverrideConfig : Configuration.EMPTY;
1385        final Configuration serviceConfig = mService.mCurConfiguration;
1386        boolean configChanged =
1387                (mConfiguration != serviceConfig && mConfiguration.diff(serviceConfig) != 0)
1388                || (mOverrideConfig != overrideConfig && !mOverrideConfig.equals(overrideConfig));
1389
1390        if ((mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
1391            // Retain configuration changed status until resetConfiguration called.
1392            mConfigHasChanged |= configChanged;
1393            configChanged = mConfigHasChanged;
1394        }
1395
1396        return configChanged;
1397    }
1398
1399    void removeLocked() {
1400        disposeInputChannel();
1401
1402        if (isChildWindow()) {
1403            if (DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
1404            mAttachedWindow.mChildWindows.remove(this);
1405        }
1406        mWinAnimator.destroyDeferredSurfaceLocked();
1407        mWinAnimator.destroySurfaceLocked();
1408        mSession.windowRemovedLocked();
1409        try {
1410            mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
1411        } catch (RuntimeException e) {
1412            // Ignore if it has already been removed (usually because
1413            // we are doing this as part of processing a death note.)
1414        }
1415    }
1416
1417    private void setConfiguration(
1418            final Configuration newConfig, final Configuration newOverrideConfig) {
1419        mConfiguration = newConfig;
1420        mOverrideConfig = newOverrideConfig;
1421        mConfigHasChanged = false;
1422
1423        mMergedConfiguration.setTo(newConfig);
1424        if (newOverrideConfig != null && newOverrideConfig != Configuration.EMPTY) {
1425            mMergedConfiguration.updateFrom(newOverrideConfig);
1426        }
1427    }
1428
1429    void setHasSurface(boolean hasSurface) {
1430        mHasSurface = hasSurface;
1431    }
1432
1433    int getAnimLayerAdjustment() {
1434        if (mTargetAppToken != null) {
1435            return mTargetAppToken.mAppAnimator.animLayerAdjustment;
1436        } else if (mAppToken != null) {
1437            return mAppToken.mAppAnimator.animLayerAdjustment;
1438        } else {
1439            // Nothing is animating, so there is no animation adjustment.
1440            return 0;
1441        }
1442    }
1443
1444    void scheduleAnimationIfDimming() {
1445        if (mDisplayContent == null) {
1446            return;
1447        }
1448        final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
1449        if (dimLayerUser != null && mDisplayContent.mDimLayerController.isDimming(
1450                dimLayerUser, mWinAnimator)) {
1451            // Force an animation pass just to update the mDimLayer layer.
1452            mService.scheduleAnimationLocked();
1453        }
1454    }
1455
1456    /**
1457     * Notifies this window that the corresponding task has just moved in the stack.
1458     * <p>
1459     * This is used to fix the following: If we moved in the stack, and if the last clip rect was
1460     * empty, meaning that our task was completely offscreen, we need to keep it invisible because
1461     * the actual app transition that updates the visibility is delayed by a few transactions.
1462     * Instead of messing around with the ordering and timing how transitions and transactions are
1463     * executed, we introduce this little hack which prevents this window of getting visible again
1464     * with the wrong bounds until the app transitions has started.
1465     * <p>
1466     * This method notifies the window about that we just moved in the stack so we can apply this
1467     * logic in {@link WindowStateAnimator#updateSurfaceWindowCrop}
1468     */
1469    void notifyMovedInStack() {
1470        mJustMovedInStack = true;
1471    }
1472
1473    /**
1474     * See {@link #notifyMovedInStack}.
1475     *
1476     * @return Whether we just got moved in the corresponding stack.
1477     */
1478    boolean hasJustMovedInStack() {
1479        return mJustMovedInStack;
1480    }
1481
1482    /**
1483     * Resets that we just moved in the corresponding stack. See {@link #notifyMovedInStack}.
1484     */
1485    void resetJustMovedInStack() {
1486        mJustMovedInStack = false;
1487    }
1488
1489    private final class DeadWindowEventReceiver extends InputEventReceiver {
1490        DeadWindowEventReceiver(InputChannel inputChannel) {
1491            super(inputChannel, mService.mH.getLooper());
1492        }
1493        @Override
1494        public void onInputEvent(InputEvent event) {
1495            finishInputEvent(event, true);
1496        }
1497    }
1498    /**
1499     *  Dummy event receiver for windows that died visible.
1500     */
1501    private DeadWindowEventReceiver mDeadWindowEventReceiver;
1502
1503    void openInputChannel(InputChannel outInputChannel) {
1504        if (mInputChannel != null) {
1505            throw new IllegalStateException("Window already has an input channel.");
1506        }
1507        String name = makeInputChannelName();
1508        InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
1509        mInputChannel = inputChannels[0];
1510        mClientChannel = inputChannels[1];
1511        mInputWindowHandle.inputChannel = inputChannels[0];
1512        if (outInputChannel != null) {
1513            mClientChannel.transferTo(outInputChannel);
1514            mClientChannel.dispose();
1515            mClientChannel = null;
1516        } else {
1517            // If the window died visible, we setup a dummy input channel, so that taps
1518            // can still detected by input monitor channel, and we can relaunch the app.
1519            // Create dummy event receiver that simply reports all events as handled.
1520            mDeadWindowEventReceiver = new DeadWindowEventReceiver(mClientChannel);
1521        }
1522        mService.mInputManager.registerInputChannel(mInputChannel, mInputWindowHandle);
1523    }
1524
1525    void disposeInputChannel() {
1526        if (mDeadWindowEventReceiver != null) {
1527            mDeadWindowEventReceiver.dispose();
1528            mDeadWindowEventReceiver = null;
1529        }
1530
1531        // unregister server channel first otherwise it complains about broken channel
1532        if (mInputChannel != null) {
1533            mService.mInputManager.unregisterInputChannel(mInputChannel);
1534            mInputChannel.dispose();
1535            mInputChannel = null;
1536        }
1537        if (mClientChannel != null) {
1538            mClientChannel.dispose();
1539            mClientChannel = null;
1540        }
1541        mInputWindowHandle.inputChannel = null;
1542    }
1543
1544    void applyDimLayerIfNeeded() {
1545        // When the app is terminated (eg. from Recents), the task might have already been
1546        // removed with the window pending removal. Don't apply dim in such cases, as there
1547        // will be no more updateDimLayer() calls, which leaves the dimlayer invalid.
1548        final AppWindowToken token = mAppToken;
1549        if (token != null && token.removed) {
1550            return;
1551        }
1552
1553        if (!mAnimatingExit && mAppDied) {
1554            // If app died visible, apply a dim over the window to indicate that it's inactive
1555            mDisplayContent.mDimLayerController.applyDimAbove(getDimLayerUser(), mWinAnimator);
1556        } else if ((mAttrs.flags & FLAG_DIM_BEHIND) != 0
1557                && mDisplayContent != null && !mAnimatingExit && isDisplayedLw()) {
1558            mDisplayContent.mDimLayerController.applyDimBehind(getDimLayerUser(), mWinAnimator);
1559        }
1560    }
1561
1562    DimLayer.DimLayerUser getDimLayerUser() {
1563        Task task = getTask();
1564        if (task != null) {
1565            return task;
1566        }
1567        return getStack();
1568    }
1569
1570    void maybeRemoveReplacedWindow() {
1571        if (mAppToken == null) {
1572            return;
1573        }
1574        for (int i = mAppToken.allAppWindows.size() - 1; i >= 0; i--) {
1575            final WindowState win = mAppToken.allAppWindows.get(i);
1576            if (win.mWillReplaceWindow && win.mReplacingWindow == this && hasDrawnLw()) {
1577                if (DEBUG_ADD_REMOVE) Slog.d(TAG, "Removing replaced window: " + win);
1578                win.mWillReplaceWindow = false;
1579                win.mAnimateReplacingWindow = false;
1580                win.mReplacingRemoveRequested = false;
1581                win.mReplacingWindow = null;
1582                mSkipEnterAnimationForSeamlessReplacement = false;
1583                if (win.mAnimatingExit) {
1584                    mService.removeWindowInnerLocked(win);
1585                }
1586            }
1587        }
1588    }
1589
1590    void setDisplayLayoutNeeded() {
1591        if (mDisplayContent != null) {
1592            mDisplayContent.layoutNeeded = true;
1593        }
1594    }
1595
1596    boolean inDockedWorkspace() {
1597        final Task task = getTask();
1598        return task != null && task.inDockedWorkspace();
1599    }
1600
1601    boolean isDockedInEffect() {
1602        final Task task = getTask();
1603        return task != null && task.isDockedInEffect();
1604    }
1605
1606    void applyScrollIfNeeded() {
1607        final Task task = getTask();
1608        if (task != null) {
1609            task.applyScrollToWindowIfNeeded(this);
1610        }
1611    }
1612
1613    int getTouchableRegion(Region region, int flags) {
1614        final boolean modal = (flags & (FLAG_NOT_TOUCH_MODAL | FLAG_NOT_FOCUSABLE)) == 0;
1615        if (modal && mAppToken != null) {
1616            // Limit the outer touch to the activity stack region.
1617            flags |= FLAG_NOT_TOUCH_MODAL;
1618            // If this is a modal window we need to dismiss it if it's not full screen and the
1619            // touch happens outside of the frame that displays the content. This means we
1620            // need to intercept touches outside of that window. The dim layer user
1621            // associated with the window (task or stack) will give us the good bounds, as
1622            // they would be used to display the dim layer.
1623            final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
1624            if (dimLayerUser != null) {
1625                dimLayerUser.getDimBounds(mTmpRect);
1626            } else {
1627                getVisibleBounds(mTmpRect);
1628            }
1629            if (inFreeformWorkspace()) {
1630                // For freeform windows we the touch region to include the whole surface for the
1631                // shadows.
1632                final DisplayMetrics displayMetrics = getDisplayContent().getDisplayMetrics();
1633                final int delta = WindowManagerService.dipToPixel(
1634                        RESIZE_HANDLE_WIDTH_IN_DP, displayMetrics);
1635                mTmpRect.inset(-delta, -delta);
1636            }
1637            region.set(mTmpRect);
1638            cropRegionToStackBoundsIfNeeded(region);
1639        } else {
1640            // Not modal or full screen modal
1641            getTouchableRegion(region);
1642        }
1643        return flags;
1644    }
1645
1646    void checkPolicyVisibilityChange() {
1647        if (mPolicyVisibility != mPolicyVisibilityAfterAnim) {
1648            if (DEBUG_VISIBILITY) {
1649                Slog.v(TAG, "Policy visibility changing after anim in " +
1650                        mWinAnimator + ": " + mPolicyVisibilityAfterAnim);
1651            }
1652            mPolicyVisibility = mPolicyVisibilityAfterAnim;
1653            setDisplayLayoutNeeded();
1654            if (!mPolicyVisibility) {
1655                if (mService.mCurrentFocus == this) {
1656                    if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1657                            "setAnimationLocked: setting mFocusMayChange true");
1658                    mService.mFocusMayChange = true;
1659                }
1660                // Window is no longer visible -- make sure if we were waiting
1661                // for it to be displayed before enabling the display, that
1662                // we allow the display to be enabled now.
1663                mService.enableScreenIfNeededLocked();
1664            }
1665        }
1666    }
1667
1668    void setRequestedSize(int requestedWidth, int requestedHeight) {
1669        if ((mRequestedWidth != requestedWidth || mRequestedHeight != requestedHeight)) {
1670            mLayoutNeeded = true;
1671            mRequestedWidth = requestedWidth;
1672            mRequestedHeight = requestedHeight;
1673        }
1674    }
1675
1676    void prepareWindowToDisplayDuringRelayout(Configuration outConfig) {
1677        if ((mAttrs.softInputMode & SOFT_INPUT_MASK_ADJUST)
1678                == SOFT_INPUT_ADJUST_RESIZE) {
1679            mLayoutNeeded = true;
1680        }
1681        if (isDrawnLw() && mService.okToDisplay()) {
1682            mWinAnimator.applyEnterAnimationLocked();
1683        }
1684        if ((mAttrs.flags & FLAG_TURN_SCREEN_ON) != 0) {
1685            if (DEBUG_VISIBILITY) Slog.v(TAG, "Relayout window turning screen on: " + this);
1686            mTurnOnScreen = true;
1687        }
1688        if (isConfigChanged()) {
1689            final Configuration newConfig = updateConfiguration();
1690            if (DEBUG_CONFIGURATION) Slog.i(TAG, "Window " + this + " visible with new config: "
1691                    + newConfig);
1692            outConfig.setTo(newConfig);
1693        }
1694    }
1695
1696    void adjustStartingWindowFlags() {
1697        if (mAttrs.type == TYPE_BASE_APPLICATION && mAppToken != null
1698                && mAppToken.startingWindow != null) {
1699            // Special handling of starting window over the base
1700            // window of the app: propagate lock screen flags to it,
1701            // to provide the correct semantics while starting.
1702            final int mask = FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD
1703                    | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
1704            WindowManager.LayoutParams sa = mAppToken.startingWindow.mAttrs;
1705            sa.flags = (sa.flags & ~mask) | (mAttrs.flags & mask);
1706        }
1707    }
1708
1709    void setWindowScale(int requestedWidth, int requestedHeight) {
1710        final boolean scaledWindow = (mAttrs.flags & FLAG_SCALED) != 0;
1711
1712        if (scaledWindow) {
1713            // requested{Width|Height} Surface's physical size
1714            // attrs.{width|height} Size on screen
1715            // TODO: We don't check if attrs != null here. Is it implicitly checked?
1716            mHScale = (mAttrs.width  != requestedWidth)  ?
1717                    (mAttrs.width  / (float)requestedWidth) : 1.0f;
1718            mVScale = (mAttrs.height != requestedHeight) ?
1719                    (mAttrs.height / (float)requestedHeight) : 1.0f;
1720        } else {
1721            mHScale = mVScale = 1;
1722        }
1723    }
1724
1725    private class DeathRecipient implements IBinder.DeathRecipient {
1726        @Override
1727        public void binderDied() {
1728            try {
1729                synchronized(mService.mWindowMap) {
1730                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
1731                    Slog.i(TAG, "WIN DEATH: " + win);
1732                    if (win != null) {
1733                        if (win.mAppToken != null && !win.mAppToken.clientHidden) {
1734                            win.mAppToken.appDied = true;
1735                        }
1736                        mService.removeWindowLocked(win);
1737                        if (win.mAttrs.type == TYPE_DOCK_DIVIDER) {
1738                            // The owner of the docked divider died :( We reset the docked stack,
1739                            // just in case they have the divider at an unstable position. Better
1740                            // also reset drag resizing state, because the owner can't do it
1741                            // anymore.
1742                            final TaskStack stack = mService.mStackIdToStack.get(DOCKED_STACK_ID);
1743                            if (stack != null) {
1744                                stack.resetDockedStackToMiddle();
1745                            }
1746                            mService.setDockedStackResizing(false);
1747                        }
1748                    } else if (mHasSurface) {
1749                        Slog.e(TAG, "!!! LEAK !!! Window removed but surface still valid.");
1750                        mService.removeWindowLocked(WindowState.this);
1751                    }
1752                }
1753            } catch (IllegalArgumentException ex) {
1754                // This will happen if the window has already been
1755                // removed.
1756            }
1757        }
1758    }
1759
1760    /**
1761     * Returns true if this window is visible and belongs to a dead app and shouldn't be removed,
1762     * because we want to preserve its location on screen to be re-activated later when the user
1763     * interacts with it.
1764     */
1765    boolean shouldKeepVisibleDeadAppWindow() {
1766        if (!isWinVisibleLw() || mAppToken == null || !mAppToken.appDied) {
1767            // Not a visible app window or the app isn't dead.
1768            return false;
1769        }
1770
1771        if (mAttrs.type == TYPE_APPLICATION_STARTING) {
1772            // We don't keep starting windows since they were added by the window manager before
1773            // the app even launched.
1774            return false;
1775        }
1776
1777        final TaskStack stack = getStack();
1778        return stack != null && StackId.keepVisibleDeadAppWindowOnScreen(stack.mStackId);
1779    }
1780
1781    /** @return true if this window desires key events. */
1782    boolean canReceiveKeys() {
1783        return isVisibleOrAdding()
1784                && (mViewVisibility == View.VISIBLE)
1785                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0)
1786                && (mAppToken == null || mAppToken.windowsAreFocusable());
1787    }
1788
1789    @Override
1790    public boolean hasDrawnLw() {
1791        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
1792    }
1793
1794    @Override
1795    public boolean showLw(boolean doAnimation) {
1796        return showLw(doAnimation, true);
1797    }
1798
1799    boolean showLw(boolean doAnimation, boolean requestAnim) {
1800        if (isHiddenFromUserLocked()) {
1801            return false;
1802        }
1803        if (!mAppOpVisibility) {
1804            // Being hidden due to app op request.
1805            return false;
1806        }
1807        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
1808            // Already showing.
1809            return false;
1810        }
1811        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
1812        if (doAnimation) {
1813            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
1814                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
1815            if (!mService.okToDisplay()) {
1816                doAnimation = false;
1817            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
1818                // Check for the case where we are currently visible and
1819                // not animating; we do not want to do animation at such a
1820                // point to become visible when we already are.
1821                doAnimation = false;
1822            }
1823        }
1824        mPolicyVisibility = true;
1825        mPolicyVisibilityAfterAnim = true;
1826        if (doAnimation) {
1827            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
1828        }
1829        if (requestAnim) {
1830            mService.scheduleAnimationLocked();
1831        }
1832        return true;
1833    }
1834
1835    @Override
1836    public boolean hideLw(boolean doAnimation) {
1837        return hideLw(doAnimation, true);
1838    }
1839
1840    boolean hideLw(boolean doAnimation, boolean requestAnim) {
1841        if (doAnimation) {
1842            if (!mService.okToDisplay()) {
1843                doAnimation = false;
1844            }
1845        }
1846        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
1847                : mPolicyVisibility;
1848        if (!current) {
1849            // Already hiding.
1850            return false;
1851        }
1852        if (doAnimation) {
1853            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
1854            if (mWinAnimator.mAnimation == null) {
1855                doAnimation = false;
1856            }
1857        }
1858        if (doAnimation) {
1859            mPolicyVisibilityAfterAnim = false;
1860        } else {
1861            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
1862            mPolicyVisibilityAfterAnim = false;
1863            mPolicyVisibility = false;
1864            // Window is no longer visible -- make sure if we were waiting
1865            // for it to be displayed before enabling the display, that
1866            // we allow the display to be enabled now.
1867            mService.enableScreenIfNeededLocked();
1868            if (mService.mCurrentFocus == this) {
1869                if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1870                        "WindowState.hideLw: setting mFocusMayChange true");
1871                mService.mFocusMayChange = true;
1872            }
1873        }
1874        if (requestAnim) {
1875            mService.scheduleAnimationLocked();
1876        }
1877        return true;
1878    }
1879
1880    public void setAppOpVisibilityLw(boolean state) {
1881        if (mAppOpVisibility != state) {
1882            mAppOpVisibility = state;
1883            if (state) {
1884                // If the policy visibility had last been to hide, then this
1885                // will incorrectly show at this point since we lost that
1886                // information.  Not a big deal -- for the windows that have app
1887                // ops modifies they should only be hidden by policy due to the
1888                // lock screen, and the user won't be changing this if locked.
1889                // Plus it will quickly be fixed the next time we do a layout.
1890                showLw(true, true);
1891            } else {
1892                hideLw(true, true);
1893            }
1894        }
1895    }
1896
1897    public void pokeDrawLockLw(long timeout) {
1898        if (isVisibleOrAdding()) {
1899            if (mDrawLock == null) {
1900                // We want the tag name to be somewhat stable so that it is easier to correlate
1901                // in wake lock statistics.  So in particular, we don't want to include the
1902                // window's hash code as in toString().
1903                final CharSequence tag = getWindowTag();
1904                mDrawLock = mService.mPowerManager.newWakeLock(
1905                        PowerManager.DRAW_WAKE_LOCK, "Window:" + tag);
1906                mDrawLock.setReferenceCounted(false);
1907                mDrawLock.setWorkSource(new WorkSource(mOwnerUid, mAttrs.packageName));
1908            }
1909            // Each call to acquire resets the timeout.
1910            if (DEBUG_POWER) {
1911                Slog.d(TAG, "pokeDrawLock: poking draw lock on behalf of visible window owned by "
1912                        + mAttrs.packageName);
1913            }
1914            mDrawLock.acquire(timeout);
1915        } else if (DEBUG_POWER) {
1916            Slog.d(TAG, "pokeDrawLock: suppressed draw lock request for invisible window "
1917                    + "owned by " + mAttrs.packageName);
1918        }
1919    }
1920
1921    @Override
1922    public boolean isAlive() {
1923        return mClient.asBinder().isBinderAlive();
1924    }
1925
1926    boolean isClosing() {
1927        return mAnimatingExit || (mService.mClosingApps.contains(mAppToken));
1928    }
1929
1930    boolean isAnimatingWithSavedSurface() {
1931        return mAppToken != null && mAppToken.mAnimatingWithSavedSurface;
1932    }
1933
1934    private boolean shouldSaveSurface() {
1935        if (mWinAnimator.mSurfaceController == null) {
1936            // Don't bother if the surface controller is gone for any reason.
1937            return false;
1938        }
1939
1940        if ((mAttrs.flags & FLAG_SECURE) != 0) {
1941            // We don't save secure surfaces since their content shouldn't be shown while the app
1942            // isn't on screen and content might leak through during the transition animation with
1943            // saved surface.
1944            return false;
1945        }
1946
1947        if (ActivityManager.isLowRamDeviceStatic()) {
1948            // Don't save surfaces on Svelte devices.
1949            return false;
1950        }
1951
1952        Task task = getTask();
1953        if (task == null || task.inHomeStack()) {
1954            // Don't save surfaces for home stack apps. These usually resume and draw
1955            // first frame very fast. Saving surfaces are mostly a waste of memory.
1956            return false;
1957        }
1958
1959        final AppWindowToken taskTop = task.getTopVisibleAppToken();
1960        if (taskTop != null && taskTop != mAppToken) {
1961            // Don't save if the window is not the topmost window.
1962            return false;
1963        }
1964
1965        if (mResizedWhileGone) {
1966            // Somebody resized our window while we were gone for layout, which means that the
1967            // client got an old size, so we have an outdated surface here.
1968            return false;
1969        }
1970
1971        if (DEBUG_DISABLE_SAVING_SURFACES) {
1972            return false;
1973        }
1974
1975        return mAppToken.shouldSaveSurface();
1976    }
1977
1978    void destroyOrSaveSurface() {
1979        mSurfaceSaved = shouldSaveSurface();
1980        if (mSurfaceSaved) {
1981            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
1982                Slog.v(TAG, "Saving surface: " + this);
1983            }
1984
1985            mWinAnimator.hide("saved surface");
1986            mWinAnimator.mDrawState = WindowStateAnimator.NO_SURFACE;
1987            setHasSurface(false);
1988            // The client should have disconnected at this point, but if it doesn't,
1989            // we need to make sure it's disconnected. Otherwise when we reuse the surface
1990            // the client can't reconnect to the buffer queue, and rendering will fail.
1991            if (mWinAnimator.mSurfaceController != null) {
1992                mWinAnimator.mSurfaceController.disconnectInTransaction();
1993            }
1994        } else {
1995            mWinAnimator.destroySurfaceLocked();
1996        }
1997    }
1998
1999    public void destroySavedSurface() {
2000        if (mSurfaceSaved) {
2001            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
2002                Slog.v(TAG, "Destroying saved surface: " + this);
2003            }
2004            mWinAnimator.destroySurfaceLocked();
2005        }
2006    }
2007
2008    public void restoreSavedSurface() {
2009        if (!mSurfaceSaved) {
2010            return;
2011        }
2012        mSurfaceSaved = false;
2013        if (mWinAnimator.mSurfaceController != null) {
2014            setHasSurface(true);
2015            mWinAnimator.mDrawState = WindowStateAnimator.READY_TO_SHOW;
2016
2017            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
2018                Slog.v(TAG, "Restoring saved surface: " + this);
2019            }
2020        } else {
2021            // mSurfaceController shouldn't be null if mSurfaceSaved was still true at
2022            // this point. Even if we destroyed the saved surface because of rotation
2023            // or resize, mSurfaceSaved flag should have been cleared. So this is a wtf.
2024            Slog.wtf(TAG, "Failed to restore saved surface: surface gone! " + this);
2025        }
2026    }
2027
2028    public boolean hasSavedSurface() {
2029        return mSurfaceSaved;
2030    }
2031
2032    @Override
2033    public boolean isDefaultDisplay() {
2034        final DisplayContent displayContent = getDisplayContent();
2035        if (displayContent == null) {
2036            // Only a window that was on a non-default display can be detached from it.
2037            return false;
2038        }
2039        return displayContent.isDefaultDisplay;
2040    }
2041
2042    @Override
2043    public boolean isDimming() {
2044        final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
2045        return dimLayerUser != null && mDisplayContent != null &&
2046                mDisplayContent.mDimLayerController.isDimming(dimLayerUser, mWinAnimator);
2047    }
2048
2049    public void setShowToOwnerOnlyLocked(boolean showToOwnerOnly) {
2050        mShowToOwnerOnly = showToOwnerOnly;
2051    }
2052
2053    boolean isHiddenFromUserLocked() {
2054        // Attached windows are evaluated based on the window that they are attached to.
2055        WindowState win = this;
2056        while (win.isChildWindow()) {
2057            win = win.mAttachedWindow;
2058        }
2059        if (win.mAttrs.type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
2060                && win.mAppToken != null && win.mAppToken.showForAllUsers) {
2061            // Save some cycles by not calling getDisplayInfo unless it is an application
2062            // window intended for all users.
2063            final DisplayContent displayContent = win.getDisplayContent();
2064            if (displayContent == null) {
2065                return true;
2066            }
2067            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
2068            if (win.mFrame.left <= 0 && win.mFrame.top <= 0
2069                    && win.mFrame.right >= displayInfo.appWidth
2070                    && win.mFrame.bottom >= displayInfo.appHeight) {
2071                // Is a fullscreen window, like the clock alarm. Show to everyone.
2072                return false;
2073            }
2074        }
2075
2076        return win.mShowToOwnerOnly
2077                && !mService.isCurrentProfileLocked(UserHandle.getUserId(win.mOwnerUid));
2078    }
2079
2080    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
2081        outRegion.set(
2082                frame.left + inset.left, frame.top + inset.top,
2083                frame.right - inset.right, frame.bottom - inset.bottom);
2084    }
2085
2086    void getTouchableRegion(Region outRegion) {
2087        final Rect frame = mFrame;
2088        switch (mTouchableInsets) {
2089            default:
2090            case TOUCHABLE_INSETS_FRAME:
2091                outRegion.set(frame);
2092                break;
2093            case TOUCHABLE_INSETS_CONTENT:
2094                applyInsets(outRegion, frame, mGivenContentInsets);
2095                break;
2096            case TOUCHABLE_INSETS_VISIBLE:
2097                applyInsets(outRegion, frame, mGivenVisibleInsets);
2098                break;
2099            case TOUCHABLE_INSETS_REGION: {
2100                final Region givenTouchableRegion = mGivenTouchableRegion;
2101                outRegion.set(givenTouchableRegion);
2102                outRegion.translate(frame.left, frame.top);
2103                break;
2104            }
2105        }
2106        cropRegionToStackBoundsIfNeeded(outRegion);
2107    }
2108
2109    void cropRegionToStackBoundsIfNeeded(Region region) {
2110        final Task task = getTask();
2111        if (task == null || !task.cropWindowsToStackBounds()) {
2112            return;
2113        }
2114
2115        final TaskStack stack = task.mStack;
2116        if (stack == null) {
2117            return;
2118        }
2119
2120        stack.getDimBounds(mTmpRect);
2121        region.op(mTmpRect, Region.Op.INTERSECT);
2122    }
2123
2124    WindowList getWindowList() {
2125        final DisplayContent displayContent = getDisplayContent();
2126        return displayContent == null ? null : displayContent.getWindowList();
2127    }
2128
2129    /**
2130     * Report a focus change.  Must be called with no locks held, and consistently
2131     * from the same serialized thread (such as dispatched from a handler).
2132     */
2133    public void reportFocusChangedSerialized(boolean focused, boolean inTouchMode) {
2134        try {
2135            mClient.windowFocusChanged(focused, inTouchMode);
2136        } catch (RemoteException e) {
2137        }
2138        if (mFocusCallbacks != null) {
2139            final int N = mFocusCallbacks.beginBroadcast();
2140            for (int i=0; i<N; i++) {
2141                IWindowFocusObserver obs = mFocusCallbacks.getBroadcastItem(i);
2142                try {
2143                    if (focused) {
2144                        obs.focusGained(mWindowId.asBinder());
2145                    } else {
2146                        obs.focusLost(mWindowId.asBinder());
2147                    }
2148                } catch (RemoteException e) {
2149                }
2150            }
2151            mFocusCallbacks.finishBroadcast();
2152        }
2153    }
2154
2155    /**
2156     * Update our current configurations, based on task configuration.
2157     *
2158     * @return A configuration suitable for sending to the client.
2159     */
2160    private Configuration updateConfiguration() {
2161        final Task task = getTask();
2162        final Configuration overrideConfig =
2163            (task != null) ? task.mOverrideConfig : Configuration.EMPTY;
2164        final boolean configChanged = isConfigChanged();
2165        if ((DEBUG_RESIZE || DEBUG_ORIENTATION || DEBUG_CONFIGURATION) && configChanged) {
2166            Slog.i(TAG, "Sending new config to window " + this + ": " +
2167                    " / config=" + mService.mCurConfiguration + " overrideConfig=" + overrideConfig);
2168        }
2169        setConfiguration(mService.mCurConfiguration, overrideConfig);
2170        return mMergedConfiguration;
2171    }
2172
2173    void reportResized() {
2174        Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "wm.reportResized_" + getWindowTag());
2175        try {
2176            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
2177                    + ": " + mCompatFrame);
2178            final Configuration newConfig = isConfigChanged() ? updateConfiguration() : null;
2179            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING)
2180                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
2181
2182            final Rect frame = mFrame;
2183            final Rect overscanInsets = mLastOverscanInsets;
2184            final Rect contentInsets = mLastContentInsets;
2185            final Rect visibleInsets = mLastVisibleInsets;
2186            final Rect stableInsets = mLastStableInsets;
2187            final Rect outsets = mLastOutsets;
2188            final boolean reportDraw = mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING;
2189            if (mAttrs.type != WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
2190                    && mClient instanceof IWindow.Stub) {
2191                // To prevent deadlock simulate one-way call if win.mClient is a local object.
2192                mService.mH.post(new Runnable() {
2193                    @Override
2194                    public void run() {
2195                        try {
2196                            dispatchResized(frame, overscanInsets, contentInsets, visibleInsets,
2197                                    stableInsets, outsets, reportDraw, newConfig);
2198                        } catch (RemoteException e) {
2199                            // Not a remote call, RemoteException won't be raised.
2200                        }
2201                    }
2202                });
2203            } else {
2204                dispatchResized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets,
2205                        outsets, reportDraw, newConfig);
2206            }
2207
2208            //TODO (multidisplay): Accessibility supported only for the default display.
2209            if (mService.mAccessibilityController != null
2210                    && getDisplayId() == Display.DEFAULT_DISPLAY) {
2211                mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
2212            }
2213
2214            mOverscanInsetsChanged = false;
2215            mContentInsetsChanged = false;
2216            mVisibleInsetsChanged = false;
2217            mStableInsetsChanged = false;
2218            mOutsetsChanged = false;
2219            mWinAnimator.mSurfaceResized = false;
2220        } catch (RemoteException e) {
2221            mOrientationChanging = false;
2222            mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
2223                    - mService.mDisplayFreezeTime);
2224            // We are assuming the hosting process is dead or in a zombie state.
2225            Slog.w(TAG, "Failed to report 'resized' to the client of " + this
2226                    + ", removing this window.");
2227            mService.mPendingRemove.add(this);
2228            mService.mWindowPlacerLocked.requestTraversal();
2229        }
2230        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
2231    }
2232
2233    Rect getBackdropFrame(Rect frame) {
2234        // When the task is docked, we send fullscreen sized backDropFrame as soon as resizing
2235        // start even if we haven't received the relayout window, so that the client requests
2236        // the relayout sooner. When dragging stops, backDropFrame needs to stay fullscreen
2237        // until the window to small size, otherwise the multithread renderer will shift last
2238        // one or more frame to wrong offset. So here we send fullscreen backdrop if either
2239        // isDragResizing() or isDragResizeChanged() is true.
2240        boolean resizing = isDragResizing() || isDragResizeChanged();
2241        if (StackId.useWindowFrameForBackdrop(getStackId()) || !resizing) {
2242            return frame;
2243        }
2244        DisplayInfo displayInfo = getDisplayInfo();
2245        mTmpRect.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight);
2246        return mTmpRect;
2247    }
2248
2249    @Override
2250    public int getStackId() {
2251        final TaskStack stack = getStack();
2252        if (stack == null) {
2253            return INVALID_STACK_ID;
2254        }
2255        return stack.mStackId;
2256    }
2257
2258    private void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
2259            Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
2260            Configuration newConfig) throws RemoteException {
2261        mClient.resized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets, outsets,
2262                reportDraw, newConfig, getBackdropFrame(frame),
2263                isDragResizeChanged() /* forceRelayout */, mPolicy.isNavBarForcedShownLw(this));
2264        mDragResizingChangeReported = true;
2265    }
2266
2267    public void registerFocusObserver(IWindowFocusObserver observer) {
2268        synchronized(mService.mWindowMap) {
2269            if (mFocusCallbacks == null) {
2270                mFocusCallbacks = new RemoteCallbackList<IWindowFocusObserver>();
2271            }
2272            mFocusCallbacks.register(observer);
2273        }
2274    }
2275
2276    public void unregisterFocusObserver(IWindowFocusObserver observer) {
2277        synchronized(mService.mWindowMap) {
2278            if (mFocusCallbacks != null) {
2279                mFocusCallbacks.unregister(observer);
2280            }
2281        }
2282    }
2283
2284    public boolean isFocused() {
2285        synchronized(mService.mWindowMap) {
2286            return mService.mCurrentFocus == this;
2287        }
2288    }
2289
2290    boolean inFreeformWorkspace() {
2291        final Task task = getTask();
2292        return task != null && task.inFreeformWorkspace();
2293    }
2294
2295    @Override
2296    public boolean isInMultiWindowMode() {
2297        final Task task = getTask();
2298        return task != null && !task.isFullscreen();
2299    }
2300
2301    boolean isDragResizeChanged() {
2302        return mDragResizing != computeDragResizing();
2303    }
2304
2305    /**
2306     * @return Whether we reported a drag resize change to the application or not already.
2307     */
2308    boolean isDragResizingChangeReported() {
2309        return mDragResizingChangeReported;
2310    }
2311
2312    /**
2313     * Resets the state whether we reported a drag resize change to the app.
2314     */
2315    void resetDragResizingChangeReported() {
2316        mDragResizingChangeReported = false;
2317    }
2318
2319    int getResizeMode() {
2320        return mResizeMode;
2321    }
2322
2323    boolean computeDragResizing() {
2324        final Task task = getTask();
2325        if (task == null) {
2326            return false;
2327        }
2328        if (mAttrs.width != MATCH_PARENT || mAttrs.height != MATCH_PARENT) {
2329
2330            // Floating windows never enter drag resize mode.
2331            return false;
2332        }
2333        if (task.isDragResizing()) {
2334            return true;
2335        }
2336
2337        // If the bounds are currently frozen, it means that the layout size that the app sees
2338        // and the bounds we clip this window to might be different. In order to avoid holes, we
2339        // simulate that we are still resizing so the app fills the hole with the resizing
2340        // background.
2341        return (mDisplayContent.mDividerControllerLocked.isResizing()
2342                        || mAppToken != null && !mAppToken.mFrozenBounds.isEmpty()) &&
2343                !task.inFreeformWorkspace() && !isGoneForLayoutLw();
2344
2345    }
2346
2347    void setDragResizing() {
2348        final boolean resizing = computeDragResizing();
2349        if (resizing == mDragResizing) {
2350            return;
2351        }
2352        mDragResizing = resizing;
2353        final Task task = getTask();
2354        if (task != null && task.isDragResizing()) {
2355            mResizeMode = task.getDragResizeMode();
2356        } else {
2357            mResizeMode = mDragResizing && mDisplayContent.mDividerControllerLocked.isResizing()
2358                    ? DRAG_RESIZE_MODE_DOCKED_DIVIDER
2359                    : DRAG_RESIZE_MODE_FREEFORM;
2360        }
2361    }
2362
2363    boolean isDragResizing() {
2364        return mDragResizing;
2365    }
2366
2367    boolean isDockedResizing() {
2368        return mDragResizing && getResizeMode() == DRAG_RESIZE_MODE_DOCKED_DIVIDER;
2369    }
2370
2371    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
2372        final TaskStack stack = getStack();
2373        pw.print(prefix); pw.print("mDisplayId="); pw.print(getDisplayId());
2374                if (stack != null) {
2375                    pw.print(" stackId="); pw.print(stack.mStackId);
2376                }
2377                pw.print(" mSession="); pw.print(mSession);
2378                pw.print(" mClient="); pw.println(mClient.asBinder());
2379        pw.print(prefix); pw.print("mOwnerUid="); pw.print(mOwnerUid);
2380                pw.print(" mShowToOwnerOnly="); pw.print(mShowToOwnerOnly);
2381                pw.print(" package="); pw.print(mAttrs.packageName);
2382                pw.print(" appop="); pw.println(AppOpsManager.opToName(mAppOp));
2383        pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
2384        pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
2385                pw.print(" h="); pw.print(mRequestedHeight);
2386                pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
2387        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
2388            pw.print(prefix); pw.print("LastRequested w="); pw.print(mLastRequestedWidth);
2389                    pw.print(" h="); pw.println(mLastRequestedHeight);
2390        }
2391        if (isChildWindow() || mLayoutAttached) {
2392            pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
2393                    pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
2394        }
2395        if (mIsImWindow || mIsWallpaper || mIsFloatingLayer) {
2396            pw.print(prefix); pw.print("mIsImWindow="); pw.print(mIsImWindow);
2397                    pw.print(" mIsWallpaper="); pw.print(mIsWallpaper);
2398                    pw.print(" mIsFloatingLayer="); pw.print(mIsFloatingLayer);
2399                    pw.print(" mWallpaperVisible="); pw.println(mWallpaperVisible);
2400        }
2401        if (dumpAll) {
2402            pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
2403                    pw.print(" mSubLayer="); pw.print(mSubLayer);
2404                    pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
2405                    pw.print((mTargetAppToken != null ?
2406                            mTargetAppToken.mAppAnimator.animLayerAdjustment
2407                          : (mAppToken != null ? mAppToken.mAppAnimator.animLayerAdjustment : 0)));
2408                    pw.print("="); pw.print(mWinAnimator.mAnimLayer);
2409                    pw.print(" mLastLayer="); pw.println(mWinAnimator.mLastLayer);
2410        }
2411        if (dumpAll) {
2412            pw.print(prefix); pw.print("mToken="); pw.println(mToken);
2413            pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
2414            if (mAppToken != null) {
2415                pw.print(prefix); pw.print("mAppToken="); pw.print(mAppToken);
2416                pw.print(" isAnimatingWithSavedSurface()=");
2417                pw.print(isAnimatingWithSavedSurface());
2418                pw.print(" mAppDied=");pw.println(mAppDied);
2419            }
2420            if (mTargetAppToken != null) {
2421                pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
2422            }
2423            pw.print(prefix); pw.print("mViewVisibility=0x");
2424            pw.print(Integer.toHexString(mViewVisibility));
2425            pw.print(" mHaveFrame="); pw.print(mHaveFrame);
2426            pw.print(" mObscured="); pw.println(mObscured);
2427            pw.print(prefix); pw.print("mSeq="); pw.print(mSeq);
2428            pw.print(" mSystemUiVisibility=0x");
2429            pw.println(Integer.toHexString(mSystemUiVisibility));
2430        }
2431        if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || !mAppOpVisibility
2432                || mAttachedHidden) {
2433            pw.print(prefix); pw.print("mPolicyVisibility=");
2434                    pw.print(mPolicyVisibility);
2435                    pw.print(" mPolicyVisibilityAfterAnim=");
2436                    pw.print(mPolicyVisibilityAfterAnim);
2437                    pw.print(" mAppOpVisibility=");
2438                    pw.print(mAppOpVisibility);
2439                    pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
2440        }
2441        if (!mRelayoutCalled || mLayoutNeeded) {
2442            pw.print(prefix); pw.print("mRelayoutCalled="); pw.print(mRelayoutCalled);
2443                    pw.print(" mLayoutNeeded="); pw.println(mLayoutNeeded);
2444        }
2445        if (mXOffset != 0 || mYOffset != 0) {
2446            pw.print(prefix); pw.print("Offsets x="); pw.print(mXOffset);
2447                    pw.print(" y="); pw.println(mYOffset);
2448        }
2449        if (dumpAll) {
2450            pw.print(prefix); pw.print("mGivenContentInsets=");
2451                    mGivenContentInsets.printShortString(pw);
2452                    pw.print(" mGivenVisibleInsets=");
2453                    mGivenVisibleInsets.printShortString(pw);
2454                    pw.println();
2455            if (mTouchableInsets != 0 || mGivenInsetsPending) {
2456                pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
2457                        pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
2458                Region region = new Region();
2459                getTouchableRegion(region);
2460                pw.print(prefix); pw.print("touchable region="); pw.println(region);
2461            }
2462            pw.print(prefix); pw.print("mConfiguration="); pw.println(mConfiguration);
2463            if (mOverrideConfig != Configuration.EMPTY) {
2464                pw.print(prefix); pw.print("mOverrideConfig="); pw.println(mOverrideConfig);
2465            }
2466        }
2467        pw.print(prefix); pw.print("mHasSurface="); pw.print(mHasSurface);
2468                pw.print(" mShownPosition="); mShownPosition.printShortString(pw);
2469                pw.print(" isReadyForDisplay()="); pw.print(isReadyForDisplay());
2470                pw.print(" hasSavedSurface()="); pw.print(hasSavedSurface());
2471                pw.print(" mWindowRemovalAllowed="); pw.println(mWindowRemovalAllowed);
2472        if (dumpAll) {
2473            pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
2474                    pw.print(" last="); mLastFrame.printShortString(pw);
2475                    pw.println();
2476        }
2477        if (mEnforceSizeCompat) {
2478            pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
2479                    pw.println();
2480        }
2481        if (dumpAll) {
2482            pw.print(prefix); pw.print("Frames: containing=");
2483                    mContainingFrame.printShortString(pw);
2484                    pw.print(" parent="); mParentFrame.printShortString(pw);
2485                    pw.println();
2486            pw.print(prefix); pw.print("    display="); mDisplayFrame.printShortString(pw);
2487                    pw.print(" overscan="); mOverscanFrame.printShortString(pw);
2488                    pw.println();
2489            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
2490                    pw.print(" visible="); mVisibleFrame.printShortString(pw);
2491                    pw.println();
2492            pw.print(prefix); pw.print("    decor="); mDecorFrame.printShortString(pw);
2493                    pw.println();
2494            pw.print(prefix); pw.print("    outset="); mOutsetFrame.printShortString(pw);
2495                    pw.println();
2496            pw.print(prefix); pw.print("Cur insets: overscan=");
2497                    mOverscanInsets.printShortString(pw);
2498                    pw.print(" content="); mContentInsets.printShortString(pw);
2499                    pw.print(" visible="); mVisibleInsets.printShortString(pw);
2500                    pw.print(" stable="); mStableInsets.printShortString(pw);
2501                    pw.print(" outsets="); mOutsets.printShortString(pw);
2502                    pw.println();
2503            pw.print(prefix); pw.print("Lst insets: overscan=");
2504                    mLastOverscanInsets.printShortString(pw);
2505                    pw.print(" content="); mLastContentInsets.printShortString(pw);
2506                    pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
2507                    pw.print(" stable="); mLastStableInsets.printShortString(pw);
2508                    pw.print(" physical="); mLastOutsets.printShortString(pw);
2509                    pw.print(" outset="); mLastOutsets.printShortString(pw);
2510                    pw.println();
2511        }
2512        pw.print(prefix); pw.print(mWinAnimator); pw.println(":");
2513        mWinAnimator.dump(pw, prefix + "  ", dumpAll);
2514        if (mAnimatingExit || mRemoveOnExit || mDestroying || mRemoved) {
2515            pw.print(prefix); pw.print("mAnimatingExit="); pw.print(mAnimatingExit);
2516                    pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
2517                    pw.print(" mDestroying="); pw.print(mDestroying);
2518                    pw.print(" mRemoved="); pw.println(mRemoved);
2519        }
2520        if (mOrientationChanging || mAppFreezing || mTurnOnScreen) {
2521            pw.print(prefix); pw.print("mOrientationChanging=");
2522                    pw.print(mOrientationChanging);
2523                    pw.print(" mAppFreezing="); pw.print(mAppFreezing);
2524                    pw.print(" mTurnOnScreen="); pw.println(mTurnOnScreen);
2525        }
2526        if (mLastFreezeDuration != 0) {
2527            pw.print(prefix); pw.print("mLastFreezeDuration=");
2528                    TimeUtils.formatDuration(mLastFreezeDuration, pw); pw.println();
2529        }
2530        if (mHScale != 1 || mVScale != 1) {
2531            pw.print(prefix); pw.print("mHScale="); pw.print(mHScale);
2532                    pw.print(" mVScale="); pw.println(mVScale);
2533        }
2534        if (mWallpaperX != -1 || mWallpaperY != -1) {
2535            pw.print(prefix); pw.print("mWallpaperX="); pw.print(mWallpaperX);
2536                    pw.print(" mWallpaperY="); pw.println(mWallpaperY);
2537        }
2538        if (mWallpaperXStep != -1 || mWallpaperYStep != -1) {
2539            pw.print(prefix); pw.print("mWallpaperXStep="); pw.print(mWallpaperXStep);
2540                    pw.print(" mWallpaperYStep="); pw.println(mWallpaperYStep);
2541        }
2542        if (mWallpaperDisplayOffsetX != Integer.MIN_VALUE
2543                || mWallpaperDisplayOffsetY != Integer.MIN_VALUE) {
2544            pw.print(prefix); pw.print("mWallpaperDisplayOffsetX=");
2545                    pw.print(mWallpaperDisplayOffsetX);
2546                    pw.print(" mWallpaperDisplayOffsetY=");
2547                    pw.println(mWallpaperDisplayOffsetY);
2548        }
2549        if (mDrawLock != null) {
2550            pw.print(prefix); pw.println("mDrawLock=" + mDrawLock);
2551        }
2552        if (isDragResizing()) {
2553            pw.print(prefix); pw.println("isDragResizing=" + isDragResizing());
2554        }
2555        if (computeDragResizing()) {
2556            pw.print(prefix); pw.println("computeDragResizing=" + computeDragResizing());
2557        }
2558    }
2559
2560    String makeInputChannelName() {
2561        return Integer.toHexString(System.identityHashCode(this))
2562            + " " + getWindowTag();
2563    }
2564
2565    CharSequence getWindowTag() {
2566        CharSequence tag = mAttrs.getTitle();
2567        if (tag == null || tag.length() <= 0) {
2568            tag = mAttrs.packageName;
2569        }
2570        return tag;
2571    }
2572
2573    @Override
2574    public String toString() {
2575        final CharSequence title = getWindowTag();
2576        if (mStringNameCache == null || mLastTitle != title || mWasExiting != mAnimatingExit) {
2577            mLastTitle = title;
2578            mWasExiting = mAnimatingExit;
2579            mStringNameCache = "Window{" + Integer.toHexString(System.identityHashCode(this))
2580                    + " u" + UserHandle.getUserId(mSession.mUid)
2581                    + " " + mLastTitle + (mAnimatingExit ? " EXITING}" : "}");
2582        }
2583        return mStringNameCache;
2584    }
2585
2586    void transformFromScreenToSurfaceSpace(Rect rect) {
2587         if (mHScale >= 0) {
2588            rect.left = (int) (rect.left / mHScale);
2589            rect.right = (int) (rect.right / mHScale);
2590        }
2591        if (mVScale >= 0) {
2592            rect.top = (int) (rect.top / mVScale);
2593            rect.bottom = (int) (rect.bottom / mVScale);
2594        }
2595    }
2596
2597    void applyGravityAndUpdateFrame(Rect containingFrame, Rect displayFrame) {
2598        final int pw = containingFrame.width();
2599        final int ph = containingFrame.height();
2600        final Task task = getTask();
2601        final boolean nonFullscreenTask = isInMultiWindowMode();
2602        final boolean fitToDisplay = task != null && !nonFullscreenTask && !layoutInParentFrame();
2603        float x, y;
2604        int w,h;
2605
2606        if ((mAttrs.flags & FLAG_SCALED) != 0) {
2607            if (mAttrs.width < 0) {
2608                w = pw;
2609            } else if (mEnforceSizeCompat) {
2610                w = (int)(mAttrs.width * mGlobalScale + .5f);
2611            } else {
2612                w = mAttrs.width;
2613            }
2614            if (mAttrs.height < 0) {
2615                h = ph;
2616            } else if (mEnforceSizeCompat) {
2617                h = (int)(mAttrs.height * mGlobalScale + .5f);
2618            } else {
2619                h = mAttrs.height;
2620            }
2621        } else {
2622            if (mAttrs.width == MATCH_PARENT) {
2623                w = pw;
2624            } else if (mEnforceSizeCompat) {
2625                w = (int)(mRequestedWidth * mGlobalScale + .5f);
2626            } else {
2627                w = mRequestedWidth;
2628            }
2629            if (mAttrs.height == MATCH_PARENT) {
2630                h = ph;
2631            } else if (mEnforceSizeCompat) {
2632                h = (int)(mRequestedHeight * mGlobalScale + .5f);
2633            } else {
2634                h = mRequestedHeight;
2635            }
2636        }
2637
2638        if (mEnforceSizeCompat) {
2639            x = mAttrs.x * mGlobalScale;
2640            y = mAttrs.y * mGlobalScale;
2641        } else {
2642            x = mAttrs.x;
2643            y = mAttrs.y;
2644        }
2645
2646        if (nonFullscreenTask && !layoutInParentFrame()) {
2647            // Make sure window fits in containing frame since it is in a non-fullscreen task as
2648            // required by {@link Gravity#apply} call.
2649            w = Math.min(w, pw);
2650            h = Math.min(h, ph);
2651        }
2652
2653        // Set mFrame
2654        Gravity.apply(mAttrs.gravity, w, h, containingFrame,
2655                (int) (x + mAttrs.horizontalMargin * pw),
2656                (int) (y + mAttrs.verticalMargin * ph), mFrame);
2657
2658        // Now make sure the window fits in the overall display frame.
2659        if (fitToDisplay) {
2660            Gravity.applyDisplay(mAttrs.gravity, displayFrame, mFrame);
2661        }
2662
2663        // We need to make sure we update the CompatFrame as it is used for
2664        // cropping decisions, etc, on systems where we lack a decor layer.
2665        mCompatFrame.set(mFrame);
2666        if (mEnforceSizeCompat) {
2667            // See comparable block in computeFrameLw.
2668            mCompatFrame.scale(mInvGlobalScale);
2669        }
2670    }
2671
2672    boolean isChildWindow() {
2673        return mAttachedWindow != null;
2674    }
2675
2676    boolean layoutInParentFrame() {
2677        return isChildWindow() && (mAttrs.privateFlags & PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME) != 0;
2678    }
2679
2680    void setReplacing(boolean animate) {
2681        if ((mAttrs.privateFlags & PRIVATE_FLAG_WILL_NOT_REPLACE_ON_RELAUNCH) != 0
2682                || mAttrs.type == TYPE_APPLICATION_STARTING) {
2683            // We don't set replacing on starting windows since they are added by window manager and
2684            // not the client so won't be replaced by the client.
2685            return;
2686        }
2687
2688        mWillReplaceWindow = true;
2689        mReplacingWindow = null;
2690        mAnimateReplacingWindow = animate;
2691    }
2692
2693    void resetReplacing() {
2694        mWillReplaceWindow = false;
2695        mReplacingWindow = null;
2696        mAnimateReplacingWindow = false;
2697    }
2698
2699    float translateToWindowX(float x) {
2700        float winX = x - mFrame.left;
2701        if (mEnforceSizeCompat) {
2702            winX *= mGlobalScale;
2703        }
2704        return winX;
2705    }
2706
2707    float translateToWindowY(float y) {
2708        float winY = y - mFrame.top;
2709        if (mEnforceSizeCompat) {
2710            winY *= mGlobalScale;
2711        }
2712        return winY;
2713    }
2714
2715    // During activity relaunch due to resize, we sometimes use window replacement
2716    // for only child windows (as the main window is handled by window preservation)
2717    // and the big surface.
2718    //
2719    // Though windows of TYPE_APPLICATION (as opposed to TYPE_BASE_APPLICATION)
2720    // are not children in the sense of an attached window, we also want to replace
2721    // them at such phases, as they won't be covered by window preservation,
2722    // and in general we expect them to return following relaunch.
2723    boolean shouldBeReplacedWithChildren() {
2724        return isChildWindow() || mAttrs.type == TYPE_APPLICATION;
2725    }
2726}
2727