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        return mPolicyVisibility && isOnScreenIgnoringKeyguard();
939    }
940
941    /**
942     * Like isOnScreen(), but ignores any force hiding of the window due
943     * to the keyguard.
944     */
945    boolean isOnScreenIgnoringKeyguard() {
946        if (!mHasSurface || mDestroying) {
947            return false;
948        }
949        final AppWindowToken atoken = mAppToken;
950        if (atoken != null) {
951            return ((!mAttachedHidden && !atoken.hiddenRequested)
952                    || mWinAnimator.mAnimation != null || atoken.mAppAnimator.animation != null);
953        }
954        return !mAttachedHidden || mWinAnimator.mAnimation != null;
955    }
956
957    /**
958     * Like isOnScreen(), but we don't return true if the window is part
959     * of a transition that has not yet been started.
960     */
961    boolean isReadyForDisplay() {
962        if (mRootToken.waitingToShow &&
963                mService.mAppTransition.isTransitionSet()) {
964            return false;
965        }
966        return mHasSurface && mPolicyVisibility && !mDestroying
967                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
968                                && !mRootToken.hidden)
969                        || mWinAnimator.mAnimation != null
970                        || ((mAppToken != null) && (mAppToken.mAppAnimator.animation != null)));
971    }
972
973    /**
974     * Like isReadyForDisplay(), but ignores any force hiding of the window due
975     * to the keyguard.
976     */
977    boolean isReadyForDisplayIgnoringKeyguard() {
978        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
979            return false;
980        }
981        final AppWindowToken atoken = mAppToken;
982        if (atoken == null && !mPolicyVisibility) {
983            // If this is not an app window, and the policy has asked to force
984            // hide, then we really do want to hide.
985            return false;
986        }
987        return mHasSurface && !mDestroying
988                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
989                                && !mRootToken.hidden)
990                        || mWinAnimator.mAnimation != null
991                        || ((atoken != null) && (atoken.mAppAnimator.animation != null)
992                                && !mWinAnimator.isDummyAnimation()));
993    }
994
995    /**
996     * Like isOnScreen, but returns false if the surface hasn't yet
997     * been drawn.
998     */
999    @Override
1000    public boolean isDisplayedLw() {
1001        final AppWindowToken atoken = mAppToken;
1002        return isDrawnLw() && mPolicyVisibility
1003            && ((!mAttachedHidden &&
1004                    (atoken == null || !atoken.hiddenRequested))
1005                        || mWinAnimator.mAnimating
1006                        || (atoken != null && atoken.mAppAnimator.animation != null));
1007    }
1008
1009    /**
1010     * Return true if this window or its app token is currently animating.
1011     */
1012    @Override
1013    public boolean isAnimatingLw() {
1014        return mWinAnimator.mAnimation != null
1015                || (mAppToken != null && mAppToken.mAppAnimator.animation != null);
1016    }
1017
1018    @Override
1019    public boolean isGoneForLayoutLw() {
1020        final AppWindowToken atoken = mAppToken;
1021        return mViewVisibility == View.GONE
1022                || !mRelayoutCalled
1023                || (atoken == null && mRootToken.hidden)
1024                || (atoken != null && (atoken.hiddenRequested || atoken.hidden))
1025                || mAttachedHidden
1026                || (mExiting && !isAnimatingLw())
1027                || mDestroying;
1028    }
1029
1030    /**
1031     * Returns true if the window has a surface that it has drawn a
1032     * complete UI in to.
1033     */
1034    public boolean isDrawFinishedLw() {
1035        return mHasSurface && !mDestroying &&
1036                (mWinAnimator.mDrawState == WindowStateAnimator.COMMIT_DRAW_PENDING
1037                || mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1038                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1039    }
1040
1041    /**
1042     * Returns true if the window has a surface that it has drawn a
1043     * complete UI in to.
1044     */
1045    public boolean isDrawnLw() {
1046        return mHasSurface && !mDestroying &&
1047                (mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1048                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1049    }
1050
1051    /**
1052     * Return true if the window is opaque and fully drawn.  This indicates
1053     * it may obscure windows behind it.
1054     */
1055    boolean isOpaqueDrawn() {
1056        return (mAttrs.format == PixelFormat.OPAQUE
1057                        || mAttrs.type == TYPE_WALLPAPER)
1058                && isDrawnLw() && mWinAnimator.mAnimation == null
1059                && (mAppToken == null || mAppToken.mAppAnimator.animation == null);
1060    }
1061
1062    /**
1063     * Return whether this window is wanting to have a translation
1064     * animation applied to it for an in-progress move.  (Only makes
1065     * sense to call from performLayoutAndPlaceSurfacesLockedInner().)
1066     */
1067    boolean shouldAnimateMove() {
1068        return mContentChanged && !mExiting && !mWinAnimator.mLastHidden && mService.okToDisplay()
1069                && (mFrame.top != mLastFrame.top
1070                        || mFrame.left != mLastFrame.left)
1071                && (mAttrs.privateFlags&PRIVATE_FLAG_NO_MOVE_ANIMATION) == 0
1072                && (mAttachedWindow == null || !mAttachedWindow.shouldAnimateMove());
1073    }
1074
1075    boolean isFullscreen(int screenWidth, int screenHeight) {
1076        return mFrame.left <= 0 && mFrame.top <= 0 &&
1077                mFrame.right >= screenWidth && mFrame.bottom >= screenHeight;
1078    }
1079
1080    boolean isConfigChanged() {
1081        boolean configChanged = mConfiguration != mService.mCurConfiguration
1082                && (mConfiguration == null
1083                        || (mConfiguration.diff(mService.mCurConfiguration) != 0));
1084
1085        if ((mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
1086            // Retain configuration changed status until resetConfiguration called.
1087            mConfigHasChanged |= configChanged;
1088            configChanged = mConfigHasChanged;
1089        }
1090
1091        return configChanged;
1092    }
1093
1094    void removeLocked() {
1095        disposeInputChannel();
1096
1097        if (mAttachedWindow != null) {
1098            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
1099            mAttachedWindow.mChildWindows.remove(this);
1100        }
1101        mWinAnimator.destroyDeferredSurfaceLocked();
1102        mWinAnimator.destroySurfaceLocked();
1103        mSession.windowRemovedLocked();
1104        try {
1105            mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
1106        } catch (RuntimeException e) {
1107            // Ignore if it has already been removed (usually because
1108            // we are doing this as part of processing a death note.)
1109        }
1110    }
1111
1112    void setConfiguration(final Configuration newConfig) {
1113        mConfiguration = newConfig;
1114        mConfigHasChanged = false;
1115    }
1116
1117    void setInputChannel(InputChannel inputChannel) {
1118        if (mInputChannel != null) {
1119            throw new IllegalStateException("Window already has an input channel.");
1120        }
1121
1122        mInputChannel = inputChannel;
1123        mInputWindowHandle.inputChannel = inputChannel;
1124    }
1125
1126    void disposeInputChannel() {
1127        if (mInputChannel != null) {
1128            mService.mInputManager.unregisterInputChannel(mInputChannel);
1129
1130            mInputChannel.dispose();
1131            mInputChannel = null;
1132        }
1133
1134        mInputWindowHandle.inputChannel = null;
1135    }
1136
1137    private class DeathRecipient implements IBinder.DeathRecipient {
1138        @Override
1139        public void binderDied() {
1140            try {
1141                synchronized(mService.mWindowMap) {
1142                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
1143                    Slog.i(TAG, "WIN DEATH: " + win);
1144                    if (win != null) {
1145                        mService.removeWindowLocked(mSession, win);
1146                    } else if (mHasSurface) {
1147                        Slog.e(TAG, "!!! LEAK !!! Window removed but surface still valid.");
1148                        mService.removeWindowLocked(mSession, WindowState.this);
1149                    }
1150                }
1151            } catch (IllegalArgumentException ex) {
1152                // This will happen if the window has already been
1153                // removed.
1154            }
1155        }
1156    }
1157
1158    /**
1159     * @return true if this window desires key events.
1160     */
1161    public final boolean canReceiveKeys() {
1162        return isVisibleOrAdding()
1163                && (mViewVisibility == View.VISIBLE)
1164                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
1165    }
1166
1167    @Override
1168    public boolean hasDrawnLw() {
1169        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
1170    }
1171
1172    @Override
1173    public boolean showLw(boolean doAnimation) {
1174        return showLw(doAnimation, true);
1175    }
1176
1177    boolean showLw(boolean doAnimation, boolean requestAnim) {
1178        if (isHiddenFromUserLocked()) {
1179            return false;
1180        }
1181        if (!mAppOpVisibility) {
1182            // Being hidden due to app op request.
1183            return false;
1184        }
1185        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
1186            // Already showing.
1187            return false;
1188        }
1189        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
1190        if (doAnimation) {
1191            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
1192                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
1193            if (!mService.okToDisplay()) {
1194                doAnimation = false;
1195            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
1196                // Check for the case where we are currently visible and
1197                // not animating; we do not want to do animation at such a
1198                // point to become visible when we already are.
1199                doAnimation = false;
1200            }
1201        }
1202        mPolicyVisibility = true;
1203        mPolicyVisibilityAfterAnim = true;
1204        if (doAnimation) {
1205            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
1206        }
1207        if (requestAnim) {
1208            mService.scheduleAnimationLocked();
1209        }
1210        return true;
1211    }
1212
1213    @Override
1214    public boolean hideLw(boolean doAnimation) {
1215        return hideLw(doAnimation, true);
1216    }
1217
1218    boolean hideLw(boolean doAnimation, boolean requestAnim) {
1219        if (doAnimation) {
1220            if (!mService.okToDisplay()) {
1221                doAnimation = false;
1222            }
1223        }
1224        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
1225                : mPolicyVisibility;
1226        if (!current) {
1227            // Already hiding.
1228            return false;
1229        }
1230        if (doAnimation) {
1231            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
1232            if (mWinAnimator.mAnimation == null) {
1233                doAnimation = false;
1234            }
1235        }
1236        if (doAnimation) {
1237            mPolicyVisibilityAfterAnim = false;
1238        } else {
1239            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
1240            mPolicyVisibilityAfterAnim = false;
1241            mPolicyVisibility = false;
1242            // Window is no longer visible -- make sure if we were waiting
1243            // for it to be displayed before enabling the display, that
1244            // we allow the display to be enabled now.
1245            mService.enableScreenIfNeededLocked();
1246            if (mService.mCurrentFocus == this) {
1247                if (WindowManagerService.DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1248                        "WindowState.hideLw: setting mFocusMayChange true");
1249                mService.mFocusMayChange = true;
1250            }
1251        }
1252        if (requestAnim) {
1253            mService.scheduleAnimationLocked();
1254        }
1255        return true;
1256    }
1257
1258    public void setAppOpVisibilityLw(boolean state) {
1259        if (mAppOpVisibility != state) {
1260            mAppOpVisibility = state;
1261            if (state) {
1262                // If the policy visibility had last been to hide, then this
1263                // will incorrectly show at this point since we lost that
1264                // information.  Not a big deal -- for the windows that have app
1265                // ops modifies they should only be hidden by policy due to the
1266                // lock screen, and the user won't be changing this if locked.
1267                // Plus it will quickly be fixed the next time we do a layout.
1268                showLw(true, true);
1269            } else {
1270                hideLw(true, true);
1271            }
1272        }
1273    }
1274
1275    @Override
1276    public boolean isAlive() {
1277        return mClient.asBinder().isBinderAlive();
1278    }
1279
1280    boolean isClosing() {
1281        return mExiting || (mService.mClosingApps.contains(mAppToken));
1282    }
1283
1284    @Override
1285    public boolean isDefaultDisplay() {
1286        final DisplayContent displayContent = getDisplayContent();
1287        if (displayContent == null) {
1288            // Only a window that was on a non-default display can be detached from it.
1289            return false;
1290        }
1291        return displayContent.isDefaultDisplay;
1292    }
1293
1294    public void setShowToOwnerOnlyLocked(boolean showToOwnerOnly) {
1295        mShowToOwnerOnly = showToOwnerOnly;
1296    }
1297
1298    boolean isHiddenFromUserLocked() {
1299        // Attached windows are evaluated based on the window that they are attached to.
1300        WindowState win = this;
1301        while (win.mAttachedWindow != null) {
1302            win = win.mAttachedWindow;
1303        }
1304        if (win.mAttrs.type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1305                && win.mAppToken != null && win.mAppToken.showWhenLocked) {
1306            // Save some cycles by not calling getDisplayInfo unless it is an application
1307            // window intended for all users.
1308            final DisplayContent displayContent = win.getDisplayContent();
1309            if (displayContent == null) {
1310                return true;
1311            }
1312            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
1313            if (win.mFrame.left <= 0 && win.mFrame.top <= 0
1314                    && win.mFrame.right >= displayInfo.appWidth
1315                    && win.mFrame.bottom >= displayInfo.appHeight) {
1316                // Is a fullscreen window, like the clock alarm. Show to everyone.
1317                return false;
1318            }
1319        }
1320
1321        return win.mShowToOwnerOnly
1322                && !mService.isCurrentProfileLocked(UserHandle.getUserId(win.mOwnerUid));
1323    }
1324
1325    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
1326        outRegion.set(
1327                frame.left + inset.left, frame.top + inset.top,
1328                frame.right - inset.right, frame.bottom - inset.bottom);
1329    }
1330
1331    public void getTouchableRegion(Region outRegion) {
1332        final Rect frame = mFrame;
1333        switch (mTouchableInsets) {
1334            default:
1335            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME:
1336                outRegion.set(frame);
1337                break;
1338            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT:
1339                applyInsets(outRegion, frame, mGivenContentInsets);
1340                break;
1341            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE:
1342                applyInsets(outRegion, frame, mGivenVisibleInsets);
1343                break;
1344            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION: {
1345                final Region givenTouchableRegion = mGivenTouchableRegion;
1346                outRegion.set(givenTouchableRegion);
1347                outRegion.translate(frame.left, frame.top);
1348                break;
1349            }
1350        }
1351    }
1352
1353    WindowList getWindowList() {
1354        final DisplayContent displayContent = getDisplayContent();
1355        return displayContent == null ? null : displayContent.getWindowList();
1356    }
1357
1358    /**
1359     * Report a focus change.  Must be called with no locks held, and consistently
1360     * from the same serialized thread (such as dispatched from a handler).
1361     */
1362    public void reportFocusChangedSerialized(boolean focused, boolean inTouchMode) {
1363        try {
1364            mClient.windowFocusChanged(focused, inTouchMode);
1365        } catch (RemoteException e) {
1366        }
1367        if (mFocusCallbacks != null) {
1368            final int N = mFocusCallbacks.beginBroadcast();
1369            for (int i=0; i<N; i++) {
1370                IWindowFocusObserver obs = mFocusCallbacks.getBroadcastItem(i);
1371                try {
1372                    if (focused) {
1373                        obs.focusGained(mWindowId.asBinder());
1374                    } else {
1375                        obs.focusLost(mWindowId.asBinder());
1376                    }
1377                } catch (RemoteException e) {
1378                }
1379            }
1380            mFocusCallbacks.finishBroadcast();
1381        }
1382    }
1383
1384    void reportResized() {
1385        try {
1386            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
1387                    + ": " + mCompatFrame);
1388            boolean configChanged = isConfigChanged();
1389            if ((DEBUG_RESIZE || DEBUG_ORIENTATION || DEBUG_CONFIGURATION) && configChanged) {
1390                Slog.i(TAG, "Sending new config to window " + this + ": "
1391                        + mWinAnimator.mSurfaceW + "x" + mWinAnimator.mSurfaceH
1392                        + " / " + mService.mCurConfiguration);
1393            }
1394            setConfiguration(mService.mCurConfiguration);
1395            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING)
1396                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
1397
1398            final Rect frame = mFrame;
1399            final Rect overscanInsets = mLastOverscanInsets;
1400            final Rect contentInsets = mLastContentInsets;
1401            final Rect visibleInsets = mLastVisibleInsets;
1402            final Rect stableInsets = mLastStableInsets;
1403            final boolean reportDraw = mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING;
1404            final Configuration newConfig = configChanged ? mConfiguration : null;
1405            if (mAttrs.type != WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
1406                    && mClient instanceof IWindow.Stub) {
1407                // To prevent deadlock simulate one-way call if win.mClient is a local object.
1408                mService.mH.post(new Runnable() {
1409                    @Override
1410                    public void run() {
1411                        try {
1412                            mClient.resized(frame, overscanInsets, contentInsets,
1413                                    visibleInsets, stableInsets,  reportDraw, newConfig);
1414                        } catch (RemoteException e) {
1415                            // Not a remote call, RemoteException won't be raised.
1416                        }
1417                    }
1418                });
1419            } else {
1420                mClient.resized(frame, overscanInsets, contentInsets, visibleInsets, stableInsets,
1421                        reportDraw, newConfig);
1422            }
1423
1424            //TODO (multidisplay): Accessibility supported only for the default display.
1425            if (mService.mAccessibilityController != null
1426                    && getDisplayId() == Display.DEFAULT_DISPLAY) {
1427                mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
1428            }
1429
1430            mOverscanInsetsChanged = false;
1431            mContentInsetsChanged = false;
1432            mVisibleInsetsChanged = false;
1433            mStableInsetsChanged = false;
1434            mWinAnimator.mSurfaceResized = false;
1435        } catch (RemoteException e) {
1436            mOrientationChanging = false;
1437            mLastFreezeDuration = (int)(SystemClock.elapsedRealtime()
1438                    - mService.mDisplayFreezeTime);
1439        }
1440    }
1441
1442    public void registerFocusObserver(IWindowFocusObserver observer) {
1443        synchronized(mService.mWindowMap) {
1444            if (mFocusCallbacks == null) {
1445                mFocusCallbacks = new RemoteCallbackList<IWindowFocusObserver>();
1446            }
1447            mFocusCallbacks.register(observer);
1448        }
1449    }
1450
1451    public void unregisterFocusObserver(IWindowFocusObserver observer) {
1452        synchronized(mService.mWindowMap) {
1453            if (mFocusCallbacks != null) {
1454                mFocusCallbacks.unregister(observer);
1455            }
1456        }
1457    }
1458
1459    public boolean isFocused() {
1460        synchronized(mService.mWindowMap) {
1461            return mService.mCurrentFocus == this;
1462        }
1463    }
1464
1465    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1466        pw.print(prefix); pw.print("mDisplayId="); pw.print(getDisplayId());
1467                pw.print(" mSession="); pw.print(mSession);
1468                pw.print(" mClient="); pw.println(mClient.asBinder());
1469        pw.print(prefix); pw.print("mOwnerUid="); pw.print(mOwnerUid);
1470                pw.print(" mShowToOwnerOnly="); pw.print(mShowToOwnerOnly);
1471                pw.print(" package="); pw.print(mAttrs.packageName);
1472                pw.print(" appop="); pw.println(AppOpsManager.opToName(mAppOp));
1473        pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
1474        pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
1475                pw.print(" h="); pw.print(mRequestedHeight);
1476                pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
1477        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
1478            pw.print(prefix); pw.print("LastRequested w="); pw.print(mLastRequestedWidth);
1479                    pw.print(" h="); pw.println(mLastRequestedHeight);
1480        }
1481        if (mAttachedWindow != null || mLayoutAttached) {
1482            pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
1483                    pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
1484        }
1485        if (mIsImWindow || mIsWallpaper || mIsFloatingLayer) {
1486            pw.print(prefix); pw.print("mIsImWindow="); pw.print(mIsImWindow);
1487                    pw.print(" mIsWallpaper="); pw.print(mIsWallpaper);
1488                    pw.print(" mIsFloatingLayer="); pw.print(mIsFloatingLayer);
1489                    pw.print(" mWallpaperVisible="); pw.println(mWallpaperVisible);
1490        }
1491        if (dumpAll) {
1492            pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
1493                    pw.print(" mSubLayer="); pw.print(mSubLayer);
1494                    pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
1495                    pw.print((mTargetAppToken != null ?
1496                            mTargetAppToken.mAppAnimator.animLayerAdjustment
1497                          : (mAppToken != null ? mAppToken.mAppAnimator.animLayerAdjustment : 0)));
1498                    pw.print("="); pw.print(mWinAnimator.mAnimLayer);
1499                    pw.print(" mLastLayer="); pw.println(mWinAnimator.mLastLayer);
1500        }
1501        if (dumpAll) {
1502            pw.print(prefix); pw.print("mToken="); pw.println(mToken);
1503            pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
1504            if (mAppToken != null) {
1505                pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
1506            }
1507            if (mTargetAppToken != null) {
1508                pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
1509            }
1510            pw.print(prefix); pw.print("mViewVisibility=0x");
1511            pw.print(Integer.toHexString(mViewVisibility));
1512            pw.print(" mHaveFrame="); pw.print(mHaveFrame);
1513            pw.print(" mObscured="); pw.println(mObscured);
1514            pw.print(prefix); pw.print("mSeq="); pw.print(mSeq);
1515            pw.print(" mSystemUiVisibility=0x");
1516            pw.println(Integer.toHexString(mSystemUiVisibility));
1517        }
1518        if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || !mAppOpVisibility
1519                || mAttachedHidden) {
1520            pw.print(prefix); pw.print("mPolicyVisibility=");
1521                    pw.print(mPolicyVisibility);
1522                    pw.print(" mPolicyVisibilityAfterAnim=");
1523                    pw.print(mPolicyVisibilityAfterAnim);
1524                    pw.print(" mAppOpVisibility=");
1525                    pw.print(mAppOpVisibility);
1526                    pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
1527        }
1528        if (!mRelayoutCalled || mLayoutNeeded) {
1529            pw.print(prefix); pw.print("mRelayoutCalled="); pw.print(mRelayoutCalled);
1530                    pw.print(" mLayoutNeeded="); pw.println(mLayoutNeeded);
1531        }
1532        if (mXOffset != 0 || mYOffset != 0) {
1533            pw.print(prefix); pw.print("Offsets x="); pw.print(mXOffset);
1534                    pw.print(" y="); pw.println(mYOffset);
1535        }
1536        if (dumpAll) {
1537            pw.print(prefix); pw.print("mGivenContentInsets=");
1538                    mGivenContentInsets.printShortString(pw);
1539                    pw.print(" mGivenVisibleInsets=");
1540                    mGivenVisibleInsets.printShortString(pw);
1541                    pw.println();
1542            if (mTouchableInsets != 0 || mGivenInsetsPending) {
1543                pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
1544                        pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
1545                Region region = new Region();
1546                getTouchableRegion(region);
1547                pw.print(prefix); pw.print("touchable region="); pw.println(region);
1548            }
1549            pw.print(prefix); pw.print("mConfiguration="); pw.println(mConfiguration);
1550        }
1551        pw.print(prefix); pw.print("mHasSurface="); pw.print(mHasSurface);
1552                pw.print(" mShownFrame="); mShownFrame.printShortString(pw);
1553                pw.print(" isReadyForDisplay()="); pw.println(isReadyForDisplay());
1554        if (dumpAll) {
1555            pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
1556                    pw.print(" last="); mLastFrame.printShortString(pw);
1557                    pw.println();
1558            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
1559                    pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
1560                    pw.println();
1561        }
1562        if (mEnforceSizeCompat) {
1563            pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
1564                    pw.println();
1565        }
1566        if (dumpAll) {
1567            pw.print(prefix); pw.print("Frames: containing=");
1568                    mContainingFrame.printShortString(pw);
1569                    pw.print(" parent="); mParentFrame.printShortString(pw);
1570                    pw.println();
1571            pw.print(prefix); pw.print("    display="); mDisplayFrame.printShortString(pw);
1572                    pw.print(" overscan="); mOverscanFrame.printShortString(pw);
1573                    pw.println();
1574            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
1575                    pw.print(" visible="); mVisibleFrame.printShortString(pw);
1576                    pw.println();
1577            pw.print(prefix); pw.print("    decor="); mDecorFrame.printShortString(pw);
1578                    pw.println();
1579            pw.print(prefix); pw.print("Cur insets: overscan=");
1580                    mOverscanInsets.printShortString(pw);
1581                    pw.print(" content="); mContentInsets.printShortString(pw);
1582                    pw.print(" visible="); mVisibleInsets.printShortString(pw);
1583                    pw.print(" stable="); mStableInsets.printShortString(pw);
1584                    pw.println();
1585            pw.print(prefix); pw.print("Lst insets: overscan=");
1586                    mLastOverscanInsets.printShortString(pw);
1587                    pw.print(" content="); mLastContentInsets.printShortString(pw);
1588                    pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
1589                    pw.print(" stable="); mLastStableInsets.printShortString(pw);
1590                    pw.println();
1591        }
1592        pw.print(prefix); pw.print(mWinAnimator); pw.println(":");
1593        mWinAnimator.dump(pw, prefix + "  ", dumpAll);
1594        if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
1595            pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
1596                    pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
1597                    pw.print(" mDestroying="); pw.print(mDestroying);
1598                    pw.print(" mRemoved="); pw.println(mRemoved);
1599        }
1600        if (mOrientationChanging || mAppFreezing || mTurnOnScreen) {
1601            pw.print(prefix); pw.print("mOrientationChanging=");
1602                    pw.print(mOrientationChanging);
1603                    pw.print(" mAppFreezing="); pw.print(mAppFreezing);
1604                    pw.print(" mTurnOnScreen="); pw.println(mTurnOnScreen);
1605        }
1606        if (mLastFreezeDuration != 0) {
1607            pw.print(prefix); pw.print("mLastFreezeDuration=");
1608                    TimeUtils.formatDuration(mLastFreezeDuration, pw); pw.println();
1609        }
1610        if (mHScale != 1 || mVScale != 1) {
1611            pw.print(prefix); pw.print("mHScale="); pw.print(mHScale);
1612                    pw.print(" mVScale="); pw.println(mVScale);
1613        }
1614        if (mWallpaperX != -1 || mWallpaperY != -1) {
1615            pw.print(prefix); pw.print("mWallpaperX="); pw.print(mWallpaperX);
1616                    pw.print(" mWallpaperY="); pw.println(mWallpaperY);
1617        }
1618        if (mWallpaperXStep != -1 || mWallpaperYStep != -1) {
1619            pw.print(prefix); pw.print("mWallpaperXStep="); pw.print(mWallpaperXStep);
1620                    pw.print(" mWallpaperYStep="); pw.println(mWallpaperYStep);
1621        }
1622        if (mWallpaperDisplayOffsetX != Integer.MIN_VALUE
1623                || mWallpaperDisplayOffsetY != Integer.MIN_VALUE) {
1624            pw.print(prefix); pw.print("mWallpaperDisplayOffsetX=");
1625                    pw.print(mWallpaperDisplayOffsetX);
1626                    pw.print(" mWallpaperDisplayOffsetY=");
1627                    pw.println(mWallpaperDisplayOffsetY);
1628        }
1629    }
1630
1631    String makeInputChannelName() {
1632        return Integer.toHexString(System.identityHashCode(this))
1633            + " " + mAttrs.getTitle();
1634    }
1635
1636    @Override
1637    public String toString() {
1638        CharSequence title = mAttrs.getTitle();
1639        if (title == null || title.length() <= 0) {
1640            title = mAttrs.packageName;
1641        }
1642        if (mStringNameCache == null || mLastTitle != title || mWasExiting != mExiting) {
1643            mLastTitle = title;
1644            mWasExiting = mExiting;
1645            mStringNameCache = "Window{" + Integer.toHexString(System.identityHashCode(this))
1646                    + " u" + UserHandle.getUserId(mSession.mUid)
1647                    + " " + mLastTitle + (mExiting ? " EXITING}" : "}");
1648        }
1649        return mStringNameCache;
1650    }
1651}
1652