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