WindowState.java revision 178af5948d71c841278081c712506f7a7fca34b9
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 android.view.WindowManager.LayoutParams.FIRST_SUB_WINDOW;
20import static android.view.WindowManager.LayoutParams.FLAG_COMPATIBLE_WINDOW;
21import static android.view.WindowManager.LayoutParams.LAST_SUB_WINDOW;
22import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD;
23import static android.view.WindowManager.LayoutParams.TYPE_INPUT_METHOD_DIALOG;
24import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
25import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
26import static android.view.WindowManager.LayoutParams.LAST_APPLICATION_WINDOW;
27import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
28
29import com.android.server.input.InputWindowHandle;
30
31import android.content.Context;
32import android.content.res.Configuration;
33import android.graphics.Matrix;
34import android.graphics.PixelFormat;
35import android.graphics.Rect;
36import android.graphics.RectF;
37import android.graphics.Region;
38import android.os.IBinder;
39import android.os.Process;
40import android.os.RemoteException;
41import android.os.UserHandle;
42import android.util.Slog;
43import android.view.DisplayInfo;
44import android.view.Gravity;
45import android.view.IApplicationToken;
46import android.view.IWindow;
47import android.view.InputChannel;
48import android.view.View;
49import android.view.ViewTreeObserver;
50import android.view.WindowManager;
51import android.view.WindowManagerPolicy;
52
53import java.io.PrintWriter;
54import java.util.ArrayList;
55
56class WindowList extends ArrayList<WindowState> {
57}
58
59/**
60 * A window in the window manager.
61 */
62final class WindowState implements WindowManagerPolicy.WindowState {
63    static final String TAG = "WindowState";
64
65    static final boolean DEBUG_VISIBILITY = WindowManagerService.DEBUG_VISIBILITY;
66    static final boolean SHOW_TRANSACTIONS = WindowManagerService.SHOW_TRANSACTIONS;
67    static final boolean SHOW_LIGHT_TRANSACTIONS = WindowManagerService.SHOW_LIGHT_TRANSACTIONS;
68    static final boolean SHOW_SURFACE_ALLOC = WindowManagerService.SHOW_SURFACE_ALLOC;
69
70    final WindowManagerService mService;
71    final WindowManagerPolicy mPolicy;
72    final Context mContext;
73    final Session mSession;
74    final IWindow mClient;
75    WindowToken mToken;
76    WindowToken mRootToken;
77    AppWindowToken mAppToken;
78    AppWindowToken mTargetAppToken;
79
80    // mAttrs.flags is tested in animation without being locked. If the bits tested are ever
81    // modified they will need to be locked.
82    final WindowManager.LayoutParams mAttrs = new WindowManager.LayoutParams();
83    final DeathRecipient mDeathRecipient;
84    final WindowState mAttachedWindow;
85    final ArrayList<WindowState> mChildWindows = new ArrayList<WindowState>();
86    final int mBaseLayer;
87    final int mSubLayer;
88    final boolean mLayoutAttached;
89    final boolean mIsImWindow;
90    final boolean mIsWallpaper;
91    final boolean mIsFloatingLayer;
92    int mSeq;
93    boolean mEnforceSizeCompat;
94    int mViewVisibility;
95    int mSystemUiVisibility;
96    boolean mPolicyVisibility = true;
97    boolean mPolicyVisibilityAfterAnim = true;
98    boolean mAppFreezing;
99    boolean mAttachedHidden;    // is our parent window hidden?
100    boolean mWallpaperVisible;  // for wallpaper, what was last vis report?
101
102    /**
103     * The window size that was requested by the application.  These are in
104     * the application's coordinate space (without compatibility scale applied).
105     */
106    int mRequestedWidth;
107    int mRequestedHeight;
108    int mLastRequestedWidth;
109    int mLastRequestedHeight;
110
111    int mLayer;
112    boolean mHaveFrame;
113    boolean mObscured;
114    boolean mTurnOnScreen;
115
116    int mLayoutSeq = -1;
117
118    Configuration mConfiguration = null;
119
120    /**
121     * Actual frame shown on-screen (may be modified by animation).  These
122     * are in the screen's coordinate space (WITH the compatibility scale
123     * applied).
124     */
125    final RectF mShownFrame = new RectF();
126
127    /**
128     * Insets that determine the actually visible area.  These are in the application's
129     * coordinate space (without compatibility scale applied).
130     */
131    final Rect mVisibleInsets = new Rect();
132    final Rect mLastVisibleInsets = new Rect();
133    boolean mVisibleInsetsChanged;
134
135    /**
136     * Insets that are covered by system windows (such as the status bar) and
137     * transient docking windows (such as the IME).  These are in the application's
138     * coordinate space (without compatibility scale applied).
139     */
140    final Rect mContentInsets = new Rect();
141    final Rect mLastContentInsets = new Rect();
142    boolean mContentInsetsChanged;
143
144    /**
145     * Set to true if we are waiting for this window to receive its
146     * given internal insets before laying out other windows based on it.
147     */
148    boolean mGivenInsetsPending;
149
150    /**
151     * These are the content insets that were given during layout for
152     * this window, to be applied to windows behind it.
153     */
154    final Rect mGivenContentInsets = new Rect();
155
156    /**
157     * These are the visible insets that were given during layout for
158     * this window, to be applied to windows behind it.
159     */
160    final Rect mGivenVisibleInsets = new Rect();
161
162    /**
163     * This is the given touchable area relative to the window frame, or null if none.
164     */
165    final Region mGivenTouchableRegion = new Region();
166
167    /**
168     * Flag indicating whether the touchable region should be adjusted by
169     * the visible insets; if false the area outside the visible insets is
170     * NOT touchable, so we must use those to adjust the frame during hit
171     * tests.
172     */
173    int mTouchableInsets = ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME;
174
175    /**
176     * This is rectangle of the window's surface that is not covered by
177     * system decorations.
178     */
179    final Rect mSystemDecorRect = new Rect();
180    final Rect mLastSystemDecorRect = new Rect();
181
182    // Current transformation being applied.
183    float mGlobalScale=1;
184    float mInvGlobalScale=1;
185    float mHScale=1, mVScale=1;
186    float mLastHScale=1, mLastVScale=1;
187    final Matrix mTmpMatrix = new Matrix();
188
189    // "Real" frame that the application sees, in display coordinate space.
190    final Rect mFrame = new Rect();
191    final Rect mLastFrame = new Rect();
192    // Frame that is scaled to the application's coordinate space when in
193    // screen size compatibility mode.
194    final Rect mCompatFrame = new Rect();
195
196    final Rect mContainingFrame = new Rect();
197    final Rect mDisplayFrame = new Rect();
198    final Rect mContentFrame = new Rect();
199    final Rect mParentFrame = new Rect();
200    final Rect mVisibleFrame = new Rect();
201
202    boolean mContentChanged;
203
204    // If a window showing a wallpaper: the requested offset for the
205    // wallpaper; if a wallpaper window: the currently applied offset.
206    float mWallpaperX = -1;
207    float mWallpaperY = -1;
208
209    // If a window showing a wallpaper: what fraction of the offset
210    // range corresponds to a full virtual screen.
211    float mWallpaperXStep = -1;
212    float mWallpaperYStep = -1;
213
214    // Wallpaper windows: pixels offset based on above variables.
215    int mXOffset;
216    int mYOffset;
217
218    // This is set after IWindowSession.relayout() has been called at
219    // least once for the window.  It allows us to detect the situation
220    // where we don't yet have a surface, but should have one soon, so
221    // we can give the window focus before waiting for the relayout.
222    boolean mRelayoutCalled;
223
224    // If the application has called relayout() with changes that can
225    // impact its window's size, we need to perform a layout pass on it
226    // even if it is not currently visible for layout.  This is set
227    // when in that case until the layout is done.
228    boolean mLayoutNeeded;
229
230    // Currently running an exit animation?
231    boolean mExiting;
232
233    // Currently on the mDestroySurface list?
234    boolean mDestroying;
235
236    // Completely remove from window manager after exit animation?
237    boolean mRemoveOnExit;
238
239    // Set when the orientation is changing and this window has not yet
240    // been updated for the new orientation.
241    boolean mOrientationChanging;
242
243    // Is this window now (or just being) removed?
244    boolean mRemoved;
245
246    // Temp for keeping track of windows that have been removed when
247    // rebuilding window list.
248    boolean mRebuilding;
249
250    // Input channel and input window handle used by the input dispatcher.
251    final InputWindowHandle mInputWindowHandle;
252    InputChannel mInputChannel;
253
254    // Used to improve performance of toString()
255    String mStringNameCache;
256    CharSequence mLastTitle;
257    boolean mWasPaused;
258
259    final WindowStateAnimator mWinAnimator;
260
261    boolean mHasSurface = false;
262
263    DisplayContent  mDisplayContent;
264
265    // UserId and appId of the owner. Don't display windows of non-current user.
266    final int mOwnerUid;
267
268    WindowState(WindowManagerService service, Session s, IWindow c, WindowToken token,
269           WindowState attachedWindow, int seq, WindowManager.LayoutParams a,
270           int viewVisibility, final DisplayContent displayContent) {
271        mService = service;
272        mSession = s;
273        mClient = c;
274        mToken = token;
275        mOwnerUid = s.mUid;
276        mAttrs.copyFrom(a);
277        mViewVisibility = viewVisibility;
278        mDisplayContent = displayContent;
279        mPolicy = mService.mPolicy;
280        mContext = mService.mContext;
281        DeathRecipient deathRecipient = new DeathRecipient();
282        mSeq = seq;
283        mEnforceSizeCompat = (mAttrs.flags & FLAG_COMPATIBLE_WINDOW) != 0;
284        if (WindowManagerService.localLOGV) Slog.v(
285            TAG, "Window " + this + " client=" + c.asBinder()
286            + " token=" + token + " (" + mAttrs.token + ")");
287        try {
288            c.asBinder().linkToDeath(deathRecipient, 0);
289        } catch (RemoteException e) {
290            mDeathRecipient = null;
291            mAttachedWindow = null;
292            mLayoutAttached = false;
293            mIsImWindow = false;
294            mIsWallpaper = false;
295            mIsFloatingLayer = false;
296            mBaseLayer = 0;
297            mSubLayer = 0;
298            mInputWindowHandle = null;
299            mWinAnimator = null;
300            return;
301        }
302        mDeathRecipient = deathRecipient;
303
304        if ((mAttrs.type >= FIRST_SUB_WINDOW &&
305                mAttrs.type <= LAST_SUB_WINDOW)) {
306            // The multiplier here is to reserve space for multiple
307            // windows in the same type layer.
308            mBaseLayer = mPolicy.windowTypeToLayerLw(
309                    attachedWindow.mAttrs.type) * WindowManagerService.TYPE_LAYER_MULTIPLIER
310                    + WindowManagerService.TYPE_LAYER_OFFSET;
311            mSubLayer = mPolicy.subWindowTypeToLayerLw(a.type);
312            mAttachedWindow = attachedWindow;
313            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Adding " + this + " to " + mAttachedWindow);
314            mAttachedWindow.mChildWindows.add(this);
315            mLayoutAttached = mAttrs.type !=
316                    WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
317            mIsImWindow = attachedWindow.mAttrs.type == TYPE_INPUT_METHOD
318                    || attachedWindow.mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
319            mIsWallpaper = attachedWindow.mAttrs.type == TYPE_WALLPAPER;
320            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
321        } else {
322            // The multiplier here is to reserve space for multiple
323            // windows in the same type layer.
324            mBaseLayer = mPolicy.windowTypeToLayerLw(a.type)
325                    * WindowManagerService.TYPE_LAYER_MULTIPLIER
326                    + WindowManagerService.TYPE_LAYER_OFFSET;
327            mSubLayer = 0;
328            mAttachedWindow = null;
329            mLayoutAttached = false;
330            mIsImWindow = mAttrs.type == TYPE_INPUT_METHOD
331                    || mAttrs.type == TYPE_INPUT_METHOD_DIALOG;
332            mIsWallpaper = mAttrs.type == TYPE_WALLPAPER;
333            mIsFloatingLayer = mIsImWindow || mIsWallpaper;
334        }
335
336        WindowState appWin = this;
337        while (appWin.mAttachedWindow != null) {
338            appWin = appWin.mAttachedWindow;
339        }
340        WindowToken appToken = appWin.mToken;
341        while (appToken.appWindowToken == null) {
342            WindowToken parent = mService.mTokenMap.get(appToken.token);
343            if (parent == null || appToken == parent) {
344                break;
345            }
346            appToken = parent;
347        }
348        mRootToken = appToken;
349        mAppToken = appToken.appWindowToken;
350
351        mWinAnimator = new WindowStateAnimator(this);
352        mWinAnimator.mAlpha = a.alpha;
353
354        mRequestedWidth = 0;
355        mRequestedHeight = 0;
356        mLastRequestedWidth = 0;
357        mLastRequestedHeight = 0;
358        mXOffset = 0;
359        mYOffset = 0;
360        mLayer = 0;
361        mInputWindowHandle = new InputWindowHandle(
362                mAppToken != null ? mAppToken.mInputApplicationHandle : null, this,
363                displayContent.getDisplayId());
364    }
365
366    void attach() {
367        if (WindowManagerService.localLOGV) Slog.v(
368            TAG, "Attaching " + this + " token=" + mToken
369            + ", list=" + mToken.windows);
370        mSession.windowAddedLocked();
371    }
372
373    @Override
374    public void computeFrameLw(Rect pf, Rect df, Rect cf, Rect vf) {
375        mHaveFrame = true;
376
377        final Rect container = mContainingFrame;
378        container.set(pf);
379
380        final Rect display = mDisplayFrame;
381        display.set(df);
382
383        final int pw = container.right - container.left;
384        final int ph = container.bottom - container.top;
385
386        int w,h;
387        if ((mAttrs.flags & WindowManager.LayoutParams.FLAG_SCALED) != 0) {
388            if (mAttrs.width < 0) {
389                w = pw;
390            } else if (mEnforceSizeCompat) {
391                w = (int)(mAttrs.width * mGlobalScale + .5f);
392            } else {
393                w = mAttrs.width;
394            }
395            if (mAttrs.height < 0) {
396                h = ph;
397            } else if (mEnforceSizeCompat) {
398                h = (int)(mAttrs.height * mGlobalScale + .5f);
399            } else {
400                h = mAttrs.height;
401            }
402        } else {
403            if (mAttrs.width == WindowManager.LayoutParams.MATCH_PARENT) {
404                w = pw;
405            } else if (mEnforceSizeCompat) {
406                w = (int)(mRequestedWidth * mGlobalScale + .5f);
407            } else {
408                w = mRequestedWidth;
409            }
410            if (mAttrs.height == WindowManager.LayoutParams.MATCH_PARENT) {
411                h = ph;
412            } else if (mEnforceSizeCompat) {
413                h = (int)(mRequestedHeight * mGlobalScale + .5f);
414            } else {
415                h = mRequestedHeight;
416            }
417        }
418
419        if (!mParentFrame.equals(pf)) {
420            //Slog.i(TAG, "Window " + this + " content frame from " + mParentFrame
421            //        + " to " + pf);
422            mParentFrame.set(pf);
423            mContentChanged = true;
424        }
425        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
426            mLastRequestedWidth = mRequestedWidth;
427            mLastRequestedHeight = mRequestedHeight;
428            mContentChanged = true;
429        }
430
431        final Rect content = mContentFrame;
432        content.set(cf);
433
434        final Rect visible = mVisibleFrame;
435        visible.set(vf);
436
437        final Rect frame = mFrame;
438        final int fw = frame.width();
439        final int fh = frame.height();
440
441        //System.out.println("In: w=" + w + " h=" + h + " container=" +
442        //                   container + " x=" + mAttrs.x + " y=" + mAttrs.y);
443
444        float x, y;
445        if (mEnforceSizeCompat) {
446            x = mAttrs.x * mGlobalScale;
447            y = mAttrs.y * mGlobalScale;
448        } else {
449            x = mAttrs.x;
450            y = mAttrs.y;
451        }
452
453        Gravity.apply(mAttrs.gravity, w, h, container,
454                (int) (x + mAttrs.horizontalMargin * pw),
455                (int) (y + mAttrs.verticalMargin * ph), frame);
456
457        //System.out.println("Out: " + mFrame);
458
459        // Now make sure the window fits in the overall display.
460        Gravity.applyDisplay(mAttrs.gravity, df, frame);
461
462        // Make sure the system, content and visible frames are inside of the
463        // final window frame.
464        if (content.left < frame.left) content.left = frame.left;
465        if (content.top < frame.top) content.top = frame.top;
466        if (content.right > frame.right) content.right = frame.right;
467        if (content.bottom > frame.bottom) content.bottom = frame.bottom;
468        if (visible.left < frame.left) visible.left = frame.left;
469        if (visible.top < frame.top) visible.top = frame.top;
470        if (visible.right > frame.right) visible.right = frame.right;
471        if (visible.bottom > frame.bottom) visible.bottom = frame.bottom;
472
473        final Rect contentInsets = mContentInsets;
474        contentInsets.left = content.left-frame.left;
475        contentInsets.top = content.top-frame.top;
476        contentInsets.right = frame.right-content.right;
477        contentInsets.bottom = frame.bottom-content.bottom;
478
479        final Rect visibleInsets = mVisibleInsets;
480        visibleInsets.left = visible.left-frame.left;
481        visibleInsets.top = visible.top-frame.top;
482        visibleInsets.right = frame.right-visible.right;
483        visibleInsets.bottom = frame.bottom-visible.bottom;
484
485        mCompatFrame.set(frame);
486        if (mEnforceSizeCompat) {
487            // If there is a size compatibility scale being applied to the
488            // window, we need to apply this to its insets so that they are
489            // reported to the app in its coordinate space.
490            contentInsets.scale(mInvGlobalScale);
491            visibleInsets.scale(mInvGlobalScale);
492
493            // Also the scaled frame that we report to the app needs to be
494            // adjusted to be in its coordinate space.
495            mCompatFrame.scale(mInvGlobalScale);
496        }
497
498        if (mIsWallpaper && (fw != frame.width() || fh != frame.height())) {
499            final DisplayInfo displayInfo = mDisplayContent.getDisplayInfo();
500            mService.updateWallpaperOffsetLocked(this, displayInfo.appWidth, displayInfo.appHeight,
501                    false);
502        }
503
504        if (WindowManagerService.localLOGV) {
505            //if ("com.google.android.youtube".equals(mAttrs.packageName)
506            //        && mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
507                Slog.v(TAG, "Resolving (mRequestedWidth="
508                        + mRequestedWidth + ", mRequestedheight="
509                        + mRequestedHeight + ") to" + " (pw=" + pw + ", ph=" + ph
510                        + "): frame=" + mFrame.toShortString()
511                        + " ci=" + contentInsets.toShortString()
512                        + " vi=" + visibleInsets.toShortString());
513            //}
514        }
515    }
516
517    MagnificationSpec getWindowMagnificationSpecLocked() {
518        MagnificationSpec spec = mDisplayContent.mMagnificationSpec;
519        if (spec != null && !spec.isNop()) {
520            if (mAttachedWindow != null) {
521                if (!mPolicy.canMagnifyWindow(mAttachedWindow.mAttrs)) {
522                    return null;
523                }
524            }
525            if (!mPolicy.canMagnifyWindow(mAttrs)) {
526                return null;
527            }
528        }
529        return spec;
530    }
531
532    @Override
533    public Rect getFrameLw() {
534        return mFrame;
535    }
536
537    @Override
538    public RectF getShownFrameLw() {
539        return mShownFrame;
540    }
541
542    @Override
543    public Rect getDisplayFrameLw() {
544        return mDisplayFrame;
545    }
546
547    @Override
548    public Rect getContentFrameLw() {
549        return mContentFrame;
550    }
551
552    @Override
553    public Rect getVisibleFrameLw() {
554        return mVisibleFrame;
555    }
556
557    @Override
558    public boolean getGivenInsetsPendingLw() {
559        return mGivenInsetsPending;
560    }
561
562    @Override
563    public Rect getGivenContentInsetsLw() {
564        return mGivenContentInsets;
565    }
566
567    @Override
568    public Rect getGivenVisibleInsetsLw() {
569        return mGivenVisibleInsets;
570    }
571
572    @Override
573    public WindowManager.LayoutParams getAttrs() {
574        return mAttrs;
575    }
576
577    public boolean getNeedsMenuLw(WindowManagerPolicy.WindowState bottom) {
578        int index = -1;
579        WindowState ws = this;
580        WindowList windows = getWindowList();
581        while (true) {
582            if ((ws.mAttrs.privateFlags
583                    & WindowManager.LayoutParams.PRIVATE_FLAG_SET_NEEDS_MENU_KEY) != 0) {
584                return (ws.mAttrs.flags & WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY) != 0;
585            }
586            // If we reached the bottom of the range of windows we are considering,
587            // assume no menu is needed.
588            if (ws == bottom) {
589                return false;
590            }
591            // The current window hasn't specified whether menu key is needed;
592            // look behind it.
593            // First, we may need to determine the starting position.
594            if (index < 0) {
595                index = windows.indexOf(ws);
596            }
597            index--;
598            if (index < 0) {
599                return false;
600            }
601            ws = windows.get(index);
602        }
603    }
604
605    @Override
606    public int getSystemUiVisibility() {
607        return mSystemUiVisibility;
608    }
609
610    @Override
611    public int getSurfaceLayer() {
612        return mLayer;
613    }
614
615    public IApplicationToken getAppToken() {
616        return mAppToken != null ? mAppToken.appToken : null;
617    }
618
619    public int getDisplayId() {
620        return mDisplayContent.getDisplayId();
621    }
622
623    public long getInputDispatchingTimeoutNanos() {
624        return mAppToken != null
625                ? mAppToken.inputDispatchingTimeoutNanos
626                : WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
627    }
628
629    public boolean hasAppShownWindows() {
630        return mAppToken != null && (mAppToken.firstWindowDrawn || mAppToken.startingDisplayed);
631    }
632
633    boolean isIdentityMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
634        if (dsdx < .99999f || dsdx > 1.00001f) return false;
635        if (dtdy < .99999f || dtdy > 1.00001f) return false;
636        if (dtdx < -.000001f || dtdx > .000001f) return false;
637        if (dsdy < -.000001f || dsdy > .000001f) return false;
638        return true;
639    }
640
641    void prelayout() {
642        if (mEnforceSizeCompat) {
643            mGlobalScale = mService.mCompatibleScreenScale;
644            mInvGlobalScale = 1/mGlobalScale;
645        } else {
646            mGlobalScale = mInvGlobalScale = 1;
647        }
648    }
649
650    /**
651     * Is this window visible?  It is not visible if there is no
652     * surface, or we are in the process of running an exit animation
653     * that will remove the surface, or its app token has been hidden.
654     */
655    public boolean isVisibleLw() {
656        final AppWindowToken atoken = mAppToken;
657        return mHasSurface && mPolicyVisibility && !mAttachedHidden
658                && (atoken == null || !atoken.hiddenRequested)
659                && !mExiting && !mDestroying;
660    }
661
662    /**
663     * Like {@link #isVisibleLw}, but also counts a window that is currently
664     * "hidden" behind the keyguard as visible.  This allows us to apply
665     * things like window flags that impact the keyguard.
666     * XXX I am starting to think we need to have ANOTHER visibility flag
667     * for this "hidden behind keyguard" state rather than overloading
668     * mPolicyVisibility.  Ungh.
669     */
670    public boolean isVisibleOrBehindKeyguardLw() {
671        if (mRootToken.waitingToShow &&
672                mService.mNextAppTransition != WindowManagerPolicy.TRANSIT_UNSET) {
673            return false;
674        }
675        final AppWindowToken atoken = mAppToken;
676        final boolean animating = atoken != null
677                ? (atoken.mAppAnimator.animation != null) : false;
678        return mHasSurface && !mDestroying && !mExiting
679                && (atoken == null ? mPolicyVisibility : !atoken.hiddenRequested)
680                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
681                                && !mRootToken.hidden)
682                        || mWinAnimator.mAnimation != null || animating);
683    }
684
685    /**
686     * Is this window visible, ignoring its app token?  It is not visible
687     * if there is no surface, or we are in the process of running an exit animation
688     * that will remove the surface.
689     */
690    public boolean isWinVisibleLw() {
691        final AppWindowToken atoken = mAppToken;
692        return mHasSurface && mPolicyVisibility && !mAttachedHidden
693                && (atoken == null || !atoken.hiddenRequested || atoken.mAppAnimator.animating)
694                && !mExiting && !mDestroying;
695    }
696
697    /**
698     * The same as isVisible(), but follows the current hidden state of
699     * the associated app token, not the pending requested hidden state.
700     */
701    boolean isVisibleNow() {
702        return mHasSurface && mPolicyVisibility && !mAttachedHidden
703                && !mRootToken.hidden && !mExiting && !mDestroying;
704    }
705
706    /**
707     * Can this window possibly be a drag/drop target?  The test here is
708     * a combination of the above "visible now" with the check that the
709     * Input Manager uses when discarding windows from input consideration.
710     */
711    boolean isPotentialDragTarget() {
712        return isVisibleNow() && !mRemoved
713                && mInputChannel != null && mInputWindowHandle != null;
714    }
715
716    /**
717     * Same as isVisible(), but we also count it as visible between the
718     * call to IWindowSession.add() and the first relayout().
719     */
720    boolean isVisibleOrAdding() {
721        final AppWindowToken atoken = mAppToken;
722        return (mHasSurface || (!mRelayoutCalled && mViewVisibility == View.VISIBLE))
723                && mPolicyVisibility && !mAttachedHidden
724                && (atoken == null || !atoken.hiddenRequested)
725                && !mExiting && !mDestroying;
726    }
727
728    /**
729     * Is this window currently on-screen?  It is on-screen either if it
730     * is visible or it is currently running an animation before no longer
731     * being visible.
732     */
733    boolean isOnScreen() {
734        if (!mHasSurface || !mPolicyVisibility || mDestroying) {
735            return false;
736        }
737        final AppWindowToken atoken = mAppToken;
738        if (atoken != null) {
739            return ((!mAttachedHidden && !atoken.hiddenRequested)
740                            || mWinAnimator.mAnimation != null || atoken.mAppAnimator.animation != null);
741        }
742        return !mAttachedHidden || mWinAnimator.mAnimation != null;
743    }
744
745    /**
746     * Like isOnScreen(), but we don't return true if the window is part
747     * of a transition that has not yet been started.
748     */
749    boolean isReadyForDisplay() {
750        if (mRootToken.waitingToShow &&
751                mService.mNextAppTransition != WindowManagerPolicy.TRANSIT_UNSET) {
752            return false;
753        }
754        return mHasSurface && mPolicyVisibility && !mDestroying
755                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
756                                && !mRootToken.hidden)
757                        || mWinAnimator.mAnimation != null
758                        || ((mAppToken != null) && (mAppToken.mAppAnimator.animation != null)));
759    }
760
761    /**
762     * Like isReadyForDisplay(), but ignores any force hiding of the window due
763     * to the keyguard.
764     */
765    boolean isReadyForDisplayIgnoringKeyguard() {
766        if (mRootToken.waitingToShow &&
767                mService.mNextAppTransition != WindowManagerPolicy.TRANSIT_UNSET) {
768            return false;
769        }
770        final AppWindowToken atoken = mAppToken;
771        if (atoken == null && !mPolicyVisibility) {
772            // If this is not an app window, and the policy has asked to force
773            // hide, then we really do want to hide.
774            return false;
775        }
776        return mHasSurface && !mDestroying
777                && ((!mAttachedHidden && mViewVisibility == View.VISIBLE
778                                && !mRootToken.hidden)
779                        || mWinAnimator.mAnimation != null
780                        || ((atoken != null) && (atoken.mAppAnimator.animation != null)
781                                && !mWinAnimator.isDummyAnimation()));
782    }
783
784    /**
785     * Like isOnScreen, but returns false if the surface hasn't yet
786     * been drawn.
787     */
788    public boolean isDisplayedLw() {
789        final AppWindowToken atoken = mAppToken;
790        return isDrawnLw() && mPolicyVisibility
791            && ((!mAttachedHidden &&
792                    (atoken == null || !atoken.hiddenRequested))
793                    || mWinAnimator.mAnimating);
794    }
795
796    /**
797     * Return true if this window (or a window it is attached to, but not
798     * considering its app token) is currently animating.
799     */
800    public boolean isAnimatingLw() {
801        return mWinAnimator.mAnimation != null;
802    }
803
804    public boolean isGoneForLayoutLw() {
805        final AppWindowToken atoken = mAppToken;
806        return mViewVisibility == View.GONE
807                || !mRelayoutCalled
808                || (atoken == null && mRootToken.hidden)
809                || (atoken != null && atoken.hiddenRequested)
810                || mAttachedHidden
811                || mExiting || mDestroying;
812    }
813
814    /**
815     * Returns true if the window has a surface that it has drawn a
816     * complete UI in to.
817     */
818    public boolean isDrawnLw() {
819        return mHasSurface && !mDestroying &&
820                (mWinAnimator.mDrawState == WindowStateAnimator.READY_TO_SHOW
821                || mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN);
822    }
823
824    /**
825     * Return true if the window is opaque and fully drawn.  This indicates
826     * it may obscure windows behind it.
827     */
828    boolean isOpaqueDrawn() {
829        return (mAttrs.format == PixelFormat.OPAQUE
830                        || mAttrs.type == TYPE_WALLPAPER)
831                && isDrawnLw() && mWinAnimator.mAnimation == null
832                && (mAppToken == null || mAppToken.mAppAnimator.animation == null);
833    }
834
835    /**
836     * Return whether this window is wanting to have a translation
837     * animation applied to it for an in-progress move.  (Only makes
838     * sense to call from performLayoutAndPlaceSurfacesLockedInner().)
839     */
840    boolean shouldAnimateMove() {
841        return mContentChanged && !mExiting && !mWinAnimator.mLastHidden && mService.okToDisplay()
842                && (mFrame.top != mLastFrame.top
843                        || mFrame.left != mLastFrame.left)
844                && (mAttachedWindow == null || !mAttachedWindow.shouldAnimateMove());
845    }
846
847    boolean isFullscreen(int screenWidth, int screenHeight) {
848        return mFrame.left <= 0 && mFrame.top <= 0 &&
849                mFrame.right >= screenWidth && mFrame.bottom >= screenHeight;
850    }
851
852    void removeLocked() {
853        disposeInputChannel();
854
855        if (mAttachedWindow != null) {
856            if (WindowManagerService.DEBUG_ADD_REMOVE) Slog.v(TAG, "Removing " + this + " from " + mAttachedWindow);
857            mAttachedWindow.mChildWindows.remove(this);
858        }
859        mWinAnimator.destroyDeferredSurfaceLocked();
860        mWinAnimator.destroySurfaceLocked();
861        mSession.windowRemovedLocked();
862        try {
863            mClient.asBinder().unlinkToDeath(mDeathRecipient, 0);
864        } catch (RuntimeException e) {
865            // Ignore if it has already been removed (usually because
866            // we are doing this as part of processing a death note.)
867        }
868    }
869
870    void setInputChannel(InputChannel inputChannel) {
871        if (mInputChannel != null) {
872            throw new IllegalStateException("Window already has an input channel.");
873        }
874
875        mInputChannel = inputChannel;
876        mInputWindowHandle.inputChannel = inputChannel;
877    }
878
879    void disposeInputChannel() {
880        if (mInputChannel != null) {
881            mService.mInputManager.unregisterInputChannel(mInputChannel);
882
883            mInputChannel.dispose();
884            mInputChannel = null;
885        }
886
887        mInputWindowHandle.inputChannel = null;
888    }
889
890    private class DeathRecipient implements IBinder.DeathRecipient {
891        public void binderDied() {
892            try {
893                synchronized(mService.mWindowMap) {
894                    WindowState win = mService.windowForClientLocked(mSession, mClient, false);
895                    Slog.i(TAG, "WIN DEATH: " + win);
896                    if (win != null) {
897                        mService.removeWindowLocked(mSession, win);
898                    }
899                }
900            } catch (IllegalArgumentException ex) {
901                // This will happen if the window has already been
902                // removed.
903            }
904        }
905    }
906
907    /** Returns true if this window desires key events.
908     * TODO(cmautner): Is this the same as {@link WindowManagerService#canBeImeTarget}
909     */
910    public final boolean canReceiveKeys() {
911        return     isVisibleOrAdding()
912                && (mViewVisibility == View.VISIBLE)
913                && ((mAttrs.flags & WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) == 0);
914    }
915
916    @Override
917    public boolean hasDrawnLw() {
918        return mWinAnimator.mDrawState == WindowStateAnimator.HAS_DRAWN;
919    }
920
921    @Override
922    public boolean showLw(boolean doAnimation) {
923        return showLw(doAnimation, true);
924    }
925
926    boolean showLw(boolean doAnimation, boolean requestAnim) {
927        if (isOtherUsersAppWindow()) {
928            Slog.w(TAG, "Current user " + mService.mCurrentUserId + " trying to display "
929                    + this + ", type " + mAttrs.type + ", belonging to " + mOwnerUid);
930            return false;
931        }
932        if (mPolicyVisibility && mPolicyVisibilityAfterAnim) {
933            // Already showing.
934            return false;
935        }
936        if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility true: " + this);
937        if (doAnimation) {
938            if (DEBUG_VISIBILITY) Slog.v(TAG, "doAnimation: mPolicyVisibility="
939                    + mPolicyVisibility + " mAnimation=" + mWinAnimator.mAnimation);
940            if (!mService.okToDisplay()) {
941                doAnimation = false;
942            } else if (mPolicyVisibility && mWinAnimator.mAnimation == null) {
943                // Check for the case where we are currently visible and
944                // not animating; we do not want to do animation at such a
945                // point to become visible when we already are.
946                doAnimation = false;
947            }
948        }
949        mPolicyVisibility = true;
950        mPolicyVisibilityAfterAnim = true;
951        if (doAnimation) {
952            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_ENTER, true);
953        }
954        if (requestAnim) {
955            mService.updateLayoutToAnimationLocked();
956        }
957        return true;
958    }
959
960    @Override
961    public boolean hideLw(boolean doAnimation) {
962        return hideLw(doAnimation, true);
963    }
964
965    boolean hideLw(boolean doAnimation, boolean requestAnim) {
966        if (doAnimation) {
967            if (!mService.okToDisplay()) {
968                doAnimation = false;
969            }
970        }
971        boolean current = doAnimation ? mPolicyVisibilityAfterAnim
972                : mPolicyVisibility;
973        if (!current) {
974            // Already hiding.
975            return false;
976        }
977        if (doAnimation) {
978            mWinAnimator.applyAnimationLocked(WindowManagerPolicy.TRANSIT_EXIT, false);
979            if (mWinAnimator.mAnimation == null) {
980                doAnimation = false;
981            }
982        }
983        if (doAnimation) {
984            mPolicyVisibilityAfterAnim = false;
985        } else {
986            if (DEBUG_VISIBILITY) Slog.v(TAG, "Policy visibility false: " + this);
987            mPolicyVisibilityAfterAnim = false;
988            mPolicyVisibility = false;
989            // Window is no longer visible -- make sure if we were waiting
990            // for it to be displayed before enabling the display, that
991            // we allow the display to be enabled now.
992            mService.enableScreenIfNeededLocked();
993            if (mService.mCurrentFocus == this) {
994                mService.mFocusMayChange = true;
995            }
996        }
997        if (requestAnim) {
998            mService.updateLayoutToAnimationLocked();
999        }
1000        return true;
1001    }
1002
1003    @Override
1004    public boolean isAlive() {
1005        return mClient.asBinder().isBinderAlive();
1006    }
1007
1008    @Override
1009    public boolean isDefaultDisplay() {
1010        return mDisplayContent.isDefaultDisplay;
1011    }
1012
1013    boolean isOtherUsersAppWindow() {
1014        final int type = mAttrs.type;
1015        if ((UserHandle.getUserId(mOwnerUid) != mService.mCurrentUserId)
1016                && (mOwnerUid != Process.SYSTEM_UID)
1017                && (type >= TYPE_BASE_APPLICATION) && (type <= LAST_APPLICATION_WINDOW)
1018                && (type != TYPE_APPLICATION_STARTING)) {
1019            return true;
1020        }
1021        return false;
1022    }
1023
1024    private static void applyInsets(Region outRegion, Rect frame, Rect inset) {
1025        outRegion.set(
1026                frame.left + inset.left, frame.top + inset.top,
1027                frame.right - inset.right, frame.bottom - inset.bottom);
1028    }
1029
1030    public void getTouchableRegion(Region outRegion) {
1031        final Rect frame = mFrame;
1032        switch (mTouchableInsets) {
1033            default:
1034            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_FRAME:
1035                outRegion.set(frame);
1036                break;
1037            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_CONTENT:
1038                applyInsets(outRegion, frame, mGivenContentInsets);
1039                break;
1040            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_VISIBLE:
1041                applyInsets(outRegion, frame, mGivenVisibleInsets);
1042                break;
1043            case ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION: {
1044                final Region givenTouchableRegion = mGivenTouchableRegion;
1045                outRegion.set(givenTouchableRegion);
1046                outRegion.translate(frame.left, frame.top);
1047                break;
1048            }
1049        }
1050    }
1051
1052    WindowList getWindowList() {
1053        return mDisplayContent.getWindowList();
1054    }
1055
1056    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1057        pw.print(prefix); pw.print("mDisplayId="); pw.print(mDisplayContent.getDisplayId());
1058                pw.print(" mSession="); pw.print(mSession);
1059                pw.print(" mClient="); pw.println(mClient.asBinder());
1060        pw.print(prefix); pw.print("mAttrs="); pw.println(mAttrs);
1061        pw.print(prefix); pw.print("Requested w="); pw.print(mRequestedWidth);
1062                pw.print(" h="); pw.print(mRequestedHeight);
1063                pw.print(" mLayoutSeq="); pw.println(mLayoutSeq);
1064        if (mRequestedWidth != mLastRequestedWidth || mRequestedHeight != mLastRequestedHeight) {
1065            pw.print(prefix); pw.print("LastRequested w="); pw.print(mLastRequestedWidth);
1066                    pw.print(" h="); pw.println(mLastRequestedHeight);
1067        }
1068        if (mAttachedWindow != null || mLayoutAttached) {
1069            pw.print(prefix); pw.print("mAttachedWindow="); pw.print(mAttachedWindow);
1070                    pw.print(" mLayoutAttached="); pw.println(mLayoutAttached);
1071        }
1072        if (mIsImWindow || mIsWallpaper || mIsFloatingLayer) {
1073            pw.print(prefix); pw.print("mIsImWindow="); pw.print(mIsImWindow);
1074                    pw.print(" mIsWallpaper="); pw.print(mIsWallpaper);
1075                    pw.print(" mIsFloatingLayer="); pw.print(mIsFloatingLayer);
1076                    pw.print(" mWallpaperVisible="); pw.println(mWallpaperVisible);
1077        }
1078        if (dumpAll) {
1079            pw.print(prefix); pw.print("mBaseLayer="); pw.print(mBaseLayer);
1080                    pw.print(" mSubLayer="); pw.print(mSubLayer);
1081                    pw.print(" mAnimLayer="); pw.print(mLayer); pw.print("+");
1082                    pw.print((mTargetAppToken != null ?
1083                            mTargetAppToken.mAppAnimator.animLayerAdjustment
1084                          : (mAppToken != null ? mAppToken.mAppAnimator.animLayerAdjustment : 0)));
1085                    pw.print("="); pw.print(mWinAnimator.mAnimLayer);
1086                    pw.print(" mLastLayer="); pw.println(mWinAnimator.mLastLayer);
1087        }
1088        if (dumpAll) {
1089            pw.print(prefix); pw.print("mToken="); pw.println(mToken);
1090            pw.print(prefix); pw.print("mRootToken="); pw.println(mRootToken);
1091            if (mAppToken != null) {
1092                pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
1093            }
1094            if (mTargetAppToken != null) {
1095                pw.print(prefix); pw.print("mTargetAppToken="); pw.println(mTargetAppToken);
1096            }
1097            pw.print(prefix); pw.print("mViewVisibility=0x");
1098            pw.print(Integer.toHexString(mViewVisibility));
1099            pw.print(" mHaveFrame="); pw.print(mHaveFrame);
1100            pw.print(" mObscured="); pw.println(mObscured);
1101            pw.print(prefix); pw.print("mSeq="); pw.print(mSeq);
1102            pw.print(" mSystemUiVisibility=0x");
1103            pw.println(Integer.toHexString(mSystemUiVisibility));
1104        }
1105        if (!mPolicyVisibility || !mPolicyVisibilityAfterAnim || mAttachedHidden) {
1106            pw.print(prefix); pw.print("mPolicyVisibility=");
1107                    pw.print(mPolicyVisibility);
1108                    pw.print(" mPolicyVisibilityAfterAnim=");
1109                    pw.print(mPolicyVisibilityAfterAnim);
1110                    pw.print(" mAttachedHidden="); pw.println(mAttachedHidden);
1111        }
1112        if (!mRelayoutCalled || mLayoutNeeded) {
1113            pw.print(prefix); pw.print("mRelayoutCalled="); pw.print(mRelayoutCalled);
1114                    pw.print(" mLayoutNeeded="); pw.println(mLayoutNeeded);
1115        }
1116        if (mXOffset != 0 || mYOffset != 0) {
1117            pw.print(prefix); pw.print("Offsets x="); pw.print(mXOffset);
1118                    pw.print(" y="); pw.println(mYOffset);
1119        }
1120        if (dumpAll) {
1121            pw.print(prefix); pw.print("mGivenContentInsets=");
1122                    mGivenContentInsets.printShortString(pw);
1123                    pw.print(" mGivenVisibleInsets=");
1124                    mGivenVisibleInsets.printShortString(pw);
1125                    pw.println();
1126            if (mTouchableInsets != 0 || mGivenInsetsPending) {
1127                pw.print(prefix); pw.print("mTouchableInsets="); pw.print(mTouchableInsets);
1128                        pw.print(" mGivenInsetsPending="); pw.println(mGivenInsetsPending);
1129                Region region = new Region();
1130                getTouchableRegion(region);
1131                pw.print(prefix); pw.print("touchable region="); pw.println(region);
1132            }
1133            pw.print(prefix); pw.print("mConfiguration="); pw.println(mConfiguration);
1134        }
1135        pw.print(prefix); pw.print("mHasSurface="); pw.print(mHasSurface);
1136                pw.print(" mShownFrame="); mShownFrame.printShortString(pw);
1137                pw.print(" isReadyForDisplay()="); pw.println(isReadyForDisplay());
1138        if (dumpAll) {
1139            pw.print(prefix); pw.print("mFrame="); mFrame.printShortString(pw);
1140                    pw.print(" last="); mLastFrame.printShortString(pw);
1141                    pw.println();
1142            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
1143                    pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
1144                    pw.println();
1145        }
1146        if (mEnforceSizeCompat) {
1147            pw.print(prefix); pw.print("mCompatFrame="); mCompatFrame.printShortString(pw);
1148                    pw.println();
1149        }
1150        if (dumpAll) {
1151            pw.print(prefix); pw.print("Frames: containing=");
1152                    mContainingFrame.printShortString(pw);
1153                    pw.print(" parent="); mParentFrame.printShortString(pw);
1154                    pw.print(" display="); mDisplayFrame.printShortString(pw);
1155                    pw.println();
1156            pw.print(prefix); pw.print("    content="); mContentFrame.printShortString(pw);
1157                    pw.print(" visible="); mVisibleFrame.printShortString(pw);
1158                    pw.println();
1159            pw.print(prefix); pw.print("Cur insets: content=");
1160                    mContentInsets.printShortString(pw);
1161                    pw.print(" visible="); mVisibleInsets.printShortString(pw);
1162                    pw.println();
1163            pw.print(prefix); pw.print("Lst insets: content=");
1164                    mLastContentInsets.printShortString(pw);
1165                    pw.print(" visible="); mLastVisibleInsets.printShortString(pw);
1166                    pw.println();
1167        }
1168        mWinAnimator.dump(pw, prefix, dumpAll);
1169        if (mExiting || mRemoveOnExit || mDestroying || mRemoved) {
1170            pw.print(prefix); pw.print("mExiting="); pw.print(mExiting);
1171                    pw.print(" mRemoveOnExit="); pw.print(mRemoveOnExit);
1172                    pw.print(" mDestroying="); pw.print(mDestroying);
1173                    pw.print(" mRemoved="); pw.println(mRemoved);
1174        }
1175        if (mOrientationChanging || mAppFreezing || mTurnOnScreen) {
1176            pw.print(prefix); pw.print("mOrientationChanging=");
1177                    pw.print(mOrientationChanging);
1178                    pw.print(" mAppFreezing="); pw.print(mAppFreezing);
1179                    pw.print(" mTurnOnScreen="); pw.println(mTurnOnScreen);
1180        }
1181        if (mHScale != 1 || mVScale != 1) {
1182            pw.print(prefix); pw.print("mHScale="); pw.print(mHScale);
1183                    pw.print(" mVScale="); pw.println(mVScale);
1184        }
1185        if (mWallpaperX != -1 || mWallpaperY != -1) {
1186            pw.print(prefix); pw.print("mWallpaperX="); pw.print(mWallpaperX);
1187                    pw.print(" mWallpaperY="); pw.println(mWallpaperY);
1188        }
1189        if (mWallpaperXStep != -1 || mWallpaperYStep != -1) {
1190            pw.print(prefix); pw.print("mWallpaperXStep="); pw.print(mWallpaperXStep);
1191                    pw.print(" mWallpaperYStep="); pw.println(mWallpaperYStep);
1192        }
1193    }
1194
1195    String makeInputChannelName() {
1196        return Integer.toHexString(System.identityHashCode(this))
1197            + " " + mAttrs.getTitle();
1198    }
1199
1200    @Override
1201    public String toString() {
1202        if (mStringNameCache == null || mLastTitle != mAttrs.getTitle()
1203                || mWasPaused != mToken.paused) {
1204            mLastTitle = mAttrs.getTitle();
1205            mWasPaused = mToken.paused;
1206            mStringNameCache = "Window{" + Integer.toHexString(System.identityHashCode(this))
1207                    + " " + mLastTitle + " paused=" + mWasPaused + "}";
1208        }
1209        return mStringNameCache;
1210    }
1211}
1212