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