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