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