WindowState.java revision c0d2d0ad6ddcd23b7bbe6b1a5668d6d719e4c86c
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 static com.android.server.wm.WindowManagerService.DEBUG_CONFIGURATION;
20import static com.android.server.wm.WindowManagerService.DEBUG_LAYOUT;
21import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
22import static com.android.server.wm.WindowManagerService.DEBUG_RESIZE;
23import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
24
25import static android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
26import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
27import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_COMPATIBLE_WINDOW;
28import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
29import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION;
30import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
31import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
32import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
33import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
34
35import android.app.AppOpsManager;
36import android.os.Debug;
37import android.os.RemoteCallbackList;
38import android.os.SystemClock;
39import android.util.TimeUtils;
40import android.view.Display;
41import android.view.IWindowFocusObserver;
42import android.view.IWindowId;
43import com.android.server.input.InputWindowHandle;
44
45import android.content.Context;
46import android.content.res.Configuration;
47import android.graphics.Matrix;
48import android.graphics.PixelFormat;
49import android.graphics.Rect;
50import android.graphics.RectF;
51import android.graphics.Region;
52import android.os.IBinder;
53import android.os.RemoteException;
54import android.os.UserHandle;
55import android.util.Slog;
56import android.view.DisplayInfo;
57import android.view.Gravity;
58import android.view.IApplicationToken;
59import android.view.IWindow;
60import android.view.InputChannel;
61import android.view.View;
62import android.view.ViewTreeObserver;
63import android.view.WindowManager;
64import android.view.WindowManagerPolicy;
65
66import java.io.PrintWriter;
67import java.util.ArrayList;
68
69class WindowList extends ArrayList<WindowState> {
70}
71
72/**
73 * A window in the window manager.
74 */
75final class WindowState implements WindowManagerPolicy.WindowState {
76    static final String TAG = "WindowState";
77
78    final WindowManagerService mService;
79    final WindowManagerPolicy mPolicy;
80    final Context mContext;
81    final Session mSession;
82    final IWindow mClient;
83    final int mAppOp;
84    // UserId and appId of the owner. Don't display windows of non-current user.
85    final int mOwnerUid;
86    final IWindowId mWindowId;
87    WindowToken mToken;
88    WindowToken mRootToken;
89    AppWindowToken mAppToken;
90    AppWindowToken mTargetAppToken;
91
92    // mAttrs.flags is tested in animation without being locked. If the bits tested are ever
93    // modified they will need to be locked.
94    final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
95    final DeathRecipient mDeathRecipient;
96    final WindowState mAttachedWindow;
97    final WindowList mChildWindows = new WindowList();
98    final int mBaseLayer;
99    final int mSubLayer;
100    final boolean mLayoutAttached;
101    final boolean mIsImWindow;
102    final boolean mIsWallpaper;
103    final boolean mIsFloatingLayer;
104    int mSeq;
105    boolean mEnforceSizeCompat;
106    int mViewVisibility;
107    int mSystemUiVisibility;
108    boolean mPolicyVisibility = true;
109    boolean mPolicyVisibilityAfterAnim = true;
110    boolean mAppOpVisibility = true;
111    boolean mAppFreezing;
112    boolean mAttachedHidden;    // is our parent window hidden?
113    boolean mWallpaperVisible;  // for wallpaper, what was last vis report?
114
115    RemoteCallbackList<IWindowFocusObserver> mFocusCallbacks;
116
117    /**
118     * The window size that was requested by the application.  These are in
119     * the application's coordinate space (without compatibility scale applied).
120     */
121    int mRequestedWidth;
122    int mRequestedHeight;
123    int mLastRequestedWidth;
124    int mLastRequestedHeight;
125
126    int mLayer;
127    boolean mHaveFrame;
128    boolean mObscured;
129    boolean mTurnOnScreen;
130
131    int mLayoutSeq = -1;
132
133    Configuration mConfiguration = null;
134    // Sticky answer to isConfigChanged(), remains true until new Configuration is assigned.
135    // Used only on {@link #TYPE_KEYGUARD}.
136    private boolean mConfigHasChanged;
137
138    /**
139     * Actual frame shown on-screen (may be modified by animation).  These
140     * are in the screen's coordinate space (WITH the compatibility scale
141     * applied).
142     */
143    final RectF mShownFrame = new RectF();
144
145    /**
146     * Insets that determine the actually visible area.  These are in the application's
147     * coordinate space (without compatibility scale applied).
148     */
149    final Rect mVisibleInsets = new Rect();
150    final Rect mLastVisibleInsets = new Rect();
151    boolean mVisibleInsetsChanged;
152
153    /**
154     * Insets that are covered by system windows (such as the status bar) and
155     * transient docking windows (such as the IME).  These are in the application's
156     * coordinate space (without compatibility scale applied).
157     */
158    final Rect mContentInsets = new Rect();
159    final Rect mLastContentInsets = new Rect();
160    boolean mContentInsetsChanged;
161
162    /**
163     * Insets that determine the area covered by the display overscan region.  These are in the
164     * application's coordinate space (without compatibility scale applied).
165     */
166    final Rect mOverscanInsets = new Rect();
167    final Rect mLastOverscanInsets = new Rect();
168    boolean mOverscanInsetsChanged;
169
170    /**
171     * Insets that determine the area covered by the stable system windows.  These are in the
172     * application's coordinate space (without compatibility scale applied).
173     */
174    final Rect mStableInsets = new Rect();
175    final Rect mLastStableInsets = new Rect();
176    boolean mStableInsetsChanged;
177
178    /**
179     * Set to true if we are waiting for this window to receive its
180     * given internal insets before laying out other windows based on it.
181     */
182    boolean mGivenInsetsPending;
183
184    /**
185     * These are the content insets that were given during layout for
186     * this window, to be applied to windows behind it.
187     */
188    final Rect mGivenContentInsets = new Rect();
189
190    /**
191     * These are the visible insets that were given during layout for
192     * this window, to be applied to windows behind it.
193     */
194    final Rect mGivenVisibleInsets = new Rect();
195
196    /**
197     * This is the given touchable area relative to the window frame, or null if none.
198     */
199    final Region mGivenTouchableRegion = new Region();
200
201    /**
202     * Flag indicating whether the touchable region should be adjusted by
203     * the visible insets; if false the area outside the visible insets is
204     * NOT touchable, so we must use those to adjust the frame during hit
205     * tests.
206     */
207    int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
208
209    /**
210     * This is rectangle of the window's surface that is not covered by
211     * system decorations.
212     */
213    final Rect mSystemDecorRect = new Rect();
214    final Rect mLastSystemDecorRect = new Rect();
215
216    // Current transformation being applied.
217    float mGlobalScale=1;
218    float mInvGlobalScale=1;
219    float mHScale=1, mVScale=1;
220    float mLastHScale=1, mLastVScale=1;
221    final Matrix mTmpMatrix = new Matrix();
222
223    // "Real" frame that the application sees, in display coordinate space.
224    final Rect mFrame = new Rect();
225    final Rect mLastFrame = new Rect();
226    // Frame that is scaled to the application's coordinate space when in
227    // screen size compatibility mode.
228    final Rect mCompatFrame = new Rect();
229
230    final Rect mContainingFrame = new Rect();
231
232    final Rect mParentFrame = new Rect();
233
234    // The entire screen area of the device.
235    final Rect mDisplayFrame = new Rect();
236
237    // The region of the display frame that the display type supports displaying content on. This
238    // is mostly a special case for TV where some displays don’t have the entire display usable.
239    // {@link WindowManager.LayoutParams#FLAG_LAYOUT_IN_OVERSCAN} flag can be used to allow
240    // window display contents to extend into the overscan region.
241    final Rect mOverscanFrame = new Rect();
242
243    // The display frame minus the stable insets. This value is always constant regardless of if
244    // the status bar or navigation bar is visible.
245    final Rect mStableFrame = new Rect();
246
247    // The area not occupied by the status and navigation bars. So, if both status and navigation
248    // bars are visible, the decor frame is equal to the stable frame.
249    final Rect mDecorFrame = new Rect();
250
251    // Equal to the decor frame if the IME (e.g. keyboard) is not present. Equal to the decor frame
252    // minus the area occupied by the IME if the IME is present.
253    final Rect mContentFrame = new Rect();
254
255    // Legacy stuff. Generally equal to the content frame expect when the IME for older apps
256    // displays hint text.
257    final Rect mVisibleFrame = new Rect();
258
259    boolean mContentChanged;
260
261    // If a window showing a wallpaper: the requested offset for the
262    // wallpaper; if a wallpaper window: the currently applied offset.
263    float mWallpaperX = -1;
264    float mWallpaperY = -1;
265
266    // If a window showing a wallpaper: what fraction of the offset
267    // range corresponds to a full virtual screen.
268    float mWallpaperXStep = -1;
269    float mWallpaperYStep = -1;
270
271    // If a window showing a wallpaper: a raw pixel offset to forcibly apply
272    // to its window; if a wallpaper window: not used.
273    int mWallpaperDisplayOffsetX = Integer.MIN_VALUE;
274    int mWallpaperDisplayOffsetY = Integer.MIN_VALUE;
275
276    // Wallpaper windows: pixels offset based on above variables.
277    int mXOffset;
278    int mYOffset;
279
280    /**
281     * This is set after IWindowSession.relayout() has been called at
282     * least once for the window.  It allows us to detect the situation
283     * where we don't yet have a surface, but should have one soon, so
284     * we can give the window focus before waiting for the relayout.
285     */
286    boolean mRelayoutCalled;
287
288    /**
289     * If the application has called relayout() with changes that can
290     * impact its window's size, we need to perform a layout pass on it
291     * even if it is not currently visible for layout.  This is set
292     * when in that case until the layout is done.
293     */
294    boolean mLayoutNeeded;
295
296    /** Currently running an exit animation? */
297    boolean mExiting;
298
299    /** Currently on the mDestroySurface list? */
300    boolean mDestroying;
301
302    /** Completely remove from window manager after exit animation? */
303    boolean mRemoveOnExit;
304
305    /**
306     * Set when the orientation is changing and this window has not yet
307     * been updated for the new orientation.
308     */
309    boolean mOrientationChanging;
310
311    /**
312     * How long we last kept the screen frozen.
313     */
314    int mLastFreezeDuration;
315
316    /** Is this window now (or just being) removed? */
317    boolean mRemoved;
318
319    /**
320     * Temp for keeping track of windows that have been removed when
321     * rebuilding window list.
322     */
323    boolean mRebuilding;
324
325    // Input channel and input window handle used by the input dispatcher.
326    final InputWindowHandle mInputWindowHandle;
327    InputChannel mInputChannel;
328
329    // Used to improve performance of toString()
330    String mStringNameCache;
331    CharSequence mLastTitle;
332    boolean mWasExiting;
333
334    final WindowStateAnimator mWinAnimator;
335
336    boolean mHasSurface = false;
337
338    boolean mNotOnAppsDisplay = false;
339    DisplayContent  mDisplayContent;
340
341    /** When true this window can be displayed on screens owther than mOwnerUid's */
342    private boolean mShowToOwnerOnly;
343
344    /** When true this window is at the top of the screen and should be layed out to extend under
345     * the status bar */
346    boolean mUnderStatusBar = true;
347
348    WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,
349           WindowState attachedWindow, int appOp, int seq, WindowManager.LayoutParams a,
350           int viewVisibility, final DisplayContent displayContent) {
351        mService = service;
352        mSession = s;
353        mClient = c;
354        mAppOp = appOp;
355        mToken = token;
356        mOwnerUid = s.mUid;
357        mWindowId = new IWindowId.Stub() {
358            @Override
359            public void registerFocusObserver(IWindowFocusObserver observer) {
360                WindowState.this.registerFocusObserver(observer);
361            }
362            @Override
363            public void unregisterFocusObserver(IWindowFocusObserver observer) {
364                WindowState.this.unregisterFocusObserver(observer);
365            }
366            @Override
367            public boolean isFocused() {
368                return WindowState.this.isFocused();
369            }
370        };
371        mAttrs.copyFrom(a);
372        mViewVisibility = viewVisibility;
373        mDisplayContent = displayContent;
374        mPolicy = mService.mPolicy;
375        mContext = mService.mContext;
376        DeathRecipient deathRecipient = new DeathRecipient();
377        mSeq = seq;
378        mEnforceSizeCompat = (mAttrs.privateFlags & PRIVATE_FLAG_COMPATIBLE_WINDOW) != 0;
379        if (WindowManagerService.localLOGV) Slog.v(
380            TAG, "Window " + this + " client=" + c.asBinder()
381            + " token=" + token + " (" + mAttrs.token + ")" + " params=" + a);
382        try {
383            c.asBinder().linkToDeath(deathRecipient, 0);
384        } catch (RemoteException e) {
385            mDeathRecipient = null;
386            mAttachedWindow = null;
387            mLayoutAttached = false;
388            mIsImWindow = false;
389            mIsWallpaper = false;
390            mIsFloatingLayer = false;
391            mBaseLayer = 0;
392            mSubLayer = 0;
393            mInputWindowHandle = null;
394            mWinAnimator = null;
395            return;
396        }
397        mDeathRecipient = deathRecipient;
398
399        if ((mAttrs.type >= FIRST_SUB_WINDOW &&
400                mAttrs.type <= LAST_SUB_WINDOW)) {
401            // The multiplier here is to reserve space for multiple
402            // windows in the same type layer.
403            mBaseLayer = mPolicy.windowTypeToLayerLw(
404                    attachedWindow.mAttrs.type) * WindowManagerService.TYPE_LAYER_MULTIPLIER
405                    + WindowManagerService.TYPE_LAYER_OFFSET;
406            mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
407            mAttachedWindow = attachedWindow;
408            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + mAttachedWindow);
409
410            int children_size = mAttachedWindow.mChildWindows.size();
411            if (children_size == 0) {
412                mAttachedWindow.mChildWindows.add(this);
413            } else {
414                for (int i = 0; i < children_size; i++) {
415                    WindowState child = (WindowState)mAttachedWindow.mChildWindows.get(i);
416                    if (this.mSubLayer < child.mSubLayer) {
417                        mAttachedWindow.mChildWindows.add(i, this);
418                        break;
419                    } else if (this.mSubLayer > child.mSubLayer) {
420                        continue;
421                    }
422
423                    if (this.mBaseLayer <= child.mBaseLayer) {
424                        mAttachedWindow.mChildWindows.add(i, this);
425                        break;
426                    } else {
427                        continue;
428                    }
429                }
430                if (children_size == mAttachedWindow.mChildWindows.size()) {
431                    mAttachedWindow.mChildWindows.add(this);
432                }
433            }
434
435            mLayoutAttached = mAttrs.type !=
436                    WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
437            mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
438                    || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
439            mIsWallpaper = attachedWindow.mAttrs.type == TYPE_WALLPAPER;
440            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
441        } else {
442            // The multiplier here is to reserve space for multiple
443            // windows in the same type layer.
444            mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
445                    * WindowManagerService.TYPE_LAYER_MULTIPLIER
446                    + WindowManagerService.TYPE_LAYER_OFFSET;
447            mSubLayer = 0;
448            mAttachedWindow = null;
449            mLayoutAttached = false;
450            mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
451                    || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
452            mIsWallpaper = mAttrs.type == TYPE_WALLPAPER;
453            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
454        }
455
456        WindowState appWin = this;
457        while (appWin.mAttachedWindow != null) {
458            appWin = appWin.mAttachedWindow;
459        }
460        WindowToken appToken = appWin.mToken;
461        while (appToken.appWindowToken == null) {
462            WindowToken parent = mService.mTokenMap.get(appToken.token);
463            if (parent == null || appToken == parent) {
464                break;
465            }
466            appToken = parent;
467        }
468        mRootToken = appToken;
469        mAppToken = appToken.appWindowToken;
470        if (mAppToken != null) {
471            final DisplayContent appDisplay = getDisplayContent();
472            mNotOnAppsDisplay = displayContent != appDisplay;
473        }
474
475        mWinAnimator = new WindowStateAnimator(this);
476        mWinAnimator.mAlpha = a.alpha;
477
478        mRequestedWidth = 0;
479        mRequestedHeight = 0;
480        mLastRequestedWidth = 0;
481        mLastRequestedHeight = 0;
482        mXOffset = 0;
483        mYOffset = 0;
484        mLayer = 0;
485        mInputWindowHandle = new InputWindowHandle(
486                mAppToken != null ? mAppToken.mInputApplicationHandle : null, this,
487                displayContent.getDisplayId());
488    }
489
490    void attach() {
491        if (WindowManagerService.localLOGV) Slog.v(
492            TAG, "Attaching " + this + " token=" + mToken
493            + ", list=" + mToken.windows);
494        mSession.windowAddedLocked();
495    }
496
497    @Override
498    public int getOwningUid() {
499        return mOwnerUid;
500    }
501
502    @Override
503    public String getOwningPackage() {
504        return mAttrs.packageName;
505    }
506
507    @Override
508    public void computeFrameLw(Rect pf, Rect df, Rect of, Rect cf, Rect vf, Rect dcf, Rect sf) {
509        mHaveFrame = true;
510
511        TaskStack stack = mAppToken != null ? getStack() : null;
512        if (stack != null && !stack.isFullscreen()) {
513            getStackBounds(stack, mContainingFrame);
514            if (mUnderStatusBar) {
515                mContainingFrame.top = pf.top;
516            }
517        } else {
518            mContainingFrame.set(pf);
519        }
520
521        mDisplayFrame.set(df);
522
523        final int pw = mContainingFrame.width();
524        final int ph = mContainingFrame.height();
525
526        int w,h;
527        if ((mAttrs.flags & WindowManager.LayoutParams.FLAG_SCALED) != 0) {
528            if (mAttrs.width < 0) {
529                w = pw;
530            } else if (mEnforceSizeCompat) {
531                w = (int)(mAttrs.width * mGlobalScale + .5f);
532            } else {
533                w = mAttrs.width;
534            }
535            if (mAttrs.height < 0) {
536                h = ph;
537            } else if (mEnforceSizeCompat) {
538                h = (int)(mAttrs.height * mGlobalScale + .5f);
539            } else {
540                h = mAttrs.height;
541            }
542        } else {
543            if (mAttrs.width == WindowManager.LayoutParams.MATCH_PARENT) {
544                w = pw;
545            } else if (mEnforceSizeCompat) {
546                w = (int)(mRequestedWidth * mGlobalScale + .5f);
547            } else {
548                w = mRequestedWidth;
549            }
550            if (mAttrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
551                h = ph;
552            } else if (mEnforceSizeCompat) {
553                h = (int)(mRequestedHeight * mGlobalScale + .5f);
554            } else {
555                h = mRequestedHeight;
556            }
557        }
558
559        if (!mParentFrame.equals(pf)) {
560            //Slog.i(TAG, "Window " + this + " content frame from " + mParentFrame
561            //        + " to " + pf);
562            mParentFrame.set(pf);
563            mContentChanged = true;
564        }
565        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
566            mLastRequestedWidth = mRequestedWidth;
567            mLastRequestedHeight = mRequestedHeight;
568            mContentChanged = true;
569        }
570
571        mOverscanFrame.set(of);
572        mContentFrame.set(cf);
573        mVisibleFrame.set(vf);
574        mDecorFrame.set(dcf);
575        mStableFrame.set(sf);
576
577        final int fw = mFrame.width();
578        final int fh = mFrame.height();
579
580        //System.out.println("In: w=" + w + " h=" + h + " container=" +
581        //                   container + " x=" + mAttrs.x + " y=" + mAttrs.y);
582
583        float x, y;
584        if (mEnforceSizeCompat) {
585            x = mAttrs.x * mGlobalScale;
586            y = mAttrs.y * mGlobalScale;
587        } else {
588            x = mAttrs.x;
589            y = mAttrs.y;
590        }
591
592        Gravity.apply(mAttrs.gravity, w, h, mContainingFrame,
593                (int) (x + mAttrs.horizontalMargin * pw),
594                (int) (y + mAttrs.verticalMargin * ph), mFrame);
595
596        //System.out.println("Out: " + mFrame);
597
598        // Now make sure the window fits in the overall display.
599        Gravity.applyDisplay(mAttrs.gravity, df, mFrame);
600
601        // Make sure the content and visible frames are inside of the
602        // final window frame.
603        mContentFrame.set(Math.max(mContentFrame.left, mFrame.left),
604                Math.max(mContentFrame.top, mFrame.top),
605                Math.min(mContentFrame.right, mFrame.right),
606                Math.min(mContentFrame.bottom, mFrame.bottom));
607
608        mVisibleFrame.set(Math.max(mVisibleFrame.left, mFrame.left),
609                Math.max(mVisibleFrame.top, mFrame.top),
610                Math.min(mVisibleFrame.right, mFrame.right),
611                Math.min(mVisibleFrame.bottom, mFrame.bottom));
612
613        mStableFrame.set(Math.max(mStableFrame.left, mFrame.left),
614                Math.max(mStableFrame.top, mFrame.top),
615                Math.min(mStableFrame.right, mFrame.right),
616                Math.min(mStableFrame.bottom, mFrame.bottom));
617
618        mOverscanInsets.set(Math.max(mOverscanFrame.left - mFrame.left, 0),
619                Math.max(mOverscanFrame.top - mFrame.top, 0),
620                Math.max(mFrame.right - mOverscanFrame.right, 0),
621                Math.max(mFrame.bottom - mOverscanFrame.bottom, 0));
622
623        mContentInsets.set(mContentFrame.left - mFrame.left,
624                mContentFrame.top - mFrame.top,
625                mFrame.right - mContentFrame.right,
626                mFrame.bottom - mContentFrame.bottom);
627
628        mVisibleInsets.set(mVisibleFrame.left - mFrame.left,
629                mVisibleFrame.top - mFrame.top,
630                mFrame.right - mVisibleFrame.right,
631                mFrame.bottom - mVisibleFrame.bottom);
632
633        mStableInsets.set(Math.max(mStableFrame.left - mFrame.left, 0),
634                Math.max(mStableFrame.top - mFrame.top, 0),
635                Math.max(mFrame.right - mStableFrame.right, 0),
636                Math.max(mFrame.bottom - mStableFrame.bottom, 0));
637
638        mCompatFrame.set(mFrame);
639        if (mEnforceSizeCompat) {
640            // If there is a size compatibility scale being applied to the
641            // window, we need to apply this to its insets so that they are
642            // reported to the app in its coordinate space.
643            mOverscanInsets.scale(mInvGlobalScale);
644            mContentInsets.scale(mInvGlobalScale);
645            mVisibleInsets.scale(mInvGlobalScale);
646            mStableInsets.scale(mInvGlobalScale);
647
648            // Also the scaled frame that we report to the app needs to be
649            // adjusted to be in its coordinate space.
650            mCompatFrame.scale(mInvGlobalScale);
651        }
652
653        if (mIsWallpaper && (fw != mFrame.width() || fh != mFrame.height())) {
654            final DisplayContent displayContent = getDisplayContent();
655            if (displayContent != null) {
656                final DisplayInfo displayInfo = displayContent.getDisplayInfo();
657                mService.updateWallpaperOffsetLocked(this,
658                        displayInfo.logicalWidth, displayInfo.logicalHeight, false);
659            }
660        }
661
662        if (DEBUG_LAYOUT || WindowManagerService.localLOGV) Slog.v(TAG,
663                "Resolving (mRequestedWidth="
664                + mRequestedWidth + ", mRequestedheight="
665                + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
666                + "): frame=" + mFrame.toShortString()
667                + " ci=" + mContentInsets.toShortString()
668                + " vi=" + mVisibleInsets.toShortString()
669                + " vi=" + mStableInsets.toShortString());
670    }
671
672    @Override
673    public Rect getFrameLw() {
674        return mFrame;
675    }
676
677    @Override
678    public RectF getShownFrameLw() {
679        return mShownFrame;
680    }
681
682    @Override
683    public Rect getDisplayFrameLw() {
684        return mDisplayFrame;
685    }
686
687    @Override
688    public Rect getOverscanFrameLw() {
689        return mOverscanFrame;
690    }
691
692    @Override
693    public Rect getContentFrameLw() {
694        return mContentFrame;
695    }
696
697    @Override
698    public Rect getVisibleFrameLw() {
699        return mVisibleFrame;
700    }
701
702    @Override
703    public boolean getGivenInsetsPendingLw() {
704        return mGivenInsetsPending;
705    }
706
707    @Override
708    public Rect getGivenContentInsetsLw() {
709        return mGivenContentInsets;
710    }
711
712    @Override
713    public Rect getGivenVisibleInsetsLw() {
714        return mGivenVisibleInsets;
715    }
716
717    @Override
718    public WindowManager.LayoutParams getAttrs() {
719        return mAttrs;
720    }
721
722    @Override
723    public boolean getNeedsMenuLw(WindowManagerPolicy.WindowState bottom) {
724        int index = -1;
725        WindowState ws = this;
726        WindowList windows = getWindowList();
727        while (true) {
728            if (ws.mAttrs.needsMenuKey != WindowManager.LayoutParams.NEEDS_MENU_UNSET) {
729                return ws.mAttrs.needsMenuKey == WindowManager.LayoutParams.NEEDS_MENU_SET_TRUE;
730            }
731            // If we reached the bottom of the range of windows we are considering,
732            // assume no menu is needed.
733            if (ws == bottom) {
734                return false;
735            }
736            // The current window hasn't specified whether menu key is needed;
737            // look behind it.
738            // First, we may need to determine the starting position.
739            if (index < 0) {
740                index = windows.indexOf(ws);
741            }
742            index--;
743            if (index < 0) {
744                return false;
745            }
746            ws = windows.get(index);
747        }
748    }
749
750    @Override
751    public int getSystemUiVisibility() {
752        return mSystemUiVisibility;
753    }
754
755    @Override
756    public int getSurfaceLayer() {
757        return mLayer;
758    }
759
760    @Override
761    public IApplicationToken getAppToken() {
762        return mAppToken != null ? mAppToken.appToken : null;
763    }
764
765    @Override
766    public boolean isVoiceInteraction() {
767        return mAppToken != null ? mAppToken.voiceInteraction : false;
768    }
769
770    boolean setInsetsChanged() {
771        mOverscanInsetsChanged |= !mLastOverscanInsets.equals(mOverscanInsets);
772        mContentInsetsChanged |= !mLastContentInsets.equals(mContentInsets);
773        mVisibleInsetsChanged |= !mLastVisibleInsets.equals(mVisibleInsets);
774        mStableInsetsChanged |= !mLastStableInsets.equals(mStableInsets);
775        return mOverscanInsetsChanged || mContentInsetsChanged || mVisibleInsetsChanged;
776    }
777
778    public DisplayContent getDisplayContent() {
779        if (mAppToken == null || mNotOnAppsDisplay) {
780            return mDisplayContent;
781        }
782        final TaskStack stack = getStack();
783        return stack == null ? mDisplayContent : stack.getDisplayContent();
784    }
785
786    public int getDisplayId() {
787        final DisplayContent displayContent = getDisplayContent();
788        if (displayContent == null) {
789            return -1;
790        }
791        return displayContent.getDisplayId();
792    }
793
794    TaskStack getStack() {
795        AppWindowToken wtoken = mAppToken == null ? mService.mFocusedApp : mAppToken;
796        if (wtoken != null) {
797            Task task = mService.mTaskIdToTask.get(wtoken.groupId);
798            if (task != null) {
799                if (task.mStack != null) {
800                    return task.mStack;
801                }
802                Slog.e(TAG, "getStack: mStack null for task=" + task);
803            } else {
804                Slog.e(TAG, "getStack: " + this + " couldn't find taskId=" + wtoken.groupId
805                    + " Callers=" + Debug.getCallers(4));
806            }
807        }
808        return mDisplayContent.getHomeStack();
809    }
810
811    void getStackBounds(Rect bounds) {
812        getStackBounds(getStack(), bounds);
813    }
814
815    private void getStackBounds(TaskStack stack, Rect bounds) {
816        if (stack != null) {
817            stack.getBounds(bounds);
818            return;
819        }
820        bounds.set(mFrame);
821    }
822
823    public long getInputDispatchingTimeoutNanos() {
824        return mAppToken != null
825                ? mAppToken.inputDispatchingTimeoutNanos
826                : WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
827    }
828
829    @Override
830    public boolean hasAppShownWindows() {
831        return mAppToken != null && (mAppToken.firstWindowDrawn || mAppToken.startingDisplayed);
832    }
833
834    boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
835        if (dsdx < .99999f || dsdx > 1.00001f) return false;
836        if (dtdy < .99999f || dtdy > 1.00001f) return false;
837        if (dtdx < -.000001f || dtdx > .000001f) return false;
838        if (dsdy < -.000001f || dsdy > .000001f) return false;
839        return true;
840    }
841
842    void prelayout() {
843        if (mEnforceSizeCompat) {
844            mGlobalScale = mService.mCompatibleScreenScale;
845            mInvGlobalScale = 1/mGlobalScale;
846        } else {
847            mGlobalScale = mInvGlobalScale = 1;
848        }
849    }
850
851    /**
852     * Is this window visible?  It is not visible if there is no
853     * surface, or we are in the process of running an exit animation
854     * that will remove the surface, or its app token has been hidden.
855     */
856    @Override
857    public boolean isVisibleLw() {
858        final AppWindowToken atoken = mAppToken;
859        return mHasSurface && mPolicyVisibility && !mAttachedHidden
860                && (atoken == null || !atoken.hiddenRequested)
861                && !mExiting && !mDestroying;
862    }
863
864    /**
865     * Like {@link #isVisibleLw}, but also counts a window that is currently
866     * "hidden" behind the keyguard as visible.  This allows us to apply
867     * things like window flags that impact the keyguard.
868     * XXX I am starting to think we need to have ANOTHER visibility flag
869     * for this "hidden behind keyguard" state rather than overloading
870     * mPolicyVisibility.  Ungh.
871     */
872    @Override
873    public boolean isVisibleOrBehindKeyguardLw() {
874        if (mRootToken.waitingToShow &&
875                mService.mAppTransition.isTransitionSet()) {
876            return false;
877        }
878        final AppWindowToken atoken = mAppToken;
879        final boolean animating = atoken != null
880                ? (atoken.mAppAnimator.animation != null) : false;
881        return mHasSurface && !mDestroying && !mExiting
882                && (atoken == null ? mPolicyVisibility : !atoken.hiddenRequested)
883                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
884                                && !mRootToken.hidden)
885                        || mWinAnimator.mAnimation != null || animating);
886    }
887
888    /**
889     * Is this window visible, ignoring its app token?  It is not visible
890     * if there is no surface, or we are in the process of running an exit animation
891     * that will remove the surface.
892     */
893    public boolean isWinVisibleLw() {
894        final AppWindowToken atoken = mAppToken;
895        return mHasSurface && mPolicyVisibility && !mAttachedHidden
896                && (atoken == null || !atoken.hiddenRequested || atoken.mAppAnimator.animating)
897                && !mExiting && !mDestroying;
898    }
899
900    /**
901     * The same as isVisible(), but follows the current hidden state of
902     * the associated app token, not the pending requested hidden state.
903     */
904    boolean isVisibleNow() {
905        return mHasSurface && mPolicyVisibility && !mAttachedHidden
906                && (!mRootToken.hidden || mAttrs.type == TYPE_APPLICATION_STARTING)
907                && !mExiting && !mDestroying;
908    }
909
910    /**
911     * Can this window possibly be a drag/drop target?  The test here is
912     * a combination of the above "visible now" with the check that the
913     * Input Manager uses when discarding windows from input consideration.
914     */
915    boolean isPotentialDragTarget() {
916        return isVisibleNow() && !mRemoved
917                && mInputChannel != null && mInputWindowHandle != null;
918    }
919
920    /**
921     * Same as isVisible(), but we also count it as visible between the
922     * call to IWindowSession.add() and the first relayout().
923     */
924    boolean isVisibleOrAdding() {
925        final AppWindowToken atoken = mAppToken;
926        return (mHasSurface || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
927                && mPolicyVisibility && !mAttachedHidden
928                && (atoken == null || !atoken.hiddenRequested)
929                && !mExiting && !mDestroying;
930    }
931
932    /**
933     * Is this window currently on-screen?  It is on-screen either if it
934     * is visible or it is currently running an animation before no longer
935     * being visible.
936     */
937    boolean isOnScreen() {
938        if (!mHasSurface || !mPolicyVisibility || mDestroying) {
939            return false;
940        }
941        final AppWindowToken atoken = mAppToken;
942        if (atoken != null) {
943            return ((!mAttachedHidden && !atoken.hiddenRequested)
944                    || mWinAnimator.mAnimation != null || atoken.mAppAnimator.animation != null);
945        }
946        return !mAttachedHidden || mWinAnimator.mAnimation != null;
947    }
948
949    /**
950     * Like isOnScreen(), but we don't return true if the window is part
951     * of a transition that has not yet been started.
952     */
953    boolean isReadyForDisplay() {
954        if (mRootToken.waitingToShow &&
955                mService.mAppTransition.isTransitionSet()) {
956            return false;
957        }
958        return mHasSurface && mPolicyVisibility && !mDestroying
959                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
960                                && !mRootToken.hidden)
961                        || mWinAnimator.mAnimation != null
962                        || ((mAppToken != null) && (mAppToken.mAppAnimator.animation != null)));
963    }
964
965    /**
966     * Like isReadyForDisplay(), but ignores any force hiding of the window due
967     * to the keyguard.
968     */
969    boolean isReadyForDisplayIgnoringKeyguard() {
970        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
971            return false;
972        }
973        final AppWindowToken atoken = mAppToken;
974        if (atoken == null && !mPolicyVisibility) {
975            // If this is not an app window, and the policy has asked to force
976            // hide, then we really do want to hide.
977            return false;
978        }
979        return mHasSurface && !mDestroying
980                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
981                                && !mRootToken.hidden)
982                        || mWinAnimator.mAnimation != null
983                        || ((atoken != null) && (atoken.mAppAnimator.animation != null)
984                                && !mWinAnimator.isDummyAnimation()));
985    }
986
987    /**
988     * Like isOnScreen, but returns false if the surface hasn't yet
989     * been drawn.
990     */
991    @Override
992    public boolean isDisplayedLw() {
993        final AppWindowToken atoken = mAppToken;
994        return isDrawnLw() && mPolicyVisibility
995            && ((!mAttachedHidden &&
996                    (atoken == null || !atoken.hiddenRequested))
997                        || mWinAnimator.mAnimating
998                        || (atoken != null && atoken.mAppAnimator.animation != null));
999    }
1000
1001    /**
1002     * Return true if this window or its app token is currently animating.
1003     */
1004    @Override
1005    public boolean isAnimatingLw() {
1006        return mWinAnimator.mAnimation != null
1007                || (mAppToken != null && mAppToken.mAppAnimator.animation != null);
1008    }
1009
1010    @Override
1011    public boolean isGoneForLayoutLw() {
1012        final AppWindowToken atoken = mAppToken;
1013        return mViewVisibility == View.GONE
1014                || !mRelayoutCalled
1015                || (atoken == null && mRootToken.hidden)
1016                || (atoken != null && (atoken.hiddenRequested || atoken.hidden))
1017                || mAttachedHidden
1018                || (mExiting && !isAnimatingLw())
1019                || mDestroying;
1020    }
1021
1022    /**
1023     * Returns true if the window has a surface that it has drawn a
1024     * complete UI in to.
1025     */
1026    public boolean isDrawFinishedLw() {
1027        return mHasSurface && !mDestroying &&
1028                (mWinAnimator.mDrawState == WindowStateAnimator.COMMIT_DRAW_PENDING
1029                || mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1030                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1031    }
1032
1033    /**
1034     * Returns true if the window has a surface that it has drawn a
1035     * complete UI in to.
1036     */
1037    public boolean isDrawnLw() {
1038        return mHasSurface && !mDestroying &&
1039                (mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1040                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1041    }
1042
1043    /**
1044     * Return true if the window is opaque and fully drawn.  This indicates
1045     * it may obscure windows behind it.
1046     */
1047    boolean isOpaqueDrawn() {
1048        return (mAttrs.format == PixelFormat.OPAQUE
1049                        || mAttrs.type == TYPE_WALLPAPER)
1050                && isDrawnLw() && mWinAnimator.mAnimation == null
1051                && (mAppToken == null || mAppToken.mAppAnimator.animation == null);
1052    }
1053
1054    /**
1055     * Return whether this window is wanting to have a translation
1056     * animation applied to it for an in-progress move.  (Only makes
1057     * sense to call from performLayoutAndPlaceSurfacesLockedInner().)
1058     */
1059    boolean shouldAnimateMove() {
1060        return mContentChanged && !mExiting && !mWinAnimator.mLastHidden && mService.okToDisplay()
1061                && (mFrame.top != mLastFrame.top
1062                        || mFrame.left != mLastFrame.left)
1063                && (mAttrs.privateFlags&PRIVATE_FLAG_NO_MOVE_ANIMATION) == 0
1064                && (mAttachedWindow == null || !mAttachedWindow.shouldAnimateMove());
1065    }
1066
1067    boolean isFullscreen(int screenWidth, int screenHeight) {
1068        return mFrame.left <= 0 && mFrame.top <= 0 &&
1069                mFrame.right >= screenWidth && mFrame.bottom >= screenHeight;
1070    }
1071
1072    boolean isConfigChanged() {
1073        boolean configChanged = mConfiguration != mService.mCurConfiguration
1074                && (mConfiguration == null
1075                        || (mConfiguration.diff(mService.mCurConfiguration) != 0));
1076
1077        if ((mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
1078            // Retain configuration changed status until resetConfiguration called.
1079            mConfigHasChanged |= configChanged;
1080            configChanged = mConfigHasChanged;
1081        }
1082
1083        return configChanged;
1084    }
1085
1086    void removeLocked() {
1087        disposeInputChannel();
1088
1089        if (mAttachedWindow != null) {
1090            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
1091            mAttachedWindow.mChildWindows.remove(this);
1092        }
1093        mWinAnimator.destroyDeferredSurfaceLocked();
1094        mWinAnimator.destroySurfaceLocked();
1095        mSession.windowRemovedLocked();
1096        try {
1097            mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
1098        } catch (RuntimeException e) {
1099            // Ignore if it has already been removed (usually because
1100            // we are doing this as part of processing a death note.)
1101        }
1102    }
1103
1104    void setConfiguration(final Configuration newConfig) {
1105        mConfiguration = newConfig;
1106        mConfigHasChanged = false;
1107    }
1108
1109    void setInputChannel(InputChannel inputChannel) {
1110        if (mInputChannel != null) {
1111            throw new IllegalStateException("Window already has an input channel.");
1112        }
1113
1114        mInputChannel = inputChannel;
1115        mInputWindowHandle.inputChannel = inputChannel;
1116    }
1117
1118    void disposeInputChannel() {
1119        if (mInputChannel != null) {
1120            mService.mInputManager.unregisterInputChannel(mInputChannel);
1121
1122            mInputChannel.dispose();
1123            mInputChannel = null;
1124        }
1125
1126        mInputWindowHandle.inputChannel = null;
1127    }
1128
1129    private class DeathRecipient implements IBinder.DeathRecipient {
1130        @Override
1131        public void binderDied() {
1132            try {
1133                synchronized(mService.mWindowMap) {
1134                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
1135                    Slog.i(TAG, "WIN DEATH: " + win);
1136                    if (win != null) {
1137                        mService.removeWindowLocked(mSession, win);
1138                    } else if (mHasSurface) {
1139                        Slog.e(TAG, "!!! LEAK !!! Window removed but surface still valid.");
1140                        mService.removeWindowLocked(mSession, WindowState.this);
1141                    }
1142                }
1143            } catch (IllegalArgumentException ex) {
1144                // This will happen if the window has already been
1145                // removed.
1146            }
1147        }
1148    }
1149
1150    /**
1151     * @return true if this window desires key events.
1152     */
1153    public final boolean canReceiveKeys() {
1154        return isVisibleOrAdding()
1155                && (mViewVisibility == View.VISIBLE)
1156                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
1157    }
1158
1159    @Override
1160    public boolean hasDrawnLw() {
1161        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
1162    }
1163
1164    @Override
1165    public boolean showLw(boolean doAnimation) {
1166        return showLw(doAnimation, true);
1167    }
1168
1169    boolean showLw(boolean doAnimation, boolean requestAnim) {
1170        if (isHiddenFromUserLocked()) {
1171            return false;
1172        }
1173        if (!mAppOpVisibility) {
1174            // Being hidden due to app op request.
1175            return false;
1176        }
1177        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
1178            // Already showing.
1179            return false;
1180        }
1181        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
1182        if (doAnimation) {
1183            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
1184                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
1185            if (!mService.okToDisplay()) {
1186                doAnimation = false;
1187            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
1188                // Check for the case where we are currently visible and
1189                // not animating; we do not want to do animation at such a
1190                // point to become visible when we already are.
1191                doAnimation = false;
1192            }
1193        }
1194        mPolicyVisibility = true;
1195        mPolicyVisibilityAfterAnim = true;
1196        if (doAnimation) {
1197            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
1198        }
1199        if (requestAnim) {
1200            mService.scheduleAnimationLocked();
1201        }
1202        return true;
1203    }
1204
1205    @Override
1206    public boolean hideLw(boolean doAnimation) {
1207        return hideLw(doAnimation, true);
1208    }
1209
1210    boolean hideLw(boolean doAnimation, boolean requestAnim) {
1211        if (doAnimation) {
1212            if (!mService.okToDisplay()) {
1213                doAnimation = false;
1214            }
1215        }
1216        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
1217                : mPolicyVisibility;
1218        if (!current) {
1219            // Already hiding.
1220            return false;
1221        }
1222        if (doAnimation) {
1223            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
1224            if (mWinAnimator.mAnimation == null) {
1225                doAnimation = false;
1226            }
1227        }
1228        if (doAnimation) {
1229            mPolicyVisibilityAfterAnim = false;
1230        } else {
1231            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
1232            mPolicyVisibilityAfterAnim = false;
1233            mPolicyVisibility = false;
1234            // Window is no longer visible -- make sure if we were waiting
1235            // for it to be displayed before enabling the display, that
1236            // we allow the display to be enabled now.
1237            mService.enableScreenIfNeededLocked();
1238            if (mService.mCurrentFocus == this) {
1239                if (WindowManagerService.DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1240                        "WindowState.hideLw: setting mFocusMayChange true");
1241                mService.mFocusMayChange = true;
1242            }
1243        }
1244        if (requestAnim) {
1245            mService.scheduleAnimationLocked();
1246        }
1247        return true;
1248    }
1249
1250    public void setAppOpVisibilityLw(boolean state) {
1251        if (mAppOpVisibility != state) {
1252            mAppOpVisibility = state;
1253            if (state) {
1254                // If the policy visibility had last been to hide, then this
1255                // will incorrectly show at this point since we lost that
1256                // information.  Not a big deal -- for the windows that have app
1257                // ops modifies they should only be hidden by policy due to the
1258                // lock screen, and the user won't be changing this if locked.
1259                // Plus it will quickly be fixed the next time we do a layout.
1260                showLw(true, true);
1261            } else {
1262                hideLw(true, true);
1263            }
1264        }
1265    }
1266
1267    @Override
1268    public boolean isAlive() {
1269        return mClient.asBinder().isBinderAlive();
1270    }
1271
1272    boolean isClosing() {
1273        return mExiting || (mService.mClosingApps.contains(mAppToken));
1274    }
1275
1276    @Override
1277    public boolean isDefaultDisplay() {
1278        final DisplayContent displayContent = getDisplayContent();
1279        if (displayContent == null) {
1280            // Only a window that was on a non-default display can be detached from it.
1281            return false;
1282        }
1283        return displayContent.isDefaultDisplay;
1284    }
1285
1286    public void setShowToOwnerOnlyLocked(boolean showToOwnerOnly) {
1287        mShowToOwnerOnly = showToOwnerOnly;
1288    }
1289
1290    boolean isHiddenFromUserLocked() {
1291        // Attached windows are evaluated based on the window that they are attached to.
1292        WindowState win = this;
1293        while (win.mAttachedWindow != null) {
1294            win = win.mAttachedWindow;
1295        }
1296        if (win.mAttrs.type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1297                && win.mAppToken != null && win.mAppToken.showWhenLocked) {
1298            // Save some cycles by not calling getDisplayInfo unless it is an application
1299            // window intended for all users.
1300            final DisplayContent displayContent = win.getDisplayContent();
1301            if (displayContent == null) {
1302                return true;
1303            }
1304            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
1305            if (win.mFrame.left <= 0 && win.mFrame.top <= 0
1306                    && win.mFrame.right >= displayInfo.appWidth
1307                    && win.mFrame.bottom >= displayInfo.appHeight) {
1308                // Is a fullscreen window, like the clock alarm. Show to everyone.
1309                return false;
1310            }
1311        }
1312
1313        return win.mShowToOwnerOnly
1314                && !mService.isCurrentProfileLocked(UserHandle.getUserId(win.mOwnerUid));
1315    }
1316
1317    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
1318        outRegion.set(
1319                frame.left + inset.left, frame.top + inset.top,
1320                frame.right - inset.right, frame.bottom - inset.bottom);
1321    }
1322
1323    public void getTouchableRegion(Region outRegion) {
1324        final Rect frame = mFrame;
1325        switch (mTouchableInsets) {
1326            default:
1327            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME:
1328                outRegion.set(frame);
1329                break;
1330            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT:
1331                applyInsets(outRegion, frame, mGivenContentInsets);
1332                break;
1333            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE:
1334                applyInsets(outRegion, frame, mGivenVisibleInsets);
1335                break;
1336            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION: {
1337                final Region givenTouchableRegion = mGivenTouchableRegion;
1338                outRegion.set(givenTouchableRegion);
1339                outRegion.translate(frame.left, frame.top);
1340                break;
1341            }
1342        }
1343    }
1344
1345    WindowList getWindowList() {
1346        final DisplayContent displayContent = getDisplayContent();
1347        return displayContent == null ? null : displayContent.getWindowList();
1348    }
1349
1350    /**
1351     * Report a focus change.  Must be called with no locks held, and consistently
1352     * from the same serialized thread (such as dispatched from a handler).
1353     */
1354    public void reportFocusChangedSerialized(boolean focused, boolean inTouchMode) {
1355        try {
1356            mClient.windowFocusChanged(focused, inTouchMode);
1357        } catch (RemoteException e) {
1358        }
1359        if (mFocusCallbacks != null) {
1360            final int N = mFocusCallbacks.beginBroadcast();
1361            for (int i=0; i<N; i++) {
1362                IWindowFocusObserver obs = mFocusCallbacks.getBroadcastItem(i);
1363                try {
1364                    if (focused) {
1365                        obs.focusGained(mWindowId.asBinder());
1366                    } else {
1367                        obs.focusLost(mWindowId.asBinder());
1368                    }
1369                } catch (RemoteException e) {
1370                }
1371            }
1372            mFocusCallbacks.finishBroadcast();
1373        }
1374    }
1375
1376    void reportResized() {
1377        try {
1378            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
1379                    + ": " + mCompatFrame);
1380            boolean configChanged = isConfigChanged();
1381            if ((DEBUG_RESIZE || DEBUG_ORIENTATION || DEBUG_CONFIGURATION) && configChanged) {
1382                Slog.i(TAG, "Sending new config to window " + this + ": "
1383                        + mWinAnimator.mSurfaceW + "x" + mWinAnimator.mSurfaceH
1384                        + " / " + mService.mCurConfiguration);
1385            }
1386            setConfiguration(mService.mCurConfiguration);
1387            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING)
1388                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
1389
1390            final Rect frame = mFrame;
1391            final Rect overscanInsets = mLastOverscanInsets;
1392            final Rect contentInsets = mLastContentInsets;
1393            final Rect visibleInsets = mLastVisibleInsets;
1394            final Rect stableInsets = mLastStableInsets;
1395            final boolean reportDraw = mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING;
1396            final Configuration newConfig = configChanged ? mConfiguration : null;
1397            if (mAttrs.type != WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
1398                    && mClient instanceof IWindow.Stub) {
1399                // To prevent deadlock simulate one-way call if win.mClient is a local object.
1400                mService.mH.post(new Runnable() {
1401                    @Override
1402                    public void run() {
1403                        try {
1404                            mClient.resized(frame, overscanInsets, contentInsets,
1405                                    visibleInsets, stableInsets,  reportDraw, newConfig);
1406                        } catch (RemoteException e) {
1407                            // Not a remote call, RemoteException won't be raised.
1408                        }
1409                    }
1410                });
1411            } else {
1412                mClient.resized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets,
1413                        reportDraw, newConfig);
1414            }
1415
1416            //TODO (multidisplay): Accessibility supported only for the default display.
1417            if (mService.mAccessibilityController != null
1418                    && getDisplayId() == Display.DEFAULT_DISPLAY) {
1419                mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
1420            }
1421
1422            mOverscanInsetsChanged = false;
1423            mContentInsetsChanged = false;
1424            mVisibleInsetsChanged = false;
1425            mStableInsetsChanged = false;
1426            mWinAnimator.mSurfaceResized = false;
1427        } catch (RemoteException e) {
1428            mOrientationChanging = false;
1429            mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
1430                    - mService.mDisplayFreezeTime);
1431        }
1432    }
1433
1434    public void registerFocusObserver(IWindowFocusObserver observer) {
1435        synchronized(mService.mWindowMap) {
1436            if (mFocusCallbacks == null) {
1437                mFocusCallbacks = new RemoteCallbackList<IWindowFocusObserver>();
1438            }
1439            mFocusCallbacks.register(observer);
1440        }
1441    }
1442
1443    public void unregisterFocusObserver(IWindowFocusObserver observer) {
1444        synchronized(mService.mWindowMap) {
1445            if (mFocusCallbacks != null) {
1446                mFocusCallbacks.unregister(observer);
1447            }
1448        }
1449    }
1450
1451    public boolean isFocused() {
1452        synchronized(mService.mWindowMap) {
1453            return mService.mCurrentFocus == this;
1454        }
1455    }
1456
1457    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1458        pw.print(prefix); pw.print("mDisplayId="); pw.print(getDisplayId());
1459                pw.print(" mSession="); pw.print(mSession);
1460                pw.print(" mClient="); pw.println(mClient.asBinder());
1461        pw.print(prefix); pw.print("mOwnerUid="); pw.print(mOwnerUid);
1462                pw.print(" mShowToOwnerOnly="); pw.print(mShowToOwnerOnly);
1463                pw.print(" package="); pw.print(mAttrs.packageName);
1464                pw.print(" appop="); pw.println(AppOpsManager.opToName(mAppOp));
1465        pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
1466        pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
1467                pw.print(" h="); pw.print(mRequestedHeight);
1468                pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
1469        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
1470            pw.print(prefix); pw.print("LastRequested w="); pw.print(mLastRequestedWidth);
1471                    pw.print(" h="); pw.println(mLastRequestedHeight);
1472        }
1473        if (mAttachedWindow != null || mLayoutAttached) {
1474            pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
1475                    pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
1476        }
1477        if (mIsImWindow || mIsWallpaper || mIsFloatingLayer) {
1478            pw.print(prefix); pw.print("mIsImWindow="); pw.print(mIsImWindow);
1479                    pw.print(" mIsWallpaper="); pw.print(mIsWallpaper);
1480                    pw.print(" mIsFloatingLayer="); pw.print(mIsFloatingLayer);
1481                    pw.print(" mWallpaperVisible="); pw.println(mWallpaperVisible);
1482        }
1483        if (dumpAll) {
1484            pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
1485                    pw.print(" mSubLayer="); pw.print(mSubLayer);
1486                    pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
1487                    pw.print((mTargetAppToken != null ?
1488                            mTargetAppToken.mAppAnimator.animLayerAdjustment
1489                          : (mAppToken != null ? mAppToken.mAppAnimator.animLayerAdjustment : 0)));
1490                    pw.print("="); pw.print(mWinAnimator.mAnimLayer);
1491                    pw.print(" mLastLayer="); pw.println(mWinAnimator.mLastLayer);
1492        }
1493        if (dumpAll) {
1494            pw.print(prefix); pw.print("mToken="); pw.println(mToken);
1495            pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
1496            if (mAppToken != null) {
1497                pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
1498            }
1499            if (mTargetAppToken != null) {
1500                pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
1501            }
1502            pw.print(prefix); pw.print("mViewVisibility=0x");
1503            pw.print(Integer.toHexString(mViewVisibility));
1504            pw.print(" mHaveFrame="); pw.print(mHaveFrame);
1505            pw.print(" mObscured="); pw.println(mObscured);
1506            pw.print(prefix); pw.print("mSeq="); pw.print(mSeq);
1507            pw.print(" mSystemUiVisibility=0x");
1508            pw.println(Integer.toHexString(mSystemUiVisibility));
1509        }
1510        if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || !mAppOpVisibility
1511                || mAttachedHidden) {
1512            pw.print(prefix); pw.print("mPolicyVisibility=");
1513                    pw.print(mPolicyVisibility);
1514                    pw.print(" mPolicyVisibilityAfterAnim=");
1515                    pw.print(mPolicyVisibilityAfterAnim);
1516                    pw.print(" mAppOpVisibility=");
1517                    pw.print(mAppOpVisibility);
1518                    pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
1519        }
1520        if (!mRelayoutCalled || mLayoutNeeded) {
1521            pw.print(prefix); pw.print("mRelayoutCalled="); pw.print(mRelayoutCalled);
1522                    pw.print(" mLayoutNeeded="); pw.println(mLayoutNeeded);
1523        }
1524        if (mXOffset != 0 || mYOffset != 0) {
1525            pw.print(prefix); pw.print("Offsets x="); pw.print(mXOffset);
1526                    pw.print(" y="); pw.println(mYOffset);
1527        }
1528        if (dumpAll) {
1529            pw.print(prefix); pw.print("mGivenContentInsets=");
1530                    mGivenContentInsets.printShortString(pw);
1531                    pw.print(" mGivenVisibleInsets=");
1532                    mGivenVisibleInsets.printShortString(pw);
1533                    pw.println();
1534            if (mTouchableInsets != 0 || mGivenInsetsPending) {
1535                pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
1536                        pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
1537                Region region = new Region();
1538                getTouchableRegion(region);
1539                pw.print(prefix); pw.print("touchable region="); pw.println(region);
1540            }
1541            pw.print(prefix); pw.print("mConfiguration="); pw.println(mConfiguration);
1542        }
1543        pw.print(prefix); pw.print("mHasSurface="); pw.print(mHasSurface);
1544                pw.print(" mShownFrame="); mShownFrame.printShortString(pw);
1545                pw.print(" isReadyForDisplay()="); pw.println(isReadyForDisplay());
1546        if (dumpAll) {
1547            pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
1548                    pw.print(" last="); mLastFrame.printShortString(pw);
1549                    pw.println();
1550            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
1551                    pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
1552                    pw.println();
1553        }
1554        if (mEnforceSizeCompat) {
1555            pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
1556                    pw.println();
1557        }
1558        if (dumpAll) {
1559            pw.print(prefix); pw.print("Frames: containing=");
1560                    mContainingFrame.printShortString(pw);
1561                    pw.print(" parent="); mParentFrame.printShortString(pw);
1562                    pw.println();
1563            pw.print(prefix); pw.print("    display="); mDisplayFrame.printShortString(pw);
1564                    pw.print(" overscan="); mOverscanFrame.printShortString(pw);
1565                    pw.println();
1566            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
1567                    pw.print(" visible="); mVisibleFrame.printShortString(pw);
1568                    pw.println();
1569            pw.print(prefix); pw.print("    decor="); mDecorFrame.printShortString(pw);
1570                    pw.println();
1571            pw.print(prefix); pw.print("Cur insets: overscan=");
1572                    mOverscanInsets.printShortString(pw);
1573                    pw.print(" content="); mContentInsets.printShortString(pw);
1574                    pw.print(" visible="); mVisibleInsets.printShortString(pw);
1575                    pw.print(" stable="); mStableInsets.printShortString(pw);
1576                    pw.println();
1577            pw.print(prefix); pw.print("Lst insets: overscan=");
1578                    mLastOverscanInsets.printShortString(pw);
1579                    pw.print(" content="); mLastContentInsets.printShortString(pw);
1580                    pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
1581                    pw.print(" stable="); mLastStableInsets.printShortString(pw);
1582                    pw.println();
1583        }
1584        pw.print(prefix); pw.print(mWinAnimator); pw.println(":");
1585        mWinAnimator.dump(pw, prefix + "  ", dumpAll);
1586        if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
1587            pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
1588                    pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
1589                    pw.print(" mDestroying="); pw.print(mDestroying);
1590                    pw.print(" mRemoved="); pw.println(mRemoved);
1591        }
1592        if (mOrientationChanging || mAppFreezing || mTurnOnScreen) {
1593            pw.print(prefix); pw.print("mOrientationChanging=");
1594                    pw.print(mOrientationChanging);
1595                    pw.print(" mAppFreezing="); pw.print(mAppFreezing);
1596                    pw.print(" mTurnOnScreen="); pw.println(mTurnOnScreen);
1597        }
1598        if (mLastFreezeDuration != 0) {
1599            pw.print(prefix); pw.print("mLastFreezeDuration=");
1600                    TimeUtils.formatDuration(mLastFreezeDuration, pw); pw.println();
1601        }
1602        if (mHScale != 1 || mVScale != 1) {
1603            pw.print(prefix); pw.print("mHScale="); pw.print(mHScale);
1604                    pw.print(" mVScale="); pw.println(mVScale);
1605        }
1606        if (mWallpaperX != -1 || mWallpaperY != -1) {
1607            pw.print(prefix); pw.print("mWallpaperX="); pw.print(mWallpaperX);
1608                    pw.print(" mWallpaperY="); pw.println(mWallpaperY);
1609        }
1610        if (mWallpaperXStep != -1 || mWallpaperYStep != -1) {
1611            pw.print(prefix); pw.print("mWallpaperXStep="); pw.print(mWallpaperXStep);
1612                    pw.print(" mWallpaperYStep="); pw.println(mWallpaperYStep);
1613        }
1614        if (mWallpaperDisplayOffsetX != Integer.MIN_VALUE
1615                || mWallpaperDisplayOffsetY != Integer.MIN_VALUE) {
1616            pw.print(prefix); pw.print("mWallpaperDisplayOffsetX=");
1617                    pw.print(mWallpaperDisplayOffsetX);
1618                    pw.print(" mWallpaperDisplayOffsetY=");
1619                    pw.println(mWallpaperDisplayOffsetY);
1620        }
1621    }
1622
1623    String makeInputChannelName() {
1624        return Integer.toHexString(System.identityHashCode(this))
1625            + " " + mAttrs.getTitle();
1626    }
1627
1628    @Override
1629    public String toString() {
1630        CharSequence title = mAttrs.getTitle();
1631        if (title == null || title.length() <= 0) {
1632            title = mAttrs.packageName;
1633        }
1634        if (mStringNameCache == null || mLastTitle != title || mWasExiting != mExiting) {
1635            mLastTitle = title;
1636            mWasExiting = mExiting;
1637            mStringNameCache = "Window{" + Integer.toHexString(System.identityHashCode(this))
1638                    + " u" + UserHandle.getUserId(mSession.mUid)
1639                    + " " + mLastTitle + (mExiting ? " EXITING}" : "}");
1640        }
1641        return mStringNameCache;
1642    }
1643}
1644