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