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