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