WindowState.java revision 067e5f68b9216b233df1c6529db182ff9b2887ab
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.privateFlags
708                    & WindowManager.LayoutParams.PRIVATE_FLAG_SET_NEEDS_MENU_KEY) != 0) {
709                return (ws.mAttrs.flags & WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY) != 0;
710            }
711            // If we reached the bottom of the range of windows we are considering,
712            // assume no menu is needed.
713            if (ws == bottom) {
714                return false;
715            }
716            // The current window hasn't specified whether menu key is needed;
717            // look behind it.
718            // First, we may need to determine the starting position.
719            if (index < 0) {
720                index = windows.indexOf(ws);
721            }
722            index--;
723            if (index < 0) {
724                return false;
725            }
726            ws = windows.get(index);
727        }
728    }
729
730    @Override
731    public int getSystemUiVisibility() {
732        return mSystemUiVisibility;
733    }
734
735    @Override
736    public int getSurfaceLayer() {
737        return mLayer;
738    }
739
740    @Override
741    public IApplicationToken getAppToken() {
742        return mAppToken != null ? mAppToken.appToken : null;
743    }
744
745    @Override
746    public boolean isVoiceInteraction() {
747        return mAppToken != null ? mAppToken.voiceInteraction : false;
748    }
749
750    boolean setInsetsChanged() {
751        mOverscanInsetsChanged |= !mLastOverscanInsets.equals(mOverscanInsets);
752        mContentInsetsChanged |= !mLastContentInsets.equals(mContentInsets);
753        mVisibleInsetsChanged |= !mLastVisibleInsets.equals(mVisibleInsets);
754        mStableInsetsChanged |= !mLastStableInsets.equals(mStableInsets);
755        return mOverscanInsetsChanged || mContentInsetsChanged || mVisibleInsetsChanged;
756    }
757
758    public DisplayContent getDisplayContent() {
759        if (mAppToken == null || mNotOnAppsDisplay) {
760            return mDisplayContent;
761        }
762        final TaskStack stack = getStack();
763        return stack == null ? mDisplayContent : stack.getDisplayContent();
764    }
765
766    public int getDisplayId() {
767        final DisplayContent displayContent = getDisplayContent();
768        if (displayContent == null) {
769            return -1;
770        }
771        return displayContent.getDisplayId();
772    }
773
774    TaskStack getStack() {
775        AppWindowToken wtoken = mAppToken == null ? mService.mFocusedApp : mAppToken;
776        if (wtoken != null) {
777            Task task = mService.mTaskIdToTask.get(wtoken.groupId);
778            if (task != null) {
779                if (task.mStack != null) {
780                    return task.mStack;
781                }
782                Slog.e(TAG, "getStack: mStack null for task=" + task);
783            } else {
784                Slog.e(TAG, "getStack: " + this + " couldn't find taskId=" + wtoken.groupId
785                    + " Callers=" + Debug.getCallers(4));
786            }
787        }
788        return mDisplayContent.getHomeStack();
789    }
790
791    void getStackBounds(Rect bounds) {
792        getStackBounds(getStack(), bounds);
793    }
794
795    private void getStackBounds(TaskStack stack, Rect bounds) {
796        if (stack != null) {
797            stack.getBounds(bounds);
798            return;
799        }
800        bounds.set(mFrame);
801    }
802
803    public long getInputDispatchingTimeoutNanos() {
804        return mAppToken != null
805                ? mAppToken.inputDispatchingTimeoutNanos
806                : WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
807    }
808
809    @Override
810    public boolean hasAppShownWindows() {
811        return mAppToken != null && (mAppToken.firstWindowDrawn || mAppToken.startingDisplayed);
812    }
813
814    boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
815        if (dsdx < .99999f || dsdx > 1.00001f) return false;
816        if (dtdy < .99999f || dtdy > 1.00001f) return false;
817        if (dtdx < -.000001f || dtdx > .000001f) return false;
818        if (dsdy < -.000001f || dsdy > .000001f) return false;
819        return true;
820    }
821
822    void prelayout() {
823        if (mEnforceSizeCompat) {
824            mGlobalScale = mService.mCompatibleScreenScale;
825            mInvGlobalScale = 1/mGlobalScale;
826        } else {
827            mGlobalScale = mInvGlobalScale = 1;
828        }
829    }
830
831    /**
832     * Is this window visible?  It is not visible if there is no
833     * surface, or we are in the process of running an exit animation
834     * that will remove the surface, or its app token has been hidden.
835     */
836    @Override
837    public boolean isVisibleLw() {
838        final AppWindowToken atoken = mAppToken;
839        return mHasSurface && mPolicyVisibility && !mAttachedHidden
840                && (atoken == null || !atoken.hiddenRequested)
841                && !mExiting && !mDestroying;
842    }
843
844    /**
845     * Like {@link #isVisibleLw}, but also counts a window that is currently
846     * "hidden" behind the keyguard as visible.  This allows us to apply
847     * things like window flags that impact the keyguard.
848     * XXX I am starting to think we need to have ANOTHER visibility flag
849     * for this "hidden behind keyguard" state rather than overloading
850     * mPolicyVisibility.  Ungh.
851     */
852    @Override
853    public boolean isVisibleOrBehindKeyguardLw() {
854        if (mRootToken.waitingToShow &&
855                mService.mAppTransition.isTransitionSet()) {
856            return false;
857        }
858        final AppWindowToken atoken = mAppToken;
859        final boolean animating = atoken != null
860                ? (atoken.mAppAnimator.animation != null) : false;
861        return mHasSurface && !mDestroying && !mExiting
862                && (atoken == null ? mPolicyVisibility : !atoken.hiddenRequested)
863                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
864                                && !mRootToken.hidden)
865                        || mWinAnimator.mAnimation != null || animating);
866    }
867
868    /**
869     * Is this window visible, ignoring its app token?  It is not visible
870     * if there is no surface, or we are in the process of running an exit animation
871     * that will remove the surface.
872     */
873    public boolean isWinVisibleLw() {
874        final AppWindowToken atoken = mAppToken;
875        return mHasSurface && mPolicyVisibility && !mAttachedHidden
876                && (atoken == null || !atoken.hiddenRequested || atoken.mAppAnimator.animating)
877                && !mExiting && !mDestroying;
878    }
879
880    /**
881     * The same as isVisible(), but follows the current hidden state of
882     * the associated app token, not the pending requested hidden state.
883     */
884    boolean isVisibleNow() {
885        return mHasSurface && mPolicyVisibility && !mAttachedHidden
886                && !mRootToken.hidden && !mExiting && !mDestroying;
887    }
888
889    /**
890     * Can this window possibly be a drag/drop target?  The test here is
891     * a combination of the above "visible now" with the check that the
892     * Input Manager uses when discarding windows from input consideration.
893     */
894    boolean isPotentialDragTarget() {
895        return isVisibleNow() && !mRemoved
896                && mInputChannel != null && mInputWindowHandle != null;
897    }
898
899    /**
900     * Same as isVisible(), but we also count it as visible between the
901     * call to IWindowSession.add() and the first relayout().
902     */
903    boolean isVisibleOrAdding() {
904        final AppWindowToken atoken = mAppToken;
905        return (mHasSurface || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
906                && mPolicyVisibility && !mAttachedHidden
907                && (atoken == null || !atoken.hiddenRequested)
908                && !mExiting && !mDestroying;
909    }
910
911    /**
912     * Is this window currently on-screen?  It is on-screen either if it
913     * is visible or it is currently running an animation before no longer
914     * being visible.
915     */
916    boolean isOnScreen() {
917        if (!mHasSurface || !mPolicyVisibility || mDestroying) {
918            return false;
919        }
920        final AppWindowToken atoken = mAppToken;
921        if (atoken != null) {
922            return ((!mAttachedHidden && !atoken.hiddenRequested)
923                    || mWinAnimator.mAnimation != null || atoken.mAppAnimator.animation != null);
924        }
925        return !mAttachedHidden || mWinAnimator.mAnimation != null;
926    }
927
928    /**
929     * Like isOnScreen(), but we don't return true if the window is part
930     * of a transition that has not yet been started.
931     */
932    boolean isReadyForDisplay() {
933        if (mRootToken.waitingToShow &&
934                mService.mAppTransition.isTransitionSet()) {
935            return false;
936        }
937        return mHasSurface && mPolicyVisibility && !mDestroying
938                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
939                                && !mRootToken.hidden)
940                        || mWinAnimator.mAnimation != null
941                        || ((mAppToken != null) && (mAppToken.mAppAnimator.animation != null)));
942    }
943
944    /**
945     * Like isReadyForDisplay(), but ignores any force hiding of the window due
946     * to the keyguard.
947     */
948    boolean isReadyForDisplayIgnoringKeyguard() {
949        if (mRootToken.waitingToShow && mService.mAppTransition.isTransitionSet()) {
950            return false;
951        }
952        final AppWindowToken atoken = mAppToken;
953        if (atoken == null && !mPolicyVisibility) {
954            // If this is not an app window, and the policy has asked to force
955            // hide, then we really do want to hide.
956            return false;
957        }
958        return mHasSurface && !mDestroying
959                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
960                                && !mRootToken.hidden)
961                        || mWinAnimator.mAnimation != null
962                        || ((atoken != null) && (atoken.mAppAnimator.animation != null)
963                                && !mWinAnimator.isDummyAnimation()));
964    }
965
966    /**
967     * Like isOnScreen, but returns false if the surface hasn't yet
968     * been drawn.
969     */
970    @Override
971    public boolean isDisplayedLw() {
972        final AppWindowToken atoken = mAppToken;
973        return isDrawnLw() && mPolicyVisibility
974            && ((!mAttachedHidden &&
975                    (atoken == null || !atoken.hiddenRequested))
976                        || mWinAnimator.mAnimating
977                        || (atoken != null && atoken.mAppAnimator.animation != null));
978    }
979
980    /**
981     * Return true if this window or its app token is currently animating.
982     */
983    @Override
984    public boolean isAnimatingLw() {
985        return mWinAnimator.mAnimation != null
986                || (mAppToken != null && mAppToken.mAppAnimator.animation != null);
987    }
988
989    @Override
990    public boolean isGoneForLayoutLw() {
991        final AppWindowToken atoken = mAppToken;
992        return mViewVisibility == View.GONE
993                || !mRelayoutCalled
994                || (atoken == null && mRootToken.hidden)
995                || (atoken != null && (atoken.hiddenRequested || atoken.hidden))
996                || mAttachedHidden
997                || (mExiting && !isAnimatingLw())
998                || mDestroying;
999    }
1000
1001    /**
1002     * Returns true if the window has a surface that it has drawn a
1003     * complete UI in to.
1004     */
1005    public boolean isDrawFinishedLw() {
1006        return mHasSurface && !mDestroying &&
1007                (mWinAnimator.mDrawState == WindowStateAnimator.COMMIT_DRAW_PENDING
1008                || mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1009                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1010    }
1011
1012    /**
1013     * Returns true if the window has a surface that it has drawn a
1014     * complete UI in to.
1015     */
1016    public boolean isDrawnLw() {
1017        return mHasSurface && !mDestroying &&
1018                (mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
1019                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
1020    }
1021
1022    /**
1023     * Return true if the window is opaque and fully drawn.  This indicates
1024     * it may obscure windows behind it.
1025     */
1026    boolean isOpaqueDrawn() {
1027        return (mAttrs.format == PixelFormat.OPAQUE
1028                        || mAttrs.type == TYPE_WALLPAPER)
1029                && isDrawnLw() && mWinAnimator.mAnimation == null
1030                && (mAppToken == null || mAppToken.mAppAnimator.animation == null);
1031    }
1032
1033    /**
1034     * Return whether this window is wanting to have a translation
1035     * animation applied to it for an in-progress move.  (Only makes
1036     * sense to call from performLayoutAndPlaceSurfacesLockedInner().)
1037     */
1038    boolean shouldAnimateMove() {
1039        return mContentChanged && !mExiting && !mWinAnimator.mLastHidden && mService.okToDisplay()
1040                && (mFrame.top != mLastFrame.top
1041                        || mFrame.left != mLastFrame.left)
1042                && (mAttrs.privateFlags&PRIVATE_FLAG_NO_MOVE_ANIMATION) == 0
1043                && (mAttachedWindow == null || !mAttachedWindow.shouldAnimateMove());
1044    }
1045
1046    boolean isFullscreen(int screenWidth, int screenHeight) {
1047        return mFrame.left <= 0 && mFrame.top <= 0 &&
1048                mFrame.right >= screenWidth && mFrame.bottom >= screenHeight;
1049    }
1050
1051    boolean isConfigChanged() {
1052        boolean configChanged = mConfiguration != mService.mCurConfiguration
1053                && (mConfiguration == null
1054                        || (mConfiguration.diff(mService.mCurConfiguration) != 0));
1055
1056        if ((mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
1057            // Retain configuration changed status until resetConfiguration called.
1058            mConfigHasChanged |= configChanged;
1059            configChanged = mConfigHasChanged;
1060        }
1061
1062        return configChanged;
1063    }
1064
1065    void removeLocked() {
1066        disposeInputChannel();
1067
1068        if (mAttachedWindow != null) {
1069            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
1070            mAttachedWindow.mChildWindows.remove(this);
1071        }
1072        mWinAnimator.destroyDeferredSurfaceLocked();
1073        mWinAnimator.destroySurfaceLocked();
1074        mSession.windowRemovedLocked();
1075        try {
1076            mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
1077        } catch (RuntimeException e) {
1078            // Ignore if it has already been removed (usually because
1079            // we are doing this as part of processing a death note.)
1080        }
1081    }
1082
1083    void setConfiguration(final Configuration newConfig) {
1084        mConfiguration = newConfig;
1085        mConfigHasChanged = false;
1086    }
1087
1088    void setInputChannel(InputChannel inputChannel) {
1089        if (mInputChannel != null) {
1090            throw new IllegalStateException("Window already has an input channel.");
1091        }
1092
1093        mInputChannel = inputChannel;
1094        mInputWindowHandle.inputChannel = inputChannel;
1095    }
1096
1097    void disposeInputChannel() {
1098        if (mInputChannel != null) {
1099            mService.mInputManager.unregisterInputChannel(mInputChannel);
1100
1101            mInputChannel.dispose();
1102            mInputChannel = null;
1103        }
1104
1105        mInputWindowHandle.inputChannel = null;
1106    }
1107
1108    private class DeathRecipient implements IBinder.DeathRecipient {
1109        @Override
1110        public void binderDied() {
1111            try {
1112                synchronized(mService.mWindowMap) {
1113                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
1114                    Slog.i(TAG, "WIN DEATH: " + win);
1115                    if (win != null) {
1116                        mService.removeWindowLocked(mSession, win);
1117                    } else if (mHasSurface) {
1118                        Slog.e(TAG, "!!! LEAK !!! Window removed but surface still valid.");
1119                        mService.removeWindowLocked(mSession, WindowState.this);
1120                    }
1121                }
1122            } catch (IllegalArgumentException ex) {
1123                // This will happen if the window has already been
1124                // removed.
1125            }
1126        }
1127    }
1128
1129    /**
1130     * @return true if this window desires key events.
1131     */
1132    public final boolean canReceiveKeys() {
1133        return isVisibleOrAdding()
1134                && (mViewVisibility == View.VISIBLE)
1135                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
1136    }
1137
1138    @Override
1139    public boolean hasDrawnLw() {
1140        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
1141    }
1142
1143    @Override
1144    public boolean showLw(boolean doAnimation) {
1145        return showLw(doAnimation, true);
1146    }
1147
1148    boolean showLw(boolean doAnimation, boolean requestAnim) {
1149        if (isHiddenFromUserLocked()) {
1150            return false;
1151        }
1152        if (!mAppOpVisibility) {
1153            // Being hidden due to app op request.
1154            return false;
1155        }
1156        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
1157            // Already showing.
1158            return false;
1159        }
1160        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
1161        if (doAnimation) {
1162            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
1163                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
1164            if (!mService.okToDisplay()) {
1165                doAnimation = false;
1166            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
1167                // Check for the case where we are currently visible and
1168                // not animating; we do not want to do animation at such a
1169                // point to become visible when we already are.
1170                doAnimation = false;
1171            }
1172        }
1173        mPolicyVisibility = true;
1174        mPolicyVisibilityAfterAnim = true;
1175        if (doAnimation) {
1176            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
1177        }
1178        if (requestAnim) {
1179            mService.scheduleAnimationLocked();
1180        }
1181        return true;
1182    }
1183
1184    @Override
1185    public boolean hideLw(boolean doAnimation) {
1186        return hideLw(doAnimation, true);
1187    }
1188
1189    boolean hideLw(boolean doAnimation, boolean requestAnim) {
1190        if (doAnimation) {
1191            if (!mService.okToDisplay()) {
1192                doAnimation = false;
1193            }
1194        }
1195        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
1196                : mPolicyVisibility;
1197        if (!current) {
1198            // Already hiding.
1199            return false;
1200        }
1201        if (doAnimation) {
1202            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
1203            if (mWinAnimator.mAnimation == null) {
1204                doAnimation = false;
1205            }
1206        }
1207        if (doAnimation) {
1208            mPolicyVisibilityAfterAnim = false;
1209        } else {
1210            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
1211            mPolicyVisibilityAfterAnim = false;
1212            mPolicyVisibility = false;
1213            // Window is no longer visible -- make sure if we were waiting
1214            // for it to be displayed before enabling the display, that
1215            // we allow the display to be enabled now.
1216            mService.enableScreenIfNeededLocked();
1217            if (mService.mCurrentFocus == this) {
1218                if (WindowManagerService.DEBUG_FOCUS_LIGHT) Slog.i(TAG,
1219                        "WindowState.hideLw: setting mFocusMayChange true");
1220                mService.mFocusMayChange = true;
1221            }
1222        }
1223        if (requestAnim) {
1224            mService.scheduleAnimationLocked();
1225        }
1226        return true;
1227    }
1228
1229    public void setAppOpVisibilityLw(boolean state) {
1230        if (mAppOpVisibility != state) {
1231            mAppOpVisibility = state;
1232            if (state) {
1233                // If the policy visibility had last been to hide, then this
1234                // will incorrectly show at this point since we lost that
1235                // information.  Not a big deal -- for the windows that have app
1236                // ops modifies they should only be hidden by policy due to the
1237                // lock screen, and the user won't be changing this if locked.
1238                // Plus it will quickly be fixed the next time we do a layout.
1239                showLw(true, true);
1240            } else {
1241                hideLw(true, true);
1242            }
1243        }
1244    }
1245
1246    @Override
1247    public boolean isAlive() {
1248        return mClient.asBinder().isBinderAlive();
1249    }
1250
1251    boolean isClosing() {
1252        return mExiting || (mService.mClosingApps.contains(mAppToken));
1253    }
1254
1255    @Override
1256    public boolean isDefaultDisplay() {
1257        final DisplayContent displayContent = getDisplayContent();
1258        if (displayContent == null) {
1259            // Only a window that was on a non-default display can be detached from it.
1260            return false;
1261        }
1262        return displayContent.isDefaultDisplay;
1263    }
1264
1265    public void setShowToOwnerOnlyLocked(boolean showToOwnerOnly) {
1266        mShowToOwnerOnly = showToOwnerOnly;
1267    }
1268
1269    boolean isHiddenFromUserLocked() {
1270        // Attached windows are evaluated based on the window that they are attached to.
1271        WindowState win = this;
1272        while (win.mAttachedWindow != null) {
1273            win = win.mAttachedWindow;
1274        }
1275        if (win.mAttrs.type < WindowManager.LayoutParams.FIRST_SYSTEM_WINDOW
1276                && win.mAppToken != null && win.mAppToken.showWhenLocked) {
1277            // Save some cycles by not calling getDisplayInfo unless it is an application
1278            // window intended for all users.
1279            final DisplayContent displayContent = win.getDisplayContent();
1280            if (displayContent == null) {
1281                return true;
1282            }
1283            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
1284            if (win.mFrame.left <= 0 && win.mFrame.top <= 0
1285                    && win.mFrame.right >= displayInfo.appWidth
1286                    && win.mFrame.bottom >= displayInfo.appHeight) {
1287                // Is a fullscreen window, like the clock alarm. Show to everyone.
1288                return false;
1289            }
1290        }
1291
1292        return win.mShowToOwnerOnly
1293                && !mService.isCurrentProfileLocked(UserHandle.getUserId(win.mOwnerUid));
1294    }
1295
1296    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
1297        outRegion.set(
1298                frame.left + inset.left, frame.top + inset.top,
1299                frame.right - inset.right, frame.bottom - inset.bottom);
1300    }
1301
1302    public void getTouchableRegion(Region outRegion) {
1303        final Rect frame = mFrame;
1304        switch (mTouchableInsets) {
1305            default:
1306            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME:
1307                outRegion.set(frame);
1308                break;
1309            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT:
1310                applyInsets(outRegion, frame, mGivenContentInsets);
1311                break;
1312            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE:
1313                applyInsets(outRegion, frame, mGivenVisibleInsets);
1314                break;
1315            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION: {
1316                final Region givenTouchableRegion = mGivenTouchableRegion;
1317                outRegion.set(givenTouchableRegion);
1318                outRegion.translate(frame.left, frame.top);
1319                break;
1320            }
1321        }
1322    }
1323
1324    WindowList getWindowList() {
1325        final DisplayContent displayContent = getDisplayContent();
1326        return displayContent == null ? null : displayContent.getWindowList();
1327    }
1328
1329    /**
1330     * Report a focus change.  Must be called with no locks held, and consistently
1331     * from the same serialized thread (such as dispatched from a handler).
1332     */
1333    public void reportFocusChangedSerialized(boolean focused, boolean inTouchMode) {
1334        try {
1335            mClient.windowFocusChanged(focused, inTouchMode);
1336        } catch (RemoteException e) {
1337        }
1338        if (mFocusCallbacks != null) {
1339            final int N = mFocusCallbacks.beginBroadcast();
1340            for (int i=0; i<N; i++) {
1341                IWindowFocusObserver obs = mFocusCallbacks.getBroadcastItem(i);
1342                try {
1343                    if (focused) {
1344                        obs.focusGained(mWindowId.asBinder());
1345                    } else {
1346                        obs.focusLost(mWindowId.asBinder());
1347                    }
1348                } catch (RemoteException e) {
1349                }
1350            }
1351            mFocusCallbacks.finishBroadcast();
1352        }
1353    }
1354
1355    void reportResized() {
1356        try {
1357            if (DEBUG_RESIZE || DEBUG_ORIENTATION) Slog.v(TAG, "Reporting new frame to " + this
1358                    + ": " + mCompatFrame);
1359            boolean configChanged = isConfigChanged();
1360            if ((DEBUG_RESIZE || DEBUG_ORIENTATION || DEBUG_CONFIGURATION) && configChanged) {
1361                Slog.i(TAG, "Sending new config to window " + this + ": "
1362                        + mWinAnimator.mSurfaceW + "x" + mWinAnimator.mSurfaceH
1363                        + " / " + mService.mCurConfiguration);
1364            }
1365            setConfiguration(mService.mCurConfiguration);
1366            if (DEBUG_ORIENTATION && mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING)
1367                Slog.i(TAG, "Resizing " + this + " WITH DRAW PENDING");
1368
1369            final Rect frame = mFrame;
1370            final Rect overscanInsets = mLastOverscanInsets;
1371            final Rect contentInsets = mLastContentInsets;
1372            final Rect visibleInsets = mLastVisibleInsets;
1373            final Rect stableInsets = mLastStableInsets;
1374            final boolean reportDraw = mWinAnimator.mDrawState == WindowStateAnimator.DRAW_PENDING;
1375            final Configuration newConfig = configChanged ? mConfiguration : null;
1376            if (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