WindowState.java revision 9fe459da7ee3fd462a646b638f647c917c229eb4
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 && isVisibleUnchecked()) {
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                if (win.isDimming()) {
1579                    win.transferDimToReplacement();
1580                }
1581                win.mWillReplaceWindow = false;
1582                win.mAnimateReplacingWindow = false;
1583                win.mReplacingRemoveRequested = false;
1584                win.mReplacingWindow = null;
1585                mSkipEnterAnimationForSeamlessReplacement = false;
1586                if (win.mAnimatingExit) {
1587                    mService.removeWindowInnerLocked(win);
1588                }
1589            }
1590        }
1591    }
1592
1593    void setDisplayLayoutNeeded() {
1594        if (mDisplayContent != null) {
1595            mDisplayContent.layoutNeeded = true;
1596        }
1597    }
1598
1599    boolean inDockedWorkspace() {
1600        final Task task = getTask();
1601        return task != null && task.inDockedWorkspace();
1602    }
1603
1604    boolean isDockedInEffect() {
1605        final Task task = getTask();
1606        return task != null && task.isDockedInEffect();
1607    }
1608
1609    void applyScrollIfNeeded() {
1610        final Task task = getTask();
1611        if (task != null) {
1612            task.applyScrollToWindowIfNeeded(this);
1613        }
1614    }
1615
1616    int getTouchableRegion(Region region, int flags) {
1617        final boolean modal = (flags & (FLAG_NOT_TOUCH_MODAL | FLAG_NOT_FOCUSABLE)) == 0;
1618        if (modal && mAppToken != null) {
1619            // Limit the outer touch to the activity stack region.
1620            flags |= FLAG_NOT_TOUCH_MODAL;
1621            // If this is a modal window we need to dismiss it if it's not full screen and the
1622            // touch happens outside of the frame that displays the content. This means we
1623            // need to intercept touches outside of that window. The dim layer user
1624            // associated with the window (task or stack) will give us the good bounds, as
1625            // they would be used to display the dim layer.
1626            final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
1627            if (dimLayerUser != null) {
1628                dimLayerUser.getDimBounds(mTmpRect);
1629            } else {
1630                getVisibleBounds(mTmpRect);
1631            }
1632            if (inFreeformWorkspace()) {
1633                // For freeform windows we the touch region to include the whole surface for the
1634                // shadows.
1635                final DisplayMetrics displayMetrics = getDisplayContent().getDisplayMetrics();
1636                final int delta = WindowManagerService.dipToPixel(
1637                        RESIZE_HANDLE_WIDTH_IN_DP, displayMetrics);
1638                mTmpRect.inset(-delta, -delta);
1639            }
1640            region.set(mTmpRect);
1641            cropRegionToStackBoundsIfNeeded(region);
1642        } else {
1643            // Not modal or full screen modal
1644            getTouchableRegion(region);
1645        }
1646        return flags;
1647    }
1648
1649    void checkPolicyVisibilityChange() {
1650        if (mPolicyVisibility != mPolicyVisibilityAfterAnim) {
1651            if (DEBUG_VISIBILITY) {
1652                Slog.v(TAG, "Policy visibility changing after anim in " +
1653                        mWinAnimator + ": " + mPolicyVisibilityAfterAnim);
1654            }
1655            mPolicyVisibility = mPolicyVisibilityAfterAnim;
1656            setDisplayLayoutNeeded();
1657            if (!mPolicyVisibility) {
1658                if (mService.mCurrentFocus == this) {
1659                    if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1660                            "setAnimationLocked: setting mFocusMayChange true");
1661                    mService.mFocusMayChange = true;
1662                }
1663                // Window is no longer visible -- make sure if we were waiting
1664                // for it to be displayed before enabling the display, that
1665                // we allow the display to be enabled now.
1666                mService.enableScreenIfNeededLocked();
1667            }
1668        }
1669    }
1670
1671    void setRequestedSize(int requestedWidth, int requestedHeight) {
1672        if ((mRequestedWidth != requestedWidth || mRequestedHeight != requestedHeight)) {
1673            mLayoutNeeded = true;
1674            mRequestedWidth = requestedWidth;
1675            mRequestedHeight = requestedHeight;
1676        }
1677    }
1678
1679    void prepareWindowToDisplayDuringRelayout(Configuration outConfig) {
1680        if ((mAttrs.softInputMode & SOFT_INPUT_MASK_ADJUST)
1681                == SOFT_INPUT_ADJUST_RESIZE) {
1682            mLayoutNeeded = true;
1683        }
1684        if (isDrawnLw() && mService.okToDisplay()) {
1685            mWinAnimator.applyEnterAnimationLocked();
1686        }
1687        if ((mAttrs.flags & FLAG_TURN_SCREEN_ON) != 0) {
1688            if (DEBUG_VISIBILITY) Slog.v(TAG, "Relayout window turning screen on: " + this);
1689            mTurnOnScreen = true;
1690        }
1691        if (isConfigChanged()) {
1692            final Configuration newConfig = updateConfiguration();
1693            if (DEBUG_CONFIGURATION) Slog.i(TAG, "Window " + this + " visible with new config: "
1694                    + newConfig);
1695            outConfig.setTo(newConfig);
1696        }
1697    }
1698
1699    void adjustStartingWindowFlags() {
1700        if (mAttrs.type == TYPE_BASE_APPLICATION && mAppToken != null
1701                && mAppToken.startingWindow != null) {
1702            // Special handling of starting window over the base
1703            // window of the app: propagate lock screen flags to it,
1704            // to provide the correct semantics while starting.
1705            final int mask = FLAG_SHOW_WHEN_LOCKED | FLAG_DISMISS_KEYGUARD
1706                    | FLAG_ALLOW_LOCK_WHILE_SCREEN_ON;
1707            WindowManager.LayoutParams sa = mAppToken.startingWindow.mAttrs;
1708            sa.flags = (sa.flags & ~mask) | (mAttrs.flags & mask);
1709        }
1710    }
1711
1712    void setWindowScale(int requestedWidth, int requestedHeight) {
1713        final boolean scaledWindow = (mAttrs.flags & FLAG_SCALED) != 0;
1714
1715        if (scaledWindow) {
1716            // requested{Width|Height} Surface's physical size
1717            // attrs.{width|height} Size on screen
1718            // TODO: We don't check if attrs != null here. Is it implicitly checked?
1719            mHScale = (mAttrs.width  != requestedWidth)  ?
1720                    (mAttrs.width  / (float)requestedWidth) : 1.0f;
1721            mVScale = (mAttrs.height != requestedHeight) ?
1722                    (mAttrs.height / (float)requestedHeight) : 1.0f;
1723        } else {
1724            mHScale = mVScale = 1;
1725        }
1726    }
1727
1728    private class DeathRecipient implements IBinder.DeathRecipient {
1729        @Override
1730        public void binderDied() {
1731            try {
1732                synchronized(mService.mWindowMap) {
1733                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
1734                    Slog.i(TAG, "WIN DEATH: " + win);
1735                    if (win != null) {
1736                        if (win.mAppToken != null && !win.mAppToken.clientHidden) {
1737                            win.mAppToken.appDied = true;
1738                        }
1739                        mService.removeWindowLocked(win);
1740                        if (win.mAttrs.type == TYPE_DOCK_DIVIDER) {
1741                            // The owner of the docked divider died :( We reset the docked stack,
1742                            // just in case they have the divider at an unstable position. Better
1743                            // also reset drag resizing state, because the owner can't do it
1744                            // anymore.
1745                            final TaskStack stack = mService.mStackIdToStack.get(DOCKED_STACK_ID);
1746                            if (stack != null) {
1747                                stack.resetDockedStackToMiddle();
1748                            }
1749                            mService.setDockedStackResizing(false);
1750                        }
1751                    } else if (mHasSurface) {
1752                        Slog.e(TAG, "!!! LEAK !!! Window removed but surface still valid.");
1753                        mService.removeWindowLocked(WindowState.this);
1754                    }
1755                }
1756            } catch (IllegalArgumentException ex) {
1757                // This will happen if the window has already been
1758                // removed.
1759            }
1760        }
1761    }
1762
1763    /**
1764     * Returns true if this window is visible and belongs to a dead app and shouldn't be removed,
1765     * because we want to preserve its location on screen to be re-activated later when the user
1766     * interacts with it.
1767     */
1768    boolean shouldKeepVisibleDeadAppWindow() {
1769        if (!isWinVisibleLw() || mAppToken == null || !mAppToken.appDied) {
1770            // Not a visible app window or the app isn't dead.
1771            return false;
1772        }
1773
1774        if (mAttrs.type == TYPE_APPLICATION_STARTING) {
1775            // We don't keep starting windows since they were added by the window manager before
1776            // the app even launched.
1777            return false;
1778        }
1779
1780        final TaskStack stack = getStack();
1781        return stack != null && StackId.keepVisibleDeadAppWindowOnScreen(stack.mStackId);
1782    }
1783
1784    /** @return true if this window desires key events. */
1785    boolean canReceiveKeys() {
1786        return isVisibleOrAdding()
1787                && (mViewVisibility == View.VISIBLE)
1788                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0)
1789                && (mAppToken == null || mAppToken.windowsAreFocusable());
1790    }
1791
1792    @Override
1793    public boolean hasDrawnLw() {
1794        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
1795    }
1796
1797    @Override
1798    public boolean showLw(boolean doAnimation) {
1799        return showLw(doAnimation, true);
1800    }
1801
1802    boolean showLw(boolean doAnimation, boolean requestAnim) {
1803        if (isHiddenFromUserLocked()) {
1804            return false;
1805        }
1806        if (!mAppOpVisibility) {
1807            // Being hidden due to app op request.
1808            return false;
1809        }
1810        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
1811            // Already showing.
1812            return false;
1813        }
1814        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
1815        if (doAnimation) {
1816            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
1817                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
1818            if (!mService.okToDisplay()) {
1819                doAnimation = false;
1820            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
1821                // Check for the case where we are currently visible and
1822                // not animating; we do not want to do animation at such a
1823                // point to become visible when we already are.
1824                doAnimation = false;
1825            }
1826        }
1827        mPolicyVisibility = true;
1828        mPolicyVisibilityAfterAnim = true;
1829        if (doAnimation) {
1830            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
1831        }
1832        if (requestAnim) {
1833            mService.scheduleAnimationLocked();
1834        }
1835        return true;
1836    }
1837
1838    @Override
1839    public boolean hideLw(boolean doAnimation) {
1840        return hideLw(doAnimation, true);
1841    }
1842
1843    boolean hideLw(boolean doAnimation, boolean requestAnim) {
1844        if (doAnimation) {
1845            if (!mService.okToDisplay()) {
1846                doAnimation = false;
1847            }
1848        }
1849        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
1850                : mPolicyVisibility;
1851        if (!current) {
1852            // Already hiding.
1853            return false;
1854        }
1855        if (doAnimation) {
1856            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
1857            if (mWinAnimator.mAnimation == null) {
1858                doAnimation = false;
1859            }
1860        }
1861        if (doAnimation) {
1862            mPolicyVisibilityAfterAnim = false;
1863        } else {
1864            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
1865            mPolicyVisibilityAfterAnim = false;
1866            mPolicyVisibility = false;
1867            // Window is no longer visible -- make sure if we were waiting
1868            // for it to be displayed before enabling the display, that
1869            // we allow the display to be enabled now.
1870            mService.enableScreenIfNeededLocked();
1871            if (mService.mCurrentFocus == this) {
1872                if (DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1873                        "WindowState.hideLw: setting mFocusMayChange true");
1874                mService.mFocusMayChange = true;
1875            }
1876        }
1877        if (requestAnim) {
1878            mService.scheduleAnimationLocked();
1879        }
1880        return true;
1881    }
1882
1883    public void setAppOpVisibilityLw(boolean state) {
1884        if (mAppOpVisibility != state) {
1885            mAppOpVisibility = state;
1886            if (state) {
1887                // If the policy visibility had last been to hide, then this
1888                // will incorrectly show at this point since we lost that
1889                // information.  Not a big deal -- for the windows that have app
1890                // ops modifies they should only be hidden by policy due to the
1891                // lock screen, and the user won't be changing this if locked.
1892                // Plus it will quickly be fixed the next time we do a layout.
1893                showLw(true, true);
1894            } else {
1895                hideLw(true, true);
1896            }
1897        }
1898    }
1899
1900    public void pokeDrawLockLw(long timeout) {
1901        if (isVisibleOrAdding()) {
1902            if (mDrawLock == null) {
1903                // We want the tag name to be somewhat stable so that it is easier to correlate
1904                // in wake lock statistics.  So in particular, we don't want to include the
1905                // window's hash code as in toString().
1906                final CharSequence tag = getWindowTag();
1907                mDrawLock = mService.mPowerManager.newWakeLock(
1908                        PowerManager.DRAW_WAKE_LOCK, "Window:" + tag);
1909                mDrawLock.setReferenceCounted(false);
1910                mDrawLock.setWorkSource(new WorkSource(mOwnerUid, mAttrs.packageName));
1911            }
1912            // Each call to acquire resets the timeout.
1913            if (DEBUG_POWER) {
1914                Slog.d(TAG, "pokeDrawLock: poking draw lock on behalf of visible window owned by "
1915                        + mAttrs.packageName);
1916            }
1917            mDrawLock.acquire(timeout);
1918        } else if (DEBUG_POWER) {
1919            Slog.d(TAG, "pokeDrawLock: suppressed draw lock request for invisible window "
1920                    + "owned by " + mAttrs.packageName);
1921        }
1922    }
1923
1924    @Override
1925    public boolean isAlive() {
1926        return mClient.asBinder().isBinderAlive();
1927    }
1928
1929    boolean isClosing() {
1930        return mAnimatingExit || (mService.mClosingApps.contains(mAppToken));
1931    }
1932
1933    boolean isAnimatingWithSavedSurface() {
1934        return mAppToken != null && mAppToken.mAnimatingWithSavedSurface;
1935    }
1936
1937    private boolean shouldSaveSurface() {
1938        if (mWinAnimator.mSurfaceController == null) {
1939            // Don't bother if the surface controller is gone for any reason.
1940            return false;
1941        }
1942
1943        if ((mAttrs.flags & FLAG_SECURE) != 0) {
1944            // We don't save secure surfaces since their content shouldn't be shown while the app
1945            // isn't on screen and content might leak through during the transition animation with
1946            // saved surface.
1947            return false;
1948        }
1949
1950        if (ActivityManager.isLowRamDeviceStatic()) {
1951            // Don't save surfaces on Svelte devices.
1952            return false;
1953        }
1954
1955        Task task = getTask();
1956        if (task == null || task.inHomeStack()) {
1957            // Don't save surfaces for home stack apps. These usually resume and draw
1958            // first frame very fast. Saving surfaces are mostly a waste of memory.
1959            return false;
1960        }
1961
1962        final AppWindowToken taskTop = task.getTopVisibleAppToken();
1963        if (taskTop != null && taskTop != mAppToken) {
1964            // Don't save if the window is not the topmost window.
1965            return false;
1966        }
1967
1968        if (mResizedWhileGone) {
1969            // Somebody resized our window while we were gone for layout, which means that the
1970            // client got an old size, so we have an outdated surface here.
1971            return false;
1972        }
1973
1974        if (DEBUG_DISABLE_SAVING_SURFACES) {
1975            return false;
1976        }
1977
1978        return mAppToken.shouldSaveSurface();
1979    }
1980
1981    void destroyOrSaveSurface() {
1982        mSurfaceSaved = shouldSaveSurface();
1983        if (mSurfaceSaved) {
1984            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
1985                Slog.v(TAG, "Saving surface: " + this);
1986            }
1987
1988            mWinAnimator.hide("saved surface");
1989            mWinAnimator.mDrawState = WindowStateAnimator.NO_SURFACE;
1990            setHasSurface(false);
1991            // The client should have disconnected at this point, but if it doesn't,
1992            // we need to make sure it's disconnected. Otherwise when we reuse the surface
1993            // the client can't reconnect to the buffer queue, and rendering will fail.
1994            if (mWinAnimator.mSurfaceController != null) {
1995                mWinAnimator.mSurfaceController.disconnectInTransaction();
1996            }
1997        } else {
1998            mWinAnimator.destroySurfaceLocked();
1999        }
2000    }
2001
2002    public void destroySavedSurface() {
2003        if (mSurfaceSaved) {
2004            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
2005                Slog.v(TAG, "Destroying saved surface: " + this);
2006            }
2007            mWinAnimator.destroySurfaceLocked();
2008        }
2009    }
2010
2011    public void restoreSavedSurface() {
2012        if (!mSurfaceSaved) {
2013            return;
2014        }
2015        mSurfaceSaved = false;
2016        if (mWinAnimator.mSurfaceController != null) {
2017            setHasSurface(true);
2018            mWinAnimator.mDrawState = WindowStateAnimator.READY_TO_SHOW;
2019
2020            if (DEBUG_APP_TRANSITIONS || DEBUG_ANIM) {
2021                Slog.v(TAG, "Restoring saved surface: " + this);
2022            }
2023        } else {
2024            // mSurfaceController shouldn't be null if mSurfaceSaved was still true at
2025            // this point. Even if we destroyed the saved surface because of rotation
2026            // or resize, mSurfaceSaved flag should have been cleared. So this is a wtf.
2027            Slog.wtf(TAG, "Failed to restore saved surface: surface gone! " + this);
2028        }
2029    }
2030
2031    public boolean hasSavedSurface() {
2032        return mSurfaceSaved;
2033    }
2034
2035    @Override
2036    public boolean isDefaultDisplay() {
2037        final DisplayContent displayContent = getDisplayContent();
2038        if (displayContent == null) {
2039            // Only a window that was on a non-default display can be detached from it.
2040            return false;
2041        }
2042        return displayContent.isDefaultDisplay;
2043    }
2044
2045    @Override
2046    public boolean isDimming() {
2047        final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
2048        return dimLayerUser != null && mDisplayContent != null &&
2049                mDisplayContent.mDimLayerController.isDimming(dimLayerUser, mWinAnimator);
2050    }
2051
2052    public void setShowToOwnerOnlyLocked(boolean showToOwnerOnly) {
2053        mShowToOwnerOnly = showToOwnerOnly;
2054    }
2055
2056    boolean isHiddenFromUserLocked() {
2057        // Attached windows are evaluated based on the window that they are attached to.
2058        WindowState win = this;
2059        while (win.isChildWindow()) {
2060            win = win.mAttachedWindow;
2061        }
2062        if (win.mAttrs.type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
2063                && win.mAppToken != null && win.mAppToken.showForAllUsers) {
2064            // Save some cycles by not calling getDisplayInfo unless it is an application
2065            // window intended for all users.
2066            final DisplayContent displayContent = win.getDisplayContent();
2067            if (displayContent == null) {
2068                return true;
2069            }
2070            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
2071            if (win.mFrame.left <= 0 && win.mFrame.top <= 0
2072                    && win.mFrame.right >= displayInfo.appWidth
2073                    && win.mFrame.bottom >= displayInfo.appHeight) {
2074                // Is a fullscreen window, like the clock alarm. Show to everyone.
2075                return false;
2076            }
2077        }
2078
2079        return win.mShowToOwnerOnly
2080                && !mService.isCurrentProfileLocked(UserHandle.getUserId(win.mOwnerUid));
2081    }
2082
2083    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
2084        outRegion.set(
2085                frame.left + inset.left, frame.top + inset.top,
2086                frame.right - inset.right, frame.bottom - inset.bottom);
2087    }
2088
2089    void getTouchableRegion(Region outRegion) {
2090        final Rect frame = mFrame;
2091        switch (mTouchableInsets) {
2092            default:
2093            case TOUCHABLE_INSETS_FRAME:
2094                outRegion.set(frame);
2095                break;
2096            case TOUCHABLE_INSETS_CONTENT:
2097                applyInsets(outRegion, frame, mGivenContentInsets);
2098                break;
2099            case TOUCHABLE_INSETS_VISIBLE:
2100                applyInsets(outRegion, frame, mGivenVisibleInsets);
2101                break;
2102            case TOUCHABLE_INSETS_REGION: {
2103                final Region givenTouchableRegion = mGivenTouchableRegion;
2104                outRegion.set(givenTouchableRegion);
2105                outRegion.translate(frame.left, frame.top);
2106                break;
2107            }
2108        }
2109        cropRegionToStackBoundsIfNeeded(outRegion);
2110    }
2111
2112    void cropRegionToStackBoundsIfNeeded(Region region) {
2113        final Task task = getTask();
2114        if (task == null || !task.cropWindowsToStackBounds()) {
2115            return;
2116        }
2117
2118        final TaskStack stack = task.mStack;
2119        if (stack == null) {
2120            return;
2121        }
2122
2123        stack.getDimBounds(mTmpRect);
2124        region.op(mTmpRect, Region.Op.INTERSECT);
2125    }
2126
2127    WindowList getWindowList() {
2128        final DisplayContent displayContent = getDisplayContent();
2129        return displayContent == null ? null : displayContent.getWindowList();
2130    }
2131
2132    /**
2133     * Report a focus change.  Must be called with no locks held, and consistently
2134     * from the same serialized thread (such as dispatched from a handler).
2135     */
2136    public void reportFocusChangedSerialized(boolean focused, boolean inTouchMode) {
2137        try {
2138            mClient.windowFocusChanged(focused, inTouchMode);
2139        } catch (RemoteException e) {
2140        }
2141        if (mFocusCallbacks != null) {
2142            final int N = mFocusCallbacks.beginBroadcast();
2143            for (int i=0; i<N; i++) {
2144                IWindowFocusObserver obs = mFocusCallbacks.getBroadcastItem(i);
2145                try {
2146                    if (focused) {
2147                        obs.focusGained(mWindowId.asBinder());
2148                    } else {
2149                        obs.focusLost(mWindowId.asBinder());
2150                    }
2151                } catch (RemoteException e) {
2152                }
2153            }
2154            mFocusCallbacks.finishBroadcast();
2155        }
2156    }
2157
2158    /**
2159     * Update our current configurations, based on task configuration.
2160     *
2161     * @return A configuration suitable for sending to the client.
2162     */
2163    private Configuration updateConfiguration() {
2164        final Task task = getTask();
2165        final Configuration overrideConfig =
2166            (task != null) ? task.mOverrideConfig : Configuration.EMPTY;
2167        final boolean configChanged = isConfigChanged();
2168        if ((DEBUG_RESIZE || DEBUG_ORIENTATION || DEBUG_CONFIGURATION) && configChanged) {
2169            Slog.i(TAG, "Sending new config to window " + this + ": " +
2170                    " / config=" + mService.mCurConfiguration + " overrideConfig=" + overrideConfig);
2171        }
2172        setConfiguration(mService.mCurConfiguration, overrideConfig);
2173        return mMergedConfiguration;
2174    }
2175
2176    void reportResized() {
2177        Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "wm.reportResized_" + getWindowTag());
2178        try {
2179            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
2180                    + ": " + mCompatFrame);
2181            final Configuration newConfig = isConfigChanged() ? updateConfiguration() : null;
2182            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING)
2183                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
2184
2185            final Rect frame = mFrame;
2186            final Rect overscanInsets = mLastOverscanInsets;
2187            final Rect contentInsets = mLastContentInsets;
2188            final Rect visibleInsets = mLastVisibleInsets;
2189            final Rect stableInsets = mLastStableInsets;
2190            final Rect outsets = mLastOutsets;
2191            final boolean reportDraw = mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING;
2192            if (mAttrs.type != WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
2193                    && mClient instanceof IWindow.Stub) {
2194                // To prevent deadlock simulate one-way call if win.mClient is a local object.
2195                mService.mH.post(new Runnable() {
2196                    @Override
2197                    public void run() {
2198                        try {
2199                            dispatchResized(frame, overscanInsets, contentInsets, visibleInsets,
2200                                    stableInsets, outsets, reportDraw, newConfig);
2201                        } catch (RemoteException e) {
2202                            // Not a remote call, RemoteException won't be raised.
2203                        }
2204                    }
2205                });
2206            } else {
2207                dispatchResized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets,
2208                        outsets, reportDraw, newConfig);
2209            }
2210
2211            //TODO (multidisplay): Accessibility supported only for the default display.
2212            if (mService.mAccessibilityController != null
2213                    && getDisplayId() == Display.DEFAULT_DISPLAY) {
2214                mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
2215            }
2216
2217            mOverscanInsetsChanged = false;
2218            mContentInsetsChanged = false;
2219            mVisibleInsetsChanged = false;
2220            mStableInsetsChanged = false;
2221            mOutsetsChanged = false;
2222            mWinAnimator.mSurfaceResized = false;
2223        } catch (RemoteException e) {
2224            mOrientationChanging = false;
2225            mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
2226                    - mService.mDisplayFreezeTime);
2227            // We are assuming the hosting process is dead or in a zombie state.
2228            Slog.w(TAG, "Failed to report 'resized' to the client of " + this
2229                    + ", removing this window.");
2230            mService.mPendingRemove.add(this);
2231            mService.mWindowPlacerLocked.requestTraversal();
2232        }
2233        Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
2234    }
2235
2236    Rect getBackdropFrame(Rect frame) {
2237        // When the task is docked, we send fullscreen sized backDropFrame as soon as resizing
2238        // start even if we haven't received the relayout window, so that the client requests
2239        // the relayout sooner. When dragging stops, backDropFrame needs to stay fullscreen
2240        // until the window to small size, otherwise the multithread renderer will shift last
2241        // one or more frame to wrong offset. So here we send fullscreen backdrop if either
2242        // isDragResizing() or isDragResizeChanged() is true.
2243        boolean resizing = isDragResizing() || isDragResizeChanged();
2244        if (StackId.useWindowFrameForBackdrop(getStackId()) || !resizing) {
2245            return frame;
2246        }
2247        DisplayInfo displayInfo = getDisplayInfo();
2248        mTmpRect.set(0, 0, displayInfo.logicalWidth, displayInfo.logicalHeight);
2249        return mTmpRect;
2250    }
2251
2252    @Override
2253    public int getStackId() {
2254        final TaskStack stack = getStack();
2255        if (stack == null) {
2256            return INVALID_STACK_ID;
2257        }
2258        return stack.mStackId;
2259    }
2260
2261    private void dispatchResized(Rect frame, Rect overscanInsets, Rect contentInsets,
2262            Rect visibleInsets, Rect stableInsets, Rect outsets, boolean reportDraw,
2263            Configuration newConfig) throws RemoteException {
2264        mClient.resized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets, outsets,
2265                reportDraw, newConfig, getBackdropFrame(frame),
2266                isDragResizeChanged() /* forceRelayout */, mPolicy.isNavBarForcedShownLw(this));
2267        mDragResizingChangeReported = true;
2268    }
2269
2270    public void registerFocusObserver(IWindowFocusObserver observer) {
2271        synchronized(mService.mWindowMap) {
2272            if (mFocusCallbacks == null) {
2273                mFocusCallbacks = new RemoteCallbackList<IWindowFocusObserver>();
2274            }
2275            mFocusCallbacks.register(observer);
2276        }
2277    }
2278
2279    public void unregisterFocusObserver(IWindowFocusObserver observer) {
2280        synchronized(mService.mWindowMap) {
2281            if (mFocusCallbacks != null) {
2282                mFocusCallbacks.unregister(observer);
2283            }
2284        }
2285    }
2286
2287    public boolean isFocused() {
2288        synchronized(mService.mWindowMap) {
2289            return mService.mCurrentFocus == this;
2290        }
2291    }
2292
2293    boolean inFreeformWorkspace() {
2294        final Task task = getTask();
2295        return task != null && task.inFreeformWorkspace();
2296    }
2297
2298    @Override
2299    public boolean isInMultiWindowMode() {
2300        final Task task = getTask();
2301        return task != null && !task.isFullscreen();
2302    }
2303
2304    boolean isDragResizeChanged() {
2305        return mDragResizing != computeDragResizing();
2306    }
2307
2308    /**
2309     * @return Whether we reported a drag resize change to the application or not already.
2310     */
2311    boolean isDragResizingChangeReported() {
2312        return mDragResizingChangeReported;
2313    }
2314
2315    /**
2316     * Resets the state whether we reported a drag resize change to the app.
2317     */
2318    void resetDragResizingChangeReported() {
2319        mDragResizingChangeReported = false;
2320    }
2321
2322    int getResizeMode() {
2323        return mResizeMode;
2324    }
2325
2326    boolean computeDragResizing() {
2327        final Task task = getTask();
2328        if (task == null) {
2329            return false;
2330        }
2331        if (mAttrs.width != MATCH_PARENT || mAttrs.height != MATCH_PARENT) {
2332
2333            // Floating windows never enter drag resize mode.
2334            return false;
2335        }
2336        if (task.isDragResizing()) {
2337            return true;
2338        }
2339
2340        // If the bounds are currently frozen, it means that the layout size that the app sees
2341        // and the bounds we clip this window to might be different. In order to avoid holes, we
2342        // simulate that we are still resizing so the app fills the hole with the resizing
2343        // background.
2344        return (mDisplayContent.mDividerControllerLocked.isResizing()
2345                        || mAppToken != null && !mAppToken.mFrozenBounds.isEmpty()) &&
2346                !task.inFreeformWorkspace() && !isGoneForLayoutLw();
2347
2348    }
2349
2350    void setDragResizing() {
2351        final boolean resizing = computeDragResizing();
2352        if (resizing == mDragResizing) {
2353            return;
2354        }
2355        mDragResizing = resizing;
2356        final Task task = getTask();
2357        if (task != null && task.isDragResizing()) {
2358            mResizeMode = task.getDragResizeMode();
2359        } else {
2360            mResizeMode = mDragResizing && mDisplayContent.mDividerControllerLocked.isResizing()
2361                    ? DRAG_RESIZE_MODE_DOCKED_DIVIDER
2362                    : DRAG_RESIZE_MODE_FREEFORM;
2363        }
2364    }
2365
2366    boolean isDragResizing() {
2367        return mDragResizing;
2368    }
2369
2370    boolean isDockedResizing() {
2371        return mDragResizing && getResizeMode() == DRAG_RESIZE_MODE_DOCKED_DIVIDER;
2372    }
2373
2374    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
2375        final TaskStack stack = getStack();
2376        pw.print(prefix); pw.print("mDisplayId="); pw.print(getDisplayId());
2377                if (stack != null) {
2378                    pw.print(" stackId="); pw.print(stack.mStackId);
2379                }
2380                pw.print(" mSession="); pw.print(mSession);
2381                pw.print(" mClient="); pw.println(mClient.asBinder());
2382        pw.print(prefix); pw.print("mOwnerUid="); pw.print(mOwnerUid);
2383                pw.print(" mShowToOwnerOnly="); pw.print(mShowToOwnerOnly);
2384                pw.print(" package="); pw.print(mAttrs.packageName);
2385                pw.print(" appop="); pw.println(AppOpsManager.opToName(mAppOp));
2386        pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
2387        pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
2388                pw.print(" h="); pw.print(mRequestedHeight);
2389                pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
2390        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
2391            pw.print(prefix); pw.print("LastRequested w="); pw.print(mLastRequestedWidth);
2392                    pw.print(" h="); pw.println(mLastRequestedHeight);
2393        }
2394        if (isChildWindow() || mLayoutAttached) {
2395            pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
2396                    pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
2397        }
2398        if (mIsImWindow || mIsWallpaper || mIsFloatingLayer) {
2399            pw.print(prefix); pw.print("mIsImWindow="); pw.print(mIsImWindow);
2400                    pw.print(" mIsWallpaper="); pw.print(mIsWallpaper);
2401                    pw.print(" mIsFloatingLayer="); pw.print(mIsFloatingLayer);
2402                    pw.print(" mWallpaperVisible="); pw.println(mWallpaperVisible);
2403        }
2404        if (dumpAll) {
2405            pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
2406                    pw.print(" mSubLayer="); pw.print(mSubLayer);
2407                    pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
2408                    pw.print((mTargetAppToken != null ?
2409                            mTargetAppToken.mAppAnimator.animLayerAdjustment
2410                          : (mAppToken != null ? mAppToken.mAppAnimator.animLayerAdjustment : 0)));
2411                    pw.print("="); pw.print(mWinAnimator.mAnimLayer);
2412                    pw.print(" mLastLayer="); pw.println(mWinAnimator.mLastLayer);
2413        }
2414        if (dumpAll) {
2415            pw.print(prefix); pw.print("mToken="); pw.println(mToken);
2416            pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
2417            if (mAppToken != null) {
2418                pw.print(prefix); pw.print("mAppToken="); pw.print(mAppToken);
2419                pw.print(" isAnimatingWithSavedSurface()=");
2420                pw.print(isAnimatingWithSavedSurface());
2421                pw.print(" mAppDied=");pw.println(mAppDied);
2422            }
2423            if (mTargetAppToken != null) {
2424                pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
2425            }
2426            pw.print(prefix); pw.print("mViewVisibility=0x");
2427            pw.print(Integer.toHexString(mViewVisibility));
2428            pw.print(" mHaveFrame="); pw.print(mHaveFrame);
2429            pw.print(" mObscured="); pw.println(mObscured);
2430            pw.print(prefix); pw.print("mSeq="); pw.print(mSeq);
2431            pw.print(" mSystemUiVisibility=0x");
2432            pw.println(Integer.toHexString(mSystemUiVisibility));
2433        }
2434        if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || !mAppOpVisibility
2435                || mAttachedHidden) {
2436            pw.print(prefix); pw.print("mPolicyVisibility=");
2437                    pw.print(mPolicyVisibility);
2438                    pw.print(" mPolicyVisibilityAfterAnim=");
2439                    pw.print(mPolicyVisibilityAfterAnim);
2440                    pw.print(" mAppOpVisibility=");
2441                    pw.print(mAppOpVisibility);
2442                    pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
2443        }
2444        if (!mRelayoutCalled || mLayoutNeeded) {
2445            pw.print(prefix); pw.print("mRelayoutCalled="); pw.print(mRelayoutCalled);
2446                    pw.print(" mLayoutNeeded="); pw.println(mLayoutNeeded);
2447        }
2448        if (mXOffset != 0 || mYOffset != 0) {
2449            pw.print(prefix); pw.print("Offsets x="); pw.print(mXOffset);
2450                    pw.print(" y="); pw.println(mYOffset);
2451        }
2452        if (dumpAll) {
2453            pw.print(prefix); pw.print("mGivenContentInsets=");
2454                    mGivenContentInsets.printShortString(pw);
2455                    pw.print(" mGivenVisibleInsets=");
2456                    mGivenVisibleInsets.printShortString(pw);
2457                    pw.println();
2458            if (mTouchableInsets != 0 || mGivenInsetsPending) {
2459                pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
2460                        pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
2461                Region region = new Region();
2462                getTouchableRegion(region);
2463                pw.print(prefix); pw.print("touchable region="); pw.println(region);
2464            }
2465            pw.print(prefix); pw.print("mConfiguration="); pw.println(mConfiguration);
2466            if (mOverrideConfig != Configuration.EMPTY) {
2467                pw.print(prefix); pw.print("mOverrideConfig="); pw.println(mOverrideConfig);
2468            }
2469        }
2470        pw.print(prefix); pw.print("mHasSurface="); pw.print(mHasSurface);
2471                pw.print(" mShownPosition="); mShownPosition.printShortString(pw);
2472                pw.print(" isReadyForDisplay()="); pw.print(isReadyForDisplay());
2473                pw.print(" hasSavedSurface()="); pw.print(hasSavedSurface());
2474                pw.print(" mWindowRemovalAllowed="); pw.println(mWindowRemovalAllowed);
2475        if (dumpAll) {
2476            pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
2477                    pw.print(" last="); mLastFrame.printShortString(pw);
2478                    pw.println();
2479        }
2480        if (mEnforceSizeCompat) {
2481            pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
2482                    pw.println();
2483        }
2484        if (dumpAll) {
2485            pw.print(prefix); pw.print("Frames: containing=");
2486                    mContainingFrame.printShortString(pw);
2487                    pw.print(" parent="); mParentFrame.printShortString(pw);
2488                    pw.println();
2489            pw.print(prefix); pw.print("    display="); mDisplayFrame.printShortString(pw);
2490                    pw.print(" overscan="); mOverscanFrame.printShortString(pw);
2491                    pw.println();
2492            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
2493                    pw.print(" visible="); mVisibleFrame.printShortString(pw);
2494                    pw.println();
2495            pw.print(prefix); pw.print("    decor="); mDecorFrame.printShortString(pw);
2496                    pw.println();
2497            pw.print(prefix); pw.print("    outset="); mOutsetFrame.printShortString(pw);
2498                    pw.println();
2499            pw.print(prefix); pw.print("Cur insets: overscan=");
2500                    mOverscanInsets.printShortString(pw);
2501                    pw.print(" content="); mContentInsets.printShortString(pw);
2502                    pw.print(" visible="); mVisibleInsets.printShortString(pw);
2503                    pw.print(" stable="); mStableInsets.printShortString(pw);
2504                    pw.print(" outsets="); mOutsets.printShortString(pw);
2505                    pw.println();
2506            pw.print(prefix); pw.print("Lst insets: overscan=");
2507                    mLastOverscanInsets.printShortString(pw);
2508                    pw.print(" content="); mLastContentInsets.printShortString(pw);
2509                    pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
2510                    pw.print(" stable="); mLastStableInsets.printShortString(pw);
2511                    pw.print(" physical="); mLastOutsets.printShortString(pw);
2512                    pw.print(" outset="); mLastOutsets.printShortString(pw);
2513                    pw.println();
2514        }
2515        pw.print(prefix); pw.print(mWinAnimator); pw.println(":");
2516        mWinAnimator.dump(pw, prefix + "  ", dumpAll);
2517        if (mAnimatingExit || mRemoveOnExit || mDestroying || mRemoved) {
2518            pw.print(prefix); pw.print("mAnimatingExit="); pw.print(mAnimatingExit);
2519                    pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
2520                    pw.print(" mDestroying="); pw.print(mDestroying);
2521                    pw.print(" mRemoved="); pw.println(mRemoved);
2522        }
2523        if (mOrientationChanging || mAppFreezing || mTurnOnScreen) {
2524            pw.print(prefix); pw.print("mOrientationChanging=");
2525                    pw.print(mOrientationChanging);
2526                    pw.print(" mAppFreezing="); pw.print(mAppFreezing);
2527                    pw.print(" mTurnOnScreen="); pw.println(mTurnOnScreen);
2528        }
2529        if (mLastFreezeDuration != 0) {
2530            pw.print(prefix); pw.print("mLastFreezeDuration=");
2531                    TimeUtils.formatDuration(mLastFreezeDuration, pw); pw.println();
2532        }
2533        if (mHScale != 1 || mVScale != 1) {
2534            pw.print(prefix); pw.print("mHScale="); pw.print(mHScale);
2535                    pw.print(" mVScale="); pw.println(mVScale);
2536        }
2537        if (mWallpaperX != -1 || mWallpaperY != -1) {
2538            pw.print(prefix); pw.print("mWallpaperX="); pw.print(mWallpaperX);
2539                    pw.print(" mWallpaperY="); pw.println(mWallpaperY);
2540        }
2541        if (mWallpaperXStep != -1 || mWallpaperYStep != -1) {
2542            pw.print(prefix); pw.print("mWallpaperXStep="); pw.print(mWallpaperXStep);
2543                    pw.print(" mWallpaperYStep="); pw.println(mWallpaperYStep);
2544        }
2545        if (mWallpaperDisplayOffsetX != Integer.MIN_VALUE
2546                || mWallpaperDisplayOffsetY != Integer.MIN_VALUE) {
2547            pw.print(prefix); pw.print("mWallpaperDisplayOffsetX=");
2548                    pw.print(mWallpaperDisplayOffsetX);
2549                    pw.print(" mWallpaperDisplayOffsetY=");
2550                    pw.println(mWallpaperDisplayOffsetY);
2551        }
2552        if (mDrawLock != null) {
2553            pw.print(prefix); pw.println("mDrawLock=" + mDrawLock);
2554        }
2555        if (isDragResizing()) {
2556            pw.print(prefix); pw.println("isDragResizing=" + isDragResizing());
2557        }
2558        if (computeDragResizing()) {
2559            pw.print(prefix); pw.println("computeDragResizing=" + computeDragResizing());
2560        }
2561    }
2562
2563    String makeInputChannelName() {
2564        return Integer.toHexString(System.identityHashCode(this))
2565            + " " + getWindowTag();
2566    }
2567
2568    CharSequence getWindowTag() {
2569        CharSequence tag = mAttrs.getTitle();
2570        if (tag == null || tag.length() <= 0) {
2571            tag = mAttrs.packageName;
2572        }
2573        return tag;
2574    }
2575
2576    @Override
2577    public String toString() {
2578        final CharSequence title = getWindowTag();
2579        if (mStringNameCache == null || mLastTitle != title || mWasExiting != mAnimatingExit) {
2580            mLastTitle = title;
2581            mWasExiting = mAnimatingExit;
2582            mStringNameCache = "Window{" + Integer.toHexString(System.identityHashCode(this))
2583                    + " u" + UserHandle.getUserId(mSession.mUid)
2584                    + " " + mLastTitle + (mAnimatingExit ? " EXITING}" : "}");
2585        }
2586        return mStringNameCache;
2587    }
2588
2589    void transformFromScreenToSurfaceSpace(Rect rect) {
2590         if (mHScale >= 0) {
2591            rect.left = (int) (rect.left / mHScale);
2592            rect.right = (int) (rect.right / mHScale);
2593        }
2594        if (mVScale >= 0) {
2595            rect.top = (int) (rect.top / mVScale);
2596            rect.bottom = (int) (rect.bottom / mVScale);
2597        }
2598    }
2599
2600    void applyGravityAndUpdateFrame(Rect containingFrame, Rect displayFrame) {
2601        final int pw = containingFrame.width();
2602        final int ph = containingFrame.height();
2603        final Task task = getTask();
2604        final boolean nonFullscreenTask = isInMultiWindowMode();
2605        final boolean fitToDisplay = task != null && !nonFullscreenTask && !layoutInParentFrame();
2606        float x, y;
2607        int w,h;
2608
2609        if ((mAttrs.flags & FLAG_SCALED) != 0) {
2610            if (mAttrs.width < 0) {
2611                w = pw;
2612            } else if (mEnforceSizeCompat) {
2613                w = (int)(mAttrs.width * mGlobalScale + .5f);
2614            } else {
2615                w = mAttrs.width;
2616            }
2617            if (mAttrs.height < 0) {
2618                h = ph;
2619            } else if (mEnforceSizeCompat) {
2620                h = (int)(mAttrs.height * mGlobalScale + .5f);
2621            } else {
2622                h = mAttrs.height;
2623            }
2624        } else {
2625            if (mAttrs.width == MATCH_PARENT) {
2626                w = pw;
2627            } else if (mEnforceSizeCompat) {
2628                w = (int)(mRequestedWidth * mGlobalScale + .5f);
2629            } else {
2630                w = mRequestedWidth;
2631            }
2632            if (mAttrs.height == MATCH_PARENT) {
2633                h = ph;
2634            } else if (mEnforceSizeCompat) {
2635                h = (int)(mRequestedHeight * mGlobalScale + .5f);
2636            } else {
2637                h = mRequestedHeight;
2638            }
2639        }
2640
2641        if (mEnforceSizeCompat) {
2642            x = mAttrs.x * mGlobalScale;
2643            y = mAttrs.y * mGlobalScale;
2644        } else {
2645            x = mAttrs.x;
2646            y = mAttrs.y;
2647        }
2648
2649        if (nonFullscreenTask && !layoutInParentFrame()) {
2650            // Make sure window fits in containing frame since it is in a non-fullscreen task as
2651            // required by {@link Gravity#apply} call.
2652            w = Math.min(w, pw);
2653            h = Math.min(h, ph);
2654        }
2655
2656        // Set mFrame
2657        Gravity.apply(mAttrs.gravity, w, h, containingFrame,
2658                (int) (x + mAttrs.horizontalMargin * pw),
2659                (int) (y + mAttrs.verticalMargin * ph), mFrame);
2660
2661        // Now make sure the window fits in the overall display frame.
2662        if (fitToDisplay) {
2663            Gravity.applyDisplay(mAttrs.gravity, displayFrame, mFrame);
2664        }
2665
2666        // We need to make sure we update the CompatFrame as it is used for
2667        // cropping decisions, etc, on systems where we lack a decor layer.
2668        mCompatFrame.set(mFrame);
2669        if (mEnforceSizeCompat) {
2670            // See comparable block in computeFrameLw.
2671            mCompatFrame.scale(mInvGlobalScale);
2672        }
2673    }
2674
2675    boolean isChildWindow() {
2676        return mAttachedWindow != null;
2677    }
2678
2679    boolean layoutInParentFrame() {
2680        return isChildWindow() && (mAttrs.privateFlags & PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME) != 0;
2681    }
2682
2683    void setReplacing(boolean animate) {
2684        if ((mAttrs.privateFlags & PRIVATE_FLAG_WILL_NOT_REPLACE_ON_RELAUNCH) != 0
2685                || mAttrs.type == TYPE_APPLICATION_STARTING) {
2686            // We don't set replacing on starting windows since they are added by window manager and
2687            // not the client so won't be replaced by the client.
2688            return;
2689        }
2690
2691        mWillReplaceWindow = true;
2692        mReplacingWindow = null;
2693        mAnimateReplacingWindow = animate;
2694    }
2695
2696    void resetReplacing() {
2697        mWillReplaceWindow = false;
2698        mReplacingWindow = null;
2699        mAnimateReplacingWindow = false;
2700    }
2701
2702    float translateToWindowX(float x) {
2703        float winX = x - mFrame.left;
2704        if (mEnforceSizeCompat) {
2705            winX *= mGlobalScale;
2706        }
2707        return winX;
2708    }
2709
2710    float translateToWindowY(float y) {
2711        float winY = y - mFrame.top;
2712        if (mEnforceSizeCompat) {
2713            winY *= mGlobalScale;
2714        }
2715        return winY;
2716    }
2717
2718    void transferDimToReplacement() {
2719        final DimLayer.DimLayerUser dimLayerUser = getDimLayerUser();
2720        if (dimLayerUser != null && mDisplayContent != null) {
2721            mDisplayContent.mDimLayerController.applyDim(dimLayerUser,
2722                    mReplacingWindow.mWinAnimator,
2723                    (mAttrs.flags & FLAG_DIM_BEHIND) != 0 ? true : false);
2724        }
2725    }
2726
2727    // During activity relaunch due to resize, we sometimes use window replacement
2728    // for only child windows (as the main window is handled by window preservation)
2729    // and the big surface.
2730    //
2731    // Though windows of TYPE_APPLICATION (as opposed to TYPE_BASE_APPLICATION)
2732    // are not children in the sense of an attached window, we also want to replace
2733    // them at such phases, as they won't be covered by window preservation,
2734    // and in general we expect them to return following relaunch.
2735    boolean shouldBeReplacedWithChildren() {
2736        return isChildWindow() || mAttrs.type == TYPE_APPLICATION;
2737    }
2738}
2739