WindowStateAnimator.java revision 9128396982233d6af49613231100f1bc4b6c477b
1/*
2 * Copyright (C) 2014 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.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
20import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_STARTING;
21import static com.android.server.wm.WindowManagerService.DEBUG_ANIM;
22import static com.android.server.wm.WindowManagerService.DEBUG_LAYERS;
23import static com.android.server.wm.WindowManagerService.DEBUG_ORIENTATION;
24import static com.android.server.wm.WindowManagerService.DEBUG_STARTING_WINDOW;
25import static com.android.server.wm.WindowManagerService.DEBUG_SURFACE_TRACE;
26import static com.android.server.wm.WindowManagerService.SHOW_TRANSACTIONS;
27import static com.android.server.wm.WindowManagerService.DEBUG_VISIBILITY;
28import static com.android.server.wm.WindowManagerService.SHOW_LIGHT_TRANSACTIONS;
29import static com.android.server.wm.WindowManagerService.SHOW_SURFACE_ALLOC;
30import static com.android.server.wm.WindowManagerService.localLOGV;
31import static com.android.server.wm.WindowManagerService.LayoutFields.SET_ORIENTATION_CHANGE_COMPLETE;
32import static com.android.server.wm.WindowManagerService.LayoutFields.SET_TURN_ON_SCREEN;
33
34import android.content.Context;
35import android.graphics.Matrix;
36import android.graphics.PixelFormat;
37import android.graphics.Point;
38import android.graphics.PointF;
39import android.graphics.Rect;
40import android.graphics.RectF;
41import android.graphics.Region;
42import android.os.Debug;
43import android.os.RemoteException;
44import android.os.UserHandle;
45import android.util.Slog;
46import android.view.Display;
47import android.view.DisplayInfo;
48import android.view.MagnificationSpec;
49import android.view.Surface.OutOfResourcesException;
50import android.view.SurfaceControl;
51import android.view.SurfaceSession;
52import android.view.View;
53import android.view.WindowManager;
54import android.view.WindowManagerPolicy;
55import android.view.WindowManager.LayoutParams;
56import android.view.animation.Animation;
57import android.view.animation.AnimationUtils;
58import android.view.animation.Transformation;
59
60import com.android.server.wm.WindowManagerService.H;
61
62import java.io.PrintWriter;
63import java.util.ArrayList;
64
65class WinAnimatorList extends ArrayList<WindowStateAnimator> {
66}
67
68/**
69 * Keep track of animations and surface operations for a single WindowState.
70 **/
71class WindowStateAnimator {
72    static final String TAG = "WindowStateAnimator";
73
74    // Unchanging local convenience fields.
75    final WindowManagerService mService;
76    final WindowState mWin;
77    final WindowStateAnimator mAttachedWinAnimator;
78    final WindowAnimator mAnimator;
79    AppWindowAnimator mAppAnimator;
80    final Session mSession;
81    final WindowManagerPolicy mPolicy;
82    final Context mContext;
83    final boolean mIsWallpaper;
84
85    // If this is a universe background window, this is the transformation
86    // it is applying to the rest of the universe.
87    final Transformation mUniverseTransform = new Transformation();
88
89    // Currently running animation.
90    boolean mAnimating;
91    boolean mLocalAnimating;
92    Animation mAnimation;
93    boolean mAnimationIsEntrance;
94    boolean mHasTransformation;
95    boolean mHasLocalTransformation;
96    final Transformation mTransformation = new Transformation();
97    boolean mWasAnimating;      // Were we animating going into the most recent animation step?
98    int mAnimLayer;
99    int mLastLayer;
100
101    SurfaceControl mSurfaceControl;
102    SurfaceControl mPendingDestroySurface;
103
104    /**
105     * Set when we have changed the size of the surface, to know that
106     * we must tell them application to resize (and thus redraw itself).
107     */
108    boolean mSurfaceResized;
109
110    /**
111     * Set if the client has asked that the destroy of its surface be delayed
112     * until it explicitly says it is okay.
113     */
114    boolean mSurfaceDestroyDeferred;
115
116    float mShownAlpha = 0;
117    float mAlpha = 0;
118    float mLastAlpha = 0;
119
120    boolean mHasClipRect;
121    Rect mClipRect = new Rect();
122    Rect mTmpClipRect = new Rect();
123    Rect mLastClipRect = new Rect();
124
125    // Used to save animation distances between the time they are calculated and when they are
126    // used.
127    int mAnimDw;
128    int mAnimDh;
129    float mDsDx=1, mDtDx=0, mDsDy=0, mDtDy=1;
130    float mLastDsDx=1, mLastDtDx=0, mLastDsDy=0, mLastDtDy=1;
131
132    boolean mHaveMatrix;
133
134    // For debugging, this is the last information given to the surface flinger.
135    boolean mSurfaceShown;
136    float mSurfaceX, mSurfaceY;
137    float mSurfaceW, mSurfaceH;
138    int mSurfaceLayer;
139    float mSurfaceAlpha;
140
141    // Set to true if, when the window gets displayed, it should perform
142    // an enter animation.
143    boolean mEnterAnimationPending;
144
145    /** Used to indicate that this window is undergoing an enter animation. Used for system
146     * windows to make the callback to View.dispatchOnWindowShownCallback(). Set when the
147     * window is first added or shown, cleared when the callback has been made. */
148    boolean mEnteringAnimation;
149
150    boolean keyguardGoingAwayAnimation;
151
152    /** This is set when there is no Surface */
153    static final int NO_SURFACE = 0;
154    /** This is set after the Surface has been created but before the window has been drawn. During
155     * this time the surface is hidden. */
156    static final int DRAW_PENDING = 1;
157    /** This is set after the window has finished drawing for the first time but before its surface
158     * is shown.  The surface will be displayed when the next layout is run. */
159    static final int COMMIT_DRAW_PENDING = 2;
160    /** This is set during the time after the window's drawing has been committed, and before its
161     * surface is actually shown.  It is used to delay showing the surface until all windows in a
162     * token are ready to be shown. */
163    static final int READY_TO_SHOW = 3;
164    /** Set when the window has been shown in the screen the first time. */
165    static final int HAS_DRAWN = 4;
166
167    private static final int SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN =
168            View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
169
170    String drawStateToString() {
171        switch (mDrawState) {
172            case NO_SURFACE: return "NO_SURFACE";
173            case DRAW_PENDING: return "DRAW_PENDING";
174            case COMMIT_DRAW_PENDING: return "COMMIT_DRAW_PENDING";
175            case READY_TO_SHOW: return "READY_TO_SHOW";
176            case HAS_DRAWN: return "HAS_DRAWN";
177            default: return Integer.toString(mDrawState);
178        }
179    }
180    int mDrawState;
181
182    /** Was this window last hidden? */
183    boolean mLastHidden;
184
185    int mAttrType;
186
187    public WindowStateAnimator(final WindowState win) {
188        final WindowManagerService service = win.mService;
189
190        mService = service;
191        mAnimator = service.mAnimator;
192        mPolicy = service.mPolicy;
193        mContext = service.mContext;
194        final DisplayContent displayContent = win.getDisplayContent();
195        if (displayContent != null) {
196            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
197            mAnimDw = displayInfo.appWidth;
198            mAnimDh = displayInfo.appHeight;
199        } else {
200            Slog.w(TAG, "WindowStateAnimator ctor: Display has been removed");
201            // This is checked on return and dealt with.
202        }
203
204        mWin = win;
205        mAttachedWinAnimator = win.mAttachedWindow == null
206                ? null : win.mAttachedWindow.mWinAnimator;
207        mAppAnimator = win.mAppToken == null ? null : win.mAppToken.mAppAnimator;
208        mSession = win.mSession;
209        mAttrType = win.mAttrs.type;
210        mIsWallpaper = win.mIsWallpaper;
211    }
212
213    public void setAnimation(Animation anim) {
214        if (localLOGV) Slog.v(TAG, "Setting animation in " + this + ": " + anim);
215        mAnimating = false;
216        mLocalAnimating = false;
217        mAnimation = anim;
218        mAnimation.restrictDuration(WindowManagerService.MAX_ANIMATION_DURATION);
219        mAnimation.scaleCurrentDuration(mService.getWindowAnimationScaleLocked());
220        // Start out animation gone if window is gone, or visible if window is visible.
221        mTransformation.clear();
222        mTransformation.setAlpha(mLastHidden ? 0 : 1);
223        mHasLocalTransformation = true;
224    }
225
226    public void clearAnimation() {
227        if (mAnimation != null) {
228            mAnimating = true;
229            mLocalAnimating = false;
230            mAnimation.cancel();
231            mAnimation = null;
232            keyguardGoingAwayAnimation = false;
233        }
234    }
235
236    /** Is the window or its container currently animating? */
237    boolean isAnimating() {
238        return mAnimation != null
239                || (mAttachedWinAnimator != null && mAttachedWinAnimator.mAnimation != null)
240                || (mAppAnimator != null &&
241                        (mAppAnimator.animation != null
242                                || mAppAnimator.mAppToken.inPendingTransaction));
243    }
244
245    /** Is the window animating the DummyAnimation? */
246    boolean isDummyAnimation() {
247        return mAppAnimator != null
248                && mAppAnimator.animation == AppWindowAnimator.sDummyAnimation;
249    }
250
251    /** Is this window currently animating? */
252    boolean isWindowAnimating() {
253        return mAnimation != null;
254    }
255
256    void cancelExitAnimationForNextAnimationLocked() {
257        if (mAnimation != null) {
258            mAnimation.cancel();
259            mAnimation = null;
260            mLocalAnimating = false;
261            destroySurfaceLocked();
262        }
263    }
264
265    private boolean stepAnimation(long currentTime) {
266        if ((mAnimation == null) || !mLocalAnimating) {
267            return false;
268        }
269        mTransformation.clear();
270        final boolean more = mAnimation.getTransformation(currentTime, mTransformation);
271        if (false && DEBUG_ANIM) Slog.v(
272            TAG, "Stepped animation in " + this +
273            ": more=" + more + ", xform=" + mTransformation);
274        return more;
275    }
276
277    // This must be called while inside a transaction.  Returns true if
278    // there is more animation to run.
279    boolean stepAnimationLocked(long currentTime) {
280        // Save the animation state as it was before this step so WindowManagerService can tell if
281        // we just started or just stopped animating by comparing mWasAnimating with isAnimating().
282        mWasAnimating = mAnimating;
283        final DisplayContent displayContent = mWin.getDisplayContent();
284        if (displayContent != null && mService.okToDisplay()) {
285            // We will run animations as long as the display isn't frozen.
286
287            if (mWin.isDrawnLw() && mAnimation != null) {
288                mHasTransformation = true;
289                mHasLocalTransformation = true;
290                if (!mLocalAnimating) {
291                    if (DEBUG_ANIM) Slog.v(
292                        TAG, "Starting animation in " + this +
293                        " @ " + currentTime + ": ww=" + mWin.mFrame.width() +
294                        " wh=" + mWin.mFrame.height() +
295                        " dw=" + mAnimDw + " dh=" + mAnimDh +
296                        " scale=" + mService.getWindowAnimationScaleLocked());
297                    mAnimation.initialize(mWin.mFrame.width(), mWin.mFrame.height(),
298                            mAnimDw, mAnimDh);
299                    final DisplayInfo displayInfo = displayContent.getDisplayInfo();
300                    mAnimDw = displayInfo.appWidth;
301                    mAnimDh = displayInfo.appHeight;
302                    mAnimation.setStartTime(currentTime);
303                    mLocalAnimating = true;
304                    mAnimating = true;
305                }
306                if ((mAnimation != null) && mLocalAnimating) {
307                    if (stepAnimation(currentTime)) {
308                        return true;
309                    }
310                }
311                if (DEBUG_ANIM) Slog.v(
312                    TAG, "Finished animation in " + this +
313                    " @ " + currentTime);
314                //WindowManagerService.this.dump();
315            }
316            mHasLocalTransformation = false;
317            if ((!mLocalAnimating || mAnimationIsEntrance) && mAppAnimator != null
318                    && mAppAnimator.animation != null) {
319                // When our app token is animating, we kind-of pretend like
320                // we are as well.  Note the mLocalAnimating mAnimationIsEntrance
321                // part of this check means that we will only do this if
322                // our window is not currently exiting, or it is not
323                // locally animating itself.  The idea being that one that
324                // is exiting and doing a local animation should be removed
325                // once that animation is done.
326                mAnimating = true;
327                mHasTransformation = true;
328                mTransformation.clear();
329                return false;
330            } else if (mHasTransformation) {
331                // Little trick to get through the path below to act like
332                // we have finished an animation.
333                mAnimating = true;
334            } else if (isAnimating()) {
335                mAnimating = true;
336            }
337        } else if (mAnimation != null) {
338            // If the display is frozen, and there is a pending animation,
339            // clear it and make sure we run the cleanup code.
340            mAnimating = true;
341        }
342
343        if (!mAnimating && !mLocalAnimating) {
344            return false;
345        }
346
347        // Done animating, clean up.
348        if (DEBUG_ANIM) Slog.v(
349            TAG, "Animation done in " + this + ": exiting=" + mWin.mExiting
350            + ", reportedVisible="
351            + (mWin.mAppToken != null ? mWin.mAppToken.reportedVisible : false));
352
353        mAnimating = false;
354        keyguardGoingAwayAnimation = false;
355        mLocalAnimating = false;
356        if (mAnimation != null) {
357            mAnimation.cancel();
358            mAnimation = null;
359        }
360        if (mAnimator.mWindowDetachedWallpaper == mWin) {
361            mAnimator.mWindowDetachedWallpaper = null;
362        }
363        mAnimLayer = mWin.mLayer;
364        if (mWin.mIsImWindow) {
365            mAnimLayer += mService.mInputMethodAnimLayerAdjustment;
366        } else if (mIsWallpaper) {
367            mAnimLayer += mService.mWallpaperAnimLayerAdjustment;
368        }
369        if (DEBUG_LAYERS) Slog.v(TAG, "Stepping win " + this
370                + " anim layer: " + mAnimLayer);
371        mHasTransformation = false;
372        mHasLocalTransformation = false;
373        if (mWin.mPolicyVisibility != mWin.mPolicyVisibilityAfterAnim) {
374            if (DEBUG_VISIBILITY) {
375                Slog.v(TAG, "Policy visibility changing after anim in " + this + ": "
376                        + mWin.mPolicyVisibilityAfterAnim);
377            }
378            mWin.mPolicyVisibility = mWin.mPolicyVisibilityAfterAnim;
379            if (displayContent != null) {
380                displayContent.layoutNeeded = true;
381            }
382            if (!mWin.mPolicyVisibility) {
383                if (mService.mCurrentFocus == mWin) {
384                    if (WindowManagerService.DEBUG_FOCUS_LIGHT) Slog.i(TAG,
385                            "setAnimationLocked: setting mFocusMayChange true");
386                    mService.mFocusMayChange = true;
387                }
388                // Window is no longer visible -- make sure if we were waiting
389                // for it to be displayed before enabling the display, that
390                // we allow the display to be enabled now.
391                mService.enableScreenIfNeededLocked();
392            }
393        }
394        mTransformation.clear();
395        if (mDrawState == HAS_DRAWN
396                && mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING
397                && mWin.mAppToken != null
398                && mWin.mAppToken.firstWindowDrawn
399                && mWin.mAppToken.startingData != null) {
400            if (DEBUG_STARTING_WINDOW) Slog.v(TAG, "Finish starting "
401                    + mWin.mToken + ": first real window done animating");
402            mService.mFinishedStarting.add(mWin.mAppToken);
403            mService.mH.sendEmptyMessage(H.FINISHED_STARTING);
404        } else if (mAttrType == LayoutParams.TYPE_STATUS_BAR && mWin.mPolicyVisibility) {
405            // Upon completion of a not-visible to visible status bar animation a relayout is
406            // required.
407            if (displayContent != null) {
408                displayContent.layoutNeeded = true;
409            }
410        }
411
412        finishExit();
413        final int displayId = mWin.getDisplayId();
414        mAnimator.setPendingLayoutChanges(displayId, WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM);
415        if (WindowManagerService.DEBUG_LAYOUT_REPEATS) mService.debugLayoutRepeats(
416                "WindowStateAnimator", mAnimator.getPendingLayoutChanges(displayId));
417
418        if (mWin.mAppToken != null) {
419            mWin.mAppToken.updateReportedVisibilityLocked();
420        }
421
422        return false;
423    }
424
425    void finishExit() {
426        if (WindowManagerService.DEBUG_ANIM) Slog.v(
427                TAG, "finishExit in " + this
428                + ": exiting=" + mWin.mExiting
429                + " remove=" + mWin.mRemoveOnExit
430                + " windowAnimating=" + isWindowAnimating());
431
432        final int N = mWin.mChildWindows.size();
433        for (int i=0; i<N; i++) {
434            mWin.mChildWindows.get(i).mWinAnimator.finishExit();
435        }
436
437        if (mEnteringAnimation && mWin.mAppToken == null) {
438            try {
439                mEnteringAnimation = false;
440                mWin.mClient.dispatchWindowShown();
441            } catch (RemoteException e) {
442            }
443        }
444
445        if (!mWin.mExiting) {
446            return;
447        }
448
449        if (isWindowAnimating()) {
450            return;
451        }
452
453        if (WindowManagerService.localLOGV) Slog.v(
454                TAG, "Exit animation finished in " + this
455                + ": remove=" + mWin.mRemoveOnExit);
456        if (mSurfaceControl != null) {
457            mService.mDestroySurface.add(mWin);
458            mWin.mDestroying = true;
459            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(
460                mWin, "HIDE (finishExit)", null);
461            hide();
462        }
463        mWin.mExiting = false;
464        if (mWin.mRemoveOnExit) {
465            mService.mPendingRemove.add(mWin);
466            mWin.mRemoveOnExit = false;
467        }
468        mAnimator.hideWallpapersLocked(mWin);
469    }
470
471    void hide() {
472        if (!mLastHidden) {
473            //dump();
474            mLastHidden = true;
475            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
476                    "HIDE (performLayout)", null);
477            if (mSurfaceControl != null) {
478                mSurfaceShown = false;
479                try {
480                    mSurfaceControl.hide();
481                } catch (RuntimeException e) {
482                    Slog.w(TAG, "Exception hiding surface in " + mWin);
483                }
484            }
485        }
486    }
487
488    boolean finishDrawingLocked() {
489        if (DEBUG_STARTING_WINDOW &&
490                mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
491            Slog.v(TAG, "Finishing drawing window " + mWin + ": mDrawState="
492                    + drawStateToString());
493        }
494        if (mDrawState == DRAW_PENDING) {
495            if (DEBUG_SURFACE_TRACE || DEBUG_ANIM || SHOW_TRANSACTIONS || DEBUG_ORIENTATION)
496                Slog.v(TAG, "finishDrawingLocked: mDrawState=COMMIT_DRAW_PENDING " + this + " in "
497                        + mSurfaceControl);
498            if (DEBUG_STARTING_WINDOW &&
499                    mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
500                Slog.v(TAG, "Draw state now committed in " + mWin);
501            }
502            mDrawState = COMMIT_DRAW_PENDING;
503            return true;
504        }
505        return false;
506    }
507
508    // This must be called while inside a transaction.
509    boolean commitFinishDrawingLocked(long currentTime) {
510        if (DEBUG_STARTING_WINDOW &&
511                mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING) {
512            Slog.i(TAG, "commitFinishDrawingLocked: " + mWin + " cur mDrawState="
513                    + drawStateToString());
514        }
515        if (mDrawState != COMMIT_DRAW_PENDING && mDrawState != READY_TO_SHOW) {
516            return false;
517        }
518        if (DEBUG_SURFACE_TRACE || DEBUG_ANIM) {
519            Slog.i(TAG, "commitFinishDrawingLocked: mDrawState=READY_TO_SHOW " + mSurfaceControl);
520        }
521        mDrawState = READY_TO_SHOW;
522        final AppWindowToken atoken = mWin.mAppToken;
523        if (atoken == null || atoken.allDrawn || mWin.mAttrs.type == TYPE_APPLICATION_STARTING) {
524            performShowLocked();
525        }
526        return true;
527    }
528
529    static class SurfaceTrace extends SurfaceControl {
530        private final static String SURFACE_TAG = "SurfaceTrace";
531        private final static boolean logSurfaceTrace = DEBUG_SURFACE_TRACE;
532        final static ArrayList<SurfaceTrace> sSurfaces = new ArrayList<SurfaceTrace>();
533
534        private float mSurfaceTraceAlpha = 0;
535        private int mLayer;
536        private final PointF mPosition = new PointF();
537        private final Point mSize = new Point();
538        private final Rect mWindowCrop = new Rect();
539        private boolean mShown = false;
540        private int mLayerStack;
541        private boolean mIsOpaque;
542        private float mDsdx, mDtdx, mDsdy, mDtdy;
543        private final String mName;
544
545        public SurfaceTrace(SurfaceSession s,
546                       String name, int w, int h, int format, int flags)
547                   throws OutOfResourcesException {
548            super(s, name, w, h, format, flags);
549            mName = name != null ? name : "Not named";
550            mSize.set(w, h);
551            if (logSurfaceTrace) Slog.v(SURFACE_TAG, "ctor: " + this + ". Called by "
552                    + Debug.getCallers(3));
553            synchronized (sSurfaces) {
554                sSurfaces.add(0, this);
555            }
556        }
557
558        @Override
559        public void setAlpha(float alpha) {
560            if (mSurfaceTraceAlpha != alpha) {
561                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setAlpha(" + alpha + "): OLD:" + this +
562                        ". Called by " + Debug.getCallers(3));
563                mSurfaceTraceAlpha = alpha;
564            }
565            super.setAlpha(alpha);
566        }
567
568        @Override
569        public void setLayer(int zorder) {
570            if (zorder != mLayer) {
571                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setLayer(" + zorder + "): OLD:" + this
572                        + ". Called by " + Debug.getCallers(3));
573                mLayer = zorder;
574            }
575            super.setLayer(zorder);
576
577            synchronized (sSurfaces) {
578                sSurfaces.remove(this);
579                int i;
580                for (i = sSurfaces.size() - 1; i >= 0; i--) {
581                    SurfaceTrace s = sSurfaces.get(i);
582                    if (s.mLayer < zorder) {
583                        break;
584                    }
585                }
586                sSurfaces.add(i + 1, this);
587            }
588        }
589
590        @Override
591        public void setPosition(float x, float y) {
592            if (x != mPosition.x || y != mPosition.y) {
593                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setPosition(" + x + "," + y + "): OLD:"
594                        + this + ". Called by " + Debug.getCallers(3));
595                mPosition.set(x, y);
596            }
597            super.setPosition(x, y);
598        }
599
600        @Override
601        public void setSize(int w, int h) {
602            if (w != mSize.x || h != mSize.y) {
603                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setSize(" + w + "," + h + "): OLD:"
604                        + this + ". Called by " + Debug.getCallers(3));
605                mSize.set(w, h);
606            }
607            super.setSize(w, h);
608        }
609
610        @Override
611        public void setWindowCrop(Rect crop) {
612            if (crop != null) {
613                if (!crop.equals(mWindowCrop)) {
614                    if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setWindowCrop("
615                            + crop.toShortString() + "): OLD:" + this + ". Called by "
616                            + Debug.getCallers(3));
617                    mWindowCrop.set(crop);
618                }
619            }
620            super.setWindowCrop(crop);
621        }
622
623        @Override
624        public void setLayerStack(int layerStack) {
625            if (layerStack != mLayerStack) {
626                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setLayerStack(" + layerStack + "): OLD:"
627                        + this + ". Called by " + Debug.getCallers(3));
628                mLayerStack = layerStack;
629            }
630            super.setLayerStack(layerStack);
631        }
632
633        @Override
634        public void setOpaque(boolean isOpaque) {
635            if (isOpaque != mIsOpaque) {
636                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setOpaque(" + isOpaque + "): OLD:"
637                        + this + ". Called by " + Debug.getCallers(3));
638                mIsOpaque = isOpaque;
639            }
640            super.setOpaque(isOpaque);
641        }
642
643        @Override
644        public void setMatrix(float dsdx, float dtdx, float dsdy, float dtdy) {
645            if (dsdx != mDsdx || dtdx != mDtdx || dsdy != mDsdy || dtdy != mDtdy) {
646                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "setMatrix(" + dsdx + "," + dtdx + ","
647                        + dsdy + "," + dtdy + "): OLD:" + this + ". Called by "
648                        + Debug.getCallers(3));
649                mDsdx = dsdx;
650                mDtdx = dtdx;
651                mDsdy = dsdy;
652                mDtdy = dtdy;
653            }
654            super.setMatrix(dsdx, dtdx, dsdy, dtdy);
655        }
656
657        @Override
658        public void hide() {
659            if (mShown) {
660                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "hide: OLD:" + this + ". Called by "
661                        + Debug.getCallers(3));
662                mShown = false;
663            }
664            super.hide();
665        }
666
667        @Override
668        public void show() {
669            if (!mShown) {
670                if (logSurfaceTrace) Slog.v(SURFACE_TAG, "show: OLD:" + this + ". Called by "
671                        + Debug.getCallers(3));
672                mShown = true;
673            }
674            super.show();
675        }
676
677        @Override
678        public void destroy() {
679            super.destroy();
680            if (logSurfaceTrace) Slog.v(SURFACE_TAG, "destroy: " + this + ". Called by "
681                    + Debug.getCallers(3));
682            synchronized (sSurfaces) {
683                sSurfaces.remove(this);
684            }
685        }
686
687        @Override
688        public void release() {
689            super.release();
690            if (logSurfaceTrace) Slog.v(SURFACE_TAG, "release: " + this + ". Called by "
691                    + Debug.getCallers(3));
692            synchronized (sSurfaces) {
693                sSurfaces.remove(this);
694            }
695        }
696
697        static void dumpAllSurfaces(PrintWriter pw, String header) {
698            synchronized (sSurfaces) {
699                final int N = sSurfaces.size();
700                if (N <= 0) {
701                    return;
702                }
703                if (header != null) {
704                    pw.println(header);
705                }
706                pw.println("WINDOW MANAGER SURFACES (dumpsys window surfaces)");
707                for (int i = 0; i < N; i++) {
708                    SurfaceTrace s = sSurfaces.get(i);
709                    pw.print("  Surface #"); pw.print(i); pw.print(": #");
710                            pw.print(Integer.toHexString(System.identityHashCode(s)));
711                            pw.print(" "); pw.println(s.mName);
712                    pw.print("    mLayerStack="); pw.print(s.mLayerStack);
713                            pw.print(" mLayer="); pw.println(s.mLayer);
714                    pw.print("    mShown="); pw.print(s.mShown); pw.print(" mAlpha=");
715                            pw.print(s.mSurfaceTraceAlpha); pw.print(" mIsOpaque=");
716                            pw.println(s.mIsOpaque);
717                    pw.print("    mPosition="); pw.print(s.mPosition.x); pw.print(",");
718                            pw.print(s.mPosition.y);
719                            pw.print(" mSize="); pw.print(s.mSize.x); pw.print("x");
720                            pw.println(s.mSize.y);
721                    pw.print("    mCrop="); s.mWindowCrop.printShortString(pw); pw.println();
722                    pw.print("    Transform: ("); pw.print(s.mDsdx); pw.print(", ");
723                            pw.print(s.mDtdx); pw.print(", "); pw.print(s.mDsdy);
724                            pw.print(", "); pw.print(s.mDtdy); pw.println(")");
725                }
726            }
727        }
728
729        @Override
730        public String toString() {
731            return "Surface " + Integer.toHexString(System.identityHashCode(this)) + " "
732                    + mName + " (" + mLayerStack + "): shown=" + mShown + " layer=" + mLayer
733                    + " alpha=" + mSurfaceTraceAlpha + " " + mPosition.x + "," + mPosition.y
734                    + " " + mSize.x + "x" + mSize.y
735                    + " crop=" + mWindowCrop.toShortString()
736                    + " opaque=" + mIsOpaque
737                    + " (" + mDsdx + "," + mDtdx + "," + mDsdy + "," + mDtdy + ")";
738        }
739    }
740
741    SurfaceControl createSurfaceLocked() {
742        final WindowState w = mWin;
743        if (mSurfaceControl == null) {
744            if (DEBUG_ANIM || DEBUG_ORIENTATION) Slog.i(TAG,
745                    "createSurface " + this + ": mDrawState=DRAW_PENDING");
746            mDrawState = DRAW_PENDING;
747            if (w.mAppToken != null) {
748                if (w.mAppToken.mAppAnimator.animation == null) {
749                    w.mAppToken.allDrawn = false;
750                    w.mAppToken.deferClearAllDrawn = false;
751                } else {
752                    // Currently animating, persist current state of allDrawn until animation
753                    // is complete.
754                    w.mAppToken.deferClearAllDrawn = true;
755                }
756            }
757
758            mService.makeWindowFreezingScreenIfNeededLocked(w);
759
760            int flags = SurfaceControl.HIDDEN;
761            final WindowManager.LayoutParams attrs = w.mAttrs;
762
763            if ((attrs.flags&WindowManager.LayoutParams.FLAG_SECURE) != 0) {
764                flags |= SurfaceControl.SECURE;
765            }
766
767            if (mService.isScreenCaptureDisabledLocked(UserHandle.getUserId(mWin.mOwnerUid))) {
768                flags |= SurfaceControl.SECURE;
769            }
770
771            int width;
772            int height;
773            if ((attrs.flags & LayoutParams.FLAG_SCALED) != 0) {
774                // for a scaled surface, we always want the requested
775                // size.
776                width = w.mRequestedWidth;
777                height = w.mRequestedHeight;
778            } else {
779                width = w.mCompatFrame.width();
780                height = w.mCompatFrame.height();
781            }
782
783            // Something is wrong and SurfaceFlinger will not like this,
784            // try to revert to sane values
785            if (width <= 0) {
786                width = 1;
787            }
788            if (height <= 0) {
789                height = 1;
790            }
791
792            float left = w.mFrame.left + w.mXOffset;
793            float top = w.mFrame.top + w.mYOffset;
794
795            // Adjust for surface insets.
796            width += attrs.surfaceInsets.left + attrs.surfaceInsets.right;
797            height += attrs.surfaceInsets.top + attrs.surfaceInsets.bottom;
798            left -= attrs.surfaceInsets.left;
799            top -= attrs.surfaceInsets.top;
800
801            if (DEBUG_VISIBILITY) {
802                Slog.v(TAG, "Creating surface in session "
803                        + mSession.mSurfaceSession + " window " + this
804                        + " w=" + width + " h=" + height
805                        + " x=" + left + " y=" + top
806                        + " format=" + attrs.format + " flags=" + flags);
807            }
808
809            // We may abort, so initialize to defaults.
810            mSurfaceShown = false;
811            mSurfaceLayer = 0;
812            mSurfaceAlpha = 0;
813            mSurfaceX = 0;
814            mSurfaceY = 0;
815            w.mLastSystemDecorRect.set(0, 0, 0, 0);
816            mLastClipRect.set(0, 0, 0, 0);
817
818            // Set up surface control with initial size.
819            try {
820                mSurfaceW = width;
821                mSurfaceH = height;
822
823                final boolean isHwAccelerated = (attrs.flags &
824                        WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED) != 0;
825                final int format = isHwAccelerated ? PixelFormat.TRANSLUCENT : attrs.format;
826                if (!PixelFormat.formatHasAlpha(attrs.format)
827                        && attrs.surfaceInsets.left == 0
828                        && attrs.surfaceInsets.top == 0
829                        && attrs.surfaceInsets.right == 0
830                        && attrs.surfaceInsets.bottom  == 0) {
831                    flags |= SurfaceControl.OPAQUE;
832                }
833
834                if (DEBUG_SURFACE_TRACE) {
835                    mSurfaceControl = new SurfaceTrace(
836                            mSession.mSurfaceSession,
837                            attrs.getTitle().toString(),
838                            width, height, format, flags);
839                } else {
840                    mSurfaceControl = new SurfaceControl(
841                        mSession.mSurfaceSession,
842                        attrs.getTitle().toString(),
843                        width, height, format, flags);
844                }
845
846                w.mHasSurface = true;
847
848                if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
849                    Slog.i(TAG, "  CREATE SURFACE "
850                            + mSurfaceControl + " IN SESSION "
851                            + mSession.mSurfaceSession
852                            + ": pid=" + mSession.mPid + " format="
853                            + attrs.format + " flags=0x"
854                            + Integer.toHexString(flags)
855                            + " / " + this);
856                }
857            } catch (OutOfResourcesException e) {
858                w.mHasSurface = false;
859                Slog.w(TAG, "OutOfResourcesException creating surface");
860                mService.reclaimSomeSurfaceMemoryLocked(this, "create", true);
861                mDrawState = NO_SURFACE;
862                return null;
863            } catch (Exception e) {
864                w.mHasSurface = false;
865                Slog.e(TAG, "Exception creating surface", e);
866                mDrawState = NO_SURFACE;
867                return null;
868            }
869
870            if (WindowManagerService.localLOGV) {
871                Slog.v(TAG, "Got surface: " + mSurfaceControl
872                        + ", set left=" + w.mFrame.left + " top=" + w.mFrame.top
873                        + ", animLayer=" + mAnimLayer);
874            }
875
876            if (SHOW_LIGHT_TRANSACTIONS) {
877                Slog.i(TAG, ">>> OPEN TRANSACTION createSurfaceLocked");
878                WindowManagerService.logSurface(w, "CREATE pos=("
879                        + w.mFrame.left + "," + w.mFrame.top + ") ("
880                        + w.mCompatFrame.width() + "x" + w.mCompatFrame.height()
881                        + "), layer=" + mAnimLayer + " HIDE", null);
882            }
883
884            // Start a new transaction and apply position & offset.
885            SurfaceControl.openTransaction();
886            try {
887                mSurfaceX = left;
888                mSurfaceY = top;
889
890                try {
891                    mSurfaceControl.setPosition(left, top);
892                    mSurfaceLayer = mAnimLayer;
893                    final DisplayContent displayContent = w.getDisplayContent();
894                    if (displayContent != null) {
895                        mSurfaceControl.setLayerStack(displayContent.getDisplay().getLayerStack());
896                    }
897                    mSurfaceControl.setLayer(mAnimLayer);
898                    mSurfaceControl.setAlpha(0);
899                    mSurfaceShown = false;
900                } catch (RuntimeException e) {
901                    Slog.w(TAG, "Error creating surface in " + w, e);
902                    mService.reclaimSomeSurfaceMemoryLocked(this, "create-init", true);
903                }
904                mLastHidden = true;
905            } finally {
906                SurfaceControl.closeTransaction();
907                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
908                        "<<< CLOSE TRANSACTION createSurfaceLocked");
909            }
910            if (WindowManagerService.localLOGV) Slog.v(
911                    TAG, "Created surface " + this);
912        }
913        return mSurfaceControl;
914    }
915
916    void destroySurfaceLocked() {
917        if (mWin.mAppToken != null && mWin == mWin.mAppToken.startingWindow) {
918            mWin.mAppToken.startingDisplayed = false;
919        }
920
921        if (mSurfaceControl != null) {
922
923            int i = mWin.mChildWindows.size();
924            while (i > 0) {
925                i--;
926                WindowState c = mWin.mChildWindows.get(i);
927                c.mAttachedHidden = true;
928            }
929
930            try {
931                if (DEBUG_VISIBILITY) {
932                    RuntimeException e = null;
933                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
934                        e = new RuntimeException();
935                        e.fillInStackTrace();
936                    }
937                    Slog.w(TAG, "Window " + this + " destroying surface "
938                            + mSurfaceControl + ", session " + mSession, e);
939                }
940                if (mSurfaceDestroyDeferred) {
941                    if (mSurfaceControl != null && mPendingDestroySurface != mSurfaceControl) {
942                        if (mPendingDestroySurface != null) {
943                            if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
944                                RuntimeException e = null;
945                                if (!WindowManagerService.HIDE_STACK_CRAWLS) {
946                                    e = new RuntimeException();
947                                    e.fillInStackTrace();
948                                }
949                                WindowManagerService.logSurface(mWin, "DESTROY PENDING", e);
950                            }
951                            mPendingDestroySurface.destroy();
952                        }
953                        mPendingDestroySurface = mSurfaceControl;
954                    }
955                } else {
956                    if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
957                        RuntimeException e = null;
958                        if (!WindowManagerService.HIDE_STACK_CRAWLS) {
959                            e = new RuntimeException();
960                            e.fillInStackTrace();
961                        }
962                        WindowManagerService.logSurface(mWin, "DESTROY", e);
963                    }
964                    mSurfaceControl.destroy();
965                }
966                mAnimator.hideWallpapersLocked(mWin);
967            } catch (RuntimeException e) {
968                Slog.w(TAG, "Exception thrown when destroying Window " + this
969                    + " surface " + mSurfaceControl + " session " + mSession
970                    + ": " + e.toString());
971            }
972
973            mSurfaceShown = false;
974            mSurfaceControl = null;
975            mWin.mHasSurface = false;
976            mDrawState = NO_SURFACE;
977        }
978    }
979
980    void destroyDeferredSurfaceLocked() {
981        try {
982            if (mPendingDestroySurface != null) {
983                if (SHOW_TRANSACTIONS || SHOW_SURFACE_ALLOC) {
984                    RuntimeException e = null;
985                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
986                        e = new RuntimeException();
987                        e.fillInStackTrace();
988                    }
989                    WindowManagerService.logSurface(mWin, "DESTROY PENDING", e);
990                }
991                mPendingDestroySurface.destroy();
992                mAnimator.hideWallpapersLocked(mWin);
993            }
994        } catch (RuntimeException e) {
995            Slog.w(TAG, "Exception thrown when destroying Window "
996                    + this + " surface " + mPendingDestroySurface
997                    + " session " + mSession + ": " + e.toString());
998        }
999        mSurfaceDestroyDeferred = false;
1000        mPendingDestroySurface = null;
1001    }
1002
1003    void computeShownFrameLocked() {
1004        final boolean selfTransformation = mHasLocalTransformation;
1005        Transformation attachedTransformation =
1006                (mAttachedWinAnimator != null && mAttachedWinAnimator.mHasLocalTransformation)
1007                ? mAttachedWinAnimator.mTransformation : null;
1008        Transformation appTransformation = (mAppAnimator != null && mAppAnimator.hasTransformation)
1009                ? mAppAnimator.transformation : null;
1010
1011        // Wallpapers are animated based on the "real" window they
1012        // are currently targeting.
1013        final WindowState wallpaperTarget = mService.mWallpaperTarget;
1014        if (mIsWallpaper && wallpaperTarget != null && mService.mAnimateWallpaperWithTarget) {
1015            final WindowStateAnimator wallpaperAnimator = wallpaperTarget.mWinAnimator;
1016            if (wallpaperAnimator.mHasLocalTransformation &&
1017                    wallpaperAnimator.mAnimation != null &&
1018                    !wallpaperAnimator.mAnimation.getDetachWallpaper()) {
1019                attachedTransformation = wallpaperAnimator.mTransformation;
1020                if (WindowManagerService.DEBUG_WALLPAPER && attachedTransformation != null) {
1021                    Slog.v(TAG, "WP target attached xform: " + attachedTransformation);
1022                }
1023            }
1024            final AppWindowAnimator wpAppAnimator = wallpaperTarget.mAppToken == null ?
1025                    null : wallpaperTarget.mAppToken.mAppAnimator;
1026                if (wpAppAnimator != null && wpAppAnimator.hasTransformation
1027                    && wpAppAnimator.animation != null
1028                    && !wpAppAnimator.animation.getDetachWallpaper()) {
1029                appTransformation = wpAppAnimator.transformation;
1030                if (WindowManagerService.DEBUG_WALLPAPER && appTransformation != null) {
1031                    Slog.v(TAG, "WP target app xform: " + appTransformation);
1032                }
1033            }
1034        }
1035
1036        final int displayId = mWin.getDisplayId();
1037        final ScreenRotationAnimation screenRotationAnimation =
1038                mAnimator.getScreenRotationAnimationLocked(displayId);
1039        final boolean screenAnimation =
1040                screenRotationAnimation != null && screenRotationAnimation.isAnimating();
1041        if (selfTransformation || attachedTransformation != null
1042                || appTransformation != null || screenAnimation) {
1043            // cache often used attributes locally
1044            final Rect frame = mWin.mFrame;
1045            final float tmpFloats[] = mService.mTmpFloats;
1046            final Matrix tmpMatrix = mWin.mTmpMatrix;
1047
1048            // Compute the desired transformation.
1049            if (screenAnimation && screenRotationAnimation.isRotating()) {
1050                // If we are doing a screen animation, the global rotation
1051                // applied to windows can result in windows that are carefully
1052                // aligned with each other to slightly separate, allowing you
1053                // to see what is behind them.  An unsightly mess.  This...
1054                // thing...  magically makes it call good: scale each window
1055                // slightly (two pixels larger in each dimension, from the
1056                // window's center).
1057                final float w = frame.width();
1058                final float h = frame.height();
1059                if (w>=1 && h>=1) {
1060                    tmpMatrix.setScale(1 + 2/w, 1 + 2/h, w/2, h/2);
1061                } else {
1062                    tmpMatrix.reset();
1063                }
1064            } else {
1065                tmpMatrix.reset();
1066            }
1067            tmpMatrix.postScale(mWin.mGlobalScale, mWin.mGlobalScale);
1068            if (selfTransformation) {
1069                tmpMatrix.postConcat(mTransformation.getMatrix());
1070            }
1071            tmpMatrix.postTranslate(frame.left + mWin.mXOffset, frame.top + mWin.mYOffset);
1072            if (attachedTransformation != null) {
1073                tmpMatrix.postConcat(attachedTransformation.getMatrix());
1074            }
1075            if (appTransformation != null) {
1076                tmpMatrix.postConcat(appTransformation.getMatrix());
1077            }
1078            if (mAnimator.mUniverseBackground != null) {
1079                tmpMatrix.postConcat(mAnimator.mUniverseBackground.mUniverseTransform.getMatrix());
1080            }
1081            if (screenAnimation) {
1082                tmpMatrix.postConcat(screenRotationAnimation.getEnterTransformation().getMatrix());
1083            }
1084
1085            //TODO (multidisplay): Magnification is supported only for the default display.
1086            if (mService.mAccessibilityController != null && displayId == Display.DEFAULT_DISPLAY) {
1087                MagnificationSpec spec = mService.mAccessibilityController
1088                        .getMagnificationSpecForWindowLocked(mWin);
1089                if (spec != null && !spec.isNop()) {
1090                    tmpMatrix.postScale(spec.scale, spec.scale);
1091                    tmpMatrix.postTranslate(spec.offsetX, spec.offsetY);
1092                }
1093            }
1094
1095            // "convert" it into SurfaceFlinger's format
1096            // (a 2x2 matrix + an offset)
1097            // Here we must not transform the position of the surface
1098            // since it is already included in the transformation.
1099            //Slog.i(TAG, "Transform: " + matrix);
1100
1101            mHaveMatrix = true;
1102            tmpMatrix.getValues(tmpFloats);
1103            mDsDx = tmpFloats[Matrix.MSCALE_X];
1104            mDtDx = tmpFloats[Matrix.MSKEW_Y];
1105            mDsDy = tmpFloats[Matrix.MSKEW_X];
1106            mDtDy = tmpFloats[Matrix.MSCALE_Y];
1107            float x = tmpFloats[Matrix.MTRANS_X];
1108            float y = tmpFloats[Matrix.MTRANS_Y];
1109            int w = frame.width();
1110            int h = frame.height();
1111            mWin.mShownFrame.set(x, y, x+w, y+h);
1112
1113            // Now set the alpha...  but because our current hardware
1114            // can't do alpha transformation on a non-opaque surface,
1115            // turn it off if we are running an animation that is also
1116            // transforming since it is more important to have that
1117            // animation be smooth.
1118            mShownAlpha = mAlpha;
1119            mHasClipRect = false;
1120            if (!mService.mLimitedAlphaCompositing
1121                    || (!PixelFormat.formatHasAlpha(mWin.mAttrs.format)
1122                    || (mWin.isIdentityMatrix(mDsDx, mDtDx, mDsDy, mDtDy)
1123                            && x == frame.left && y == frame.top))) {
1124                //Slog.i(TAG, "Applying alpha transform");
1125                if (selfTransformation) {
1126                    mShownAlpha *= mTransformation.getAlpha();
1127                }
1128                if (attachedTransformation != null) {
1129                    mShownAlpha *= attachedTransformation.getAlpha();
1130                }
1131                if (appTransformation != null) {
1132                    mShownAlpha *= appTransformation.getAlpha();
1133                    if (appTransformation.hasClipRect()) {
1134                        mClipRect.set(appTransformation.getClipRect());
1135                        if (mWin.mHScale > 0) {
1136                            mClipRect.left /= mWin.mHScale;
1137                            mClipRect.right /= mWin.mHScale;
1138                        }
1139                        if (mWin.mVScale > 0) {
1140                            mClipRect.top /= mWin.mVScale;
1141                            mClipRect.bottom /= mWin.mVScale;
1142                        }
1143                        mHasClipRect = true;
1144                    }
1145                }
1146                if (mAnimator.mUniverseBackground != null) {
1147                    mShownAlpha *= mAnimator.mUniverseBackground.mUniverseTransform.getAlpha();
1148                }
1149                if (screenAnimation) {
1150                    mShownAlpha *= screenRotationAnimation.getEnterTransformation().getAlpha();
1151                }
1152            } else {
1153                //Slog.i(TAG, "Not applying alpha transform");
1154            }
1155
1156            if ((DEBUG_SURFACE_TRACE || WindowManagerService.localLOGV)
1157                    && (mShownAlpha == 1.0 || mShownAlpha == 0.0)) Slog.v(
1158                    TAG, "computeShownFrameLocked: Animating " + this + " mAlpha=" + mAlpha
1159                    + " self=" + (selfTransformation ? mTransformation.getAlpha() : "null")
1160                    + " attached=" + (attachedTransformation == null ?
1161                            "null" : attachedTransformation.getAlpha())
1162                    + " app=" + (appTransformation == null ? "null" : appTransformation.getAlpha())
1163                    + " screen=" + (screenAnimation ?
1164                            screenRotationAnimation.getEnterTransformation().getAlpha() : "null"));
1165            return;
1166        } else if (mIsWallpaper && mService.mInnerFields.mWallpaperActionPending) {
1167            return;
1168        }
1169
1170        if (WindowManagerService.localLOGV) Slog.v(
1171                TAG, "computeShownFrameLocked: " + this +
1172                " not attached, mAlpha=" + mAlpha);
1173
1174        final boolean applyUniverseTransformation = (mAnimator.mUniverseBackground != null
1175                && mWin.mAttrs.type != WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND
1176                && mWin.mBaseLayer < mAnimator.mAboveUniverseLayer);
1177        MagnificationSpec spec = null;
1178        //TODO (multidisplay): Magnification is supported only for the default display.
1179        if (mService.mAccessibilityController != null && displayId == Display.DEFAULT_DISPLAY) {
1180            spec = mService.mAccessibilityController.getMagnificationSpecForWindowLocked(mWin);
1181        }
1182        if (applyUniverseTransformation || spec != null) {
1183            final Rect frame = mWin.mFrame;
1184            final float tmpFloats[] = mService.mTmpFloats;
1185            final Matrix tmpMatrix = mWin.mTmpMatrix;
1186
1187            tmpMatrix.setScale(mWin.mGlobalScale, mWin.mGlobalScale);
1188            tmpMatrix.postTranslate(frame.left + mWin.mXOffset, frame.top + mWin.mYOffset);
1189
1190            if (applyUniverseTransformation) {
1191                tmpMatrix.postConcat(mAnimator.mUniverseBackground.mUniverseTransform.getMatrix());
1192            }
1193
1194            if (spec != null && !spec.isNop()) {
1195                tmpMatrix.postScale(spec.scale, spec.scale);
1196                tmpMatrix.postTranslate(spec.offsetX, spec.offsetY);
1197            }
1198
1199            tmpMatrix.getValues(tmpFloats);
1200
1201            mHaveMatrix = true;
1202            mDsDx = tmpFloats[Matrix.MSCALE_X];
1203            mDtDx = tmpFloats[Matrix.MSKEW_Y];
1204            mDsDy = tmpFloats[Matrix.MSKEW_X];
1205            mDtDy = tmpFloats[Matrix.MSCALE_Y];
1206            float x = tmpFloats[Matrix.MTRANS_X];
1207            float y = tmpFloats[Matrix.MTRANS_Y];
1208            int w = frame.width();
1209            int h = frame.height();
1210            mWin.mShownFrame.set(x, y, x + w, y + h);
1211
1212            mShownAlpha = mAlpha;
1213            if (applyUniverseTransformation) {
1214                mShownAlpha *= mAnimator.mUniverseBackground.mUniverseTransform.getAlpha();
1215            }
1216        } else {
1217            mWin.mShownFrame.set(mWin.mFrame);
1218            if (mWin.mXOffset != 0 || mWin.mYOffset != 0) {
1219                mWin.mShownFrame.offset(mWin.mXOffset, mWin.mYOffset);
1220            }
1221            mShownAlpha = mAlpha;
1222            mHaveMatrix = false;
1223            mDsDx = mWin.mGlobalScale;
1224            mDtDx = 0;
1225            mDsDy = 0;
1226            mDtDy = mWin.mGlobalScale;
1227        }
1228    }
1229
1230    void applyDecorRect(final Rect decorRect) {
1231        final WindowState w = mWin;
1232        final int width = w.mFrame.width();
1233        final int height = w.mFrame.height();
1234
1235        // Compute the offset of the window in relation to the decor rect.
1236        final int left = w.mXOffset + w.mFrame.left;
1237        final int top = w.mYOffset + w.mFrame.top;
1238
1239        // Initialize the decor rect to the entire frame.
1240        w.mSystemDecorRect.set(0, 0, width, height);
1241
1242        // Intersect with the decor rect, offsetted by window position.
1243        w.mSystemDecorRect.intersect(decorRect.left - left, decorRect.top - top,
1244                decorRect.right - left, decorRect.bottom - top);
1245
1246        // If size compatibility is being applied to the window, the
1247        // surface is scaled relative to the screen.  Also apply this
1248        // scaling to the crop rect.  We aren't using the standard rect
1249        // scale function because we want to round things to make the crop
1250        // always round to a larger rect to ensure we don't crop too
1251        // much and hide part of the window that should be seen.
1252        if (w.mEnforceSizeCompat && w.mInvGlobalScale != 1.0f) {
1253            final float scale = w.mInvGlobalScale;
1254            w.mSystemDecorRect.left = (int) (w.mSystemDecorRect.left * scale - 0.5f);
1255            w.mSystemDecorRect.top = (int) (w.mSystemDecorRect.top * scale - 0.5f);
1256            w.mSystemDecorRect.right = (int) ((w.mSystemDecorRect.right+1) * scale - 0.5f);
1257            w.mSystemDecorRect.bottom = (int) ((w.mSystemDecorRect.bottom+1) * scale - 0.5f);
1258        }
1259    }
1260
1261    void updateSurfaceWindowCrop(final boolean recoveringMemory) {
1262        final WindowState w = mWin;
1263        final DisplayContent displayContent = w.getDisplayContent();
1264        if (displayContent == null) {
1265            return;
1266        }
1267
1268        // Need to recompute a new system decor rect each time.
1269        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
1270            // Currently can't do this cropping for scaled windows.  We'll
1271            // just keep the crop rect the same as the source surface.
1272            w.mSystemDecorRect.set(0, 0, w.mRequestedWidth, w.mRequestedHeight);
1273        } else if (!w.isDefaultDisplay()) {
1274            // On a different display there is no system decor.  Crop the window
1275            // by the screen boundaries.
1276            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
1277            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
1278            w.mSystemDecorRect.intersect(-w.mCompatFrame.left, -w.mCompatFrame.top,
1279                    displayInfo.logicalWidth - w.mCompatFrame.left,
1280                    displayInfo.logicalHeight - w.mCompatFrame.top);
1281        } else if (w.mLayer >= mService.mSystemDecorLayer) {
1282            // Above the decor layer is easy, just use the entire window.
1283            // Unless we have a universe background...  in which case all the
1284            // windows need to be cropped by the screen, so they don't cover
1285            // the universe background.
1286            if (mAnimator.mUniverseBackground == null) {
1287                w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
1288            } else {
1289                applyDecorRect(mService.mScreenRect);
1290            }
1291        } else if (w.mAttrs.type == WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND
1292                || w.mDecorFrame.isEmpty()) {
1293            // The universe background isn't cropped, nor windows without policy decor.
1294            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
1295        } else if (w.mAttrs.type == LayoutParams.TYPE_WALLPAPER && mAnimator.mAnimating) {
1296            // If we're animating, the wallpaper crop should only be updated at the end of the
1297            // animation.
1298            mTmpClipRect.set(w.mSystemDecorRect);
1299            applyDecorRect(w.mDecorFrame);
1300            w.mSystemDecorRect.union(mTmpClipRect);
1301        } else {
1302            // Crop to the system decor specified by policy.
1303            applyDecorRect(w.mDecorFrame);
1304        }
1305
1306        // By default, the clip rect is the system decor.
1307        final Rect clipRect = mTmpClipRect;
1308        clipRect.set(w.mSystemDecorRect);
1309
1310        // Expand the clip rect for surface insets.
1311        final WindowManager.LayoutParams attrs = w.mAttrs;
1312        clipRect.left -= attrs.surfaceInsets.left;
1313        clipRect.top -= attrs.surfaceInsets.top;
1314        clipRect.right += attrs.surfaceInsets.right;
1315        clipRect.bottom += attrs.surfaceInsets.bottom;
1316
1317        // If we have an animated clip rect, intersect it with the clip rect.
1318        if (mHasClipRect) {
1319            // NOTE: We are adding a temporary workaround due to the status bar
1320            // not always reporting the correct system decor rect. In such
1321            // cases, we take into account the specified content insets as well.
1322            if ((w.mSystemUiVisibility & SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN)
1323                    == SYSTEM_UI_FLAGS_LAYOUT_STABLE_FULLSCREEN
1324                    || (w.mAttrs.flags & FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) != 0) {
1325                // Don't apply the workaround to apps explicitly requesting
1326                // fullscreen layout or when the bars are transparent.
1327                clipRect.intersect(mClipRect);
1328            } else {
1329                final int offsetTop = Math.max(clipRect.top, w.mContentInsets.top);
1330                clipRect.offset(0, -offsetTop);
1331                clipRect.intersect(mClipRect);
1332                clipRect.offset(0, offsetTop);
1333            }
1334        }
1335
1336        // The clip rect was generated assuming (0,0) as the window origin,
1337        // so we need to translate to match the actual surface coordinates.
1338        clipRect.offset(attrs.surfaceInsets.left, attrs.surfaceInsets.top);
1339
1340        if (!clipRect.equals(mLastClipRect)) {
1341            mLastClipRect.set(clipRect);
1342            try {
1343                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1344                        "CROP " + clipRect.toShortString(), null);
1345                mSurfaceControl.setWindowCrop(clipRect);
1346            } catch (RuntimeException e) {
1347                Slog.w(TAG, "Error setting crop surface of " + w
1348                        + " crop=" + clipRect.toShortString(), e);
1349                if (!recoveringMemory) {
1350                    mService.reclaimSomeSurfaceMemoryLocked(this, "crop", true);
1351                }
1352            }
1353        }
1354    }
1355
1356    void setSurfaceBoundariesLocked(final boolean recoveringMemory) {
1357        final WindowState w = mWin;
1358
1359        int width;
1360        int height;
1361        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
1362            // for a scaled surface, we always want the requested
1363            // size.
1364            width  = w.mRequestedWidth;
1365            height = w.mRequestedHeight;
1366        } else {
1367            width = w.mCompatFrame.width();
1368            height = w.mCompatFrame.height();
1369        }
1370
1371        // Something is wrong and SurfaceFlinger will not like this,
1372        // try to revert to sane values
1373        if (width < 1) {
1374            width = 1;
1375        }
1376        if (height < 1) {
1377            height = 1;
1378        }
1379
1380        float left = w.mShownFrame.left;
1381        float top = w.mShownFrame.top;
1382
1383        // Adjust for surface insets.
1384        final LayoutParams attrs = w.getAttrs();
1385        width += attrs.surfaceInsets.left + attrs.surfaceInsets.right;
1386        height += attrs.surfaceInsets.top + attrs.surfaceInsets.bottom;
1387        left -= attrs.surfaceInsets.left;
1388        top -= attrs.surfaceInsets.top;
1389
1390        final boolean surfaceMoved = mSurfaceX != left || mSurfaceY != top;
1391        if (surfaceMoved) {
1392            mSurfaceX = left;
1393            mSurfaceY = top;
1394
1395            try {
1396                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1397                        "POS " + left + ", " + top, null);
1398                mSurfaceControl.setPosition(left, top);
1399            } catch (RuntimeException e) {
1400                Slog.w(TAG, "Error positioning surface of " + w
1401                        + " pos=(" + left + "," + top + ")", e);
1402                if (!recoveringMemory) {
1403                    mService.reclaimSomeSurfaceMemoryLocked(this, "position", true);
1404                }
1405            }
1406        }
1407
1408        final boolean surfaceResized = mSurfaceW != width || mSurfaceH != height;
1409        if (surfaceResized) {
1410            mSurfaceW = width;
1411            mSurfaceH = height;
1412            mSurfaceResized = true;
1413
1414            try {
1415                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1416                        "SIZE " + width + "x" + height, null);
1417                mSurfaceControl.setSize(width, height);
1418                mAnimator.setPendingLayoutChanges(w.getDisplayId(),
1419                        WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER);
1420                if ((w.mAttrs.flags & LayoutParams.FLAG_DIM_BEHIND) != 0) {
1421                    final TaskStack stack = w.getStack();
1422                    if (stack != null) {
1423                        stack.startDimmingIfNeeded(this);
1424                    }
1425                }
1426            } catch (RuntimeException e) {
1427                // If something goes wrong with the surface (such
1428                // as running out of memory), don't take down the
1429                // entire system.
1430                Slog.e(TAG, "Error resizing surface of " + w
1431                        + " size=(" + width + "x" + height + ")", e);
1432                if (!recoveringMemory) {
1433                    mService.reclaimSomeSurfaceMemoryLocked(this, "size", true);
1434                }
1435            }
1436        }
1437
1438        updateSurfaceWindowCrop(recoveringMemory);
1439    }
1440
1441    public void prepareSurfaceLocked(final boolean recoveringMemory) {
1442        final WindowState w = mWin;
1443        if (mSurfaceControl == null) {
1444            if (w.mOrientationChanging) {
1445                if (DEBUG_ORIENTATION) {
1446                    Slog.v(TAG, "Orientation change skips hidden " + w);
1447                }
1448                w.mOrientationChanging = false;
1449            }
1450            return;
1451        }
1452
1453        boolean displayed = false;
1454
1455        computeShownFrameLocked();
1456
1457        setSurfaceBoundariesLocked(recoveringMemory);
1458
1459        if (mIsWallpaper && !mWin.mWallpaperVisible) {
1460            // Wallpaper is no longer visible and there is no wp target => hide it.
1461            hide();
1462        } else if (w.mAttachedHidden || !w.isOnScreen()) {
1463            hide();
1464            mAnimator.hideWallpapersLocked(w);
1465
1466            // If we are waiting for this window to handle an
1467            // orientation change, well, it is hidden, so
1468            // doesn't really matter.  Note that this does
1469            // introduce a potential glitch if the window
1470            // becomes unhidden before it has drawn for the
1471            // new orientation.
1472            if (w.mOrientationChanging) {
1473                w.mOrientationChanging = false;
1474                if (DEBUG_ORIENTATION) Slog.v(TAG,
1475                        "Orientation change skips hidden " + w);
1476            }
1477        } else if (mLastLayer != mAnimLayer
1478                || mLastAlpha != mShownAlpha
1479                || mLastDsDx != mDsDx
1480                || mLastDtDx != mDtDx
1481                || mLastDsDy != mDsDy
1482                || mLastDtDy != mDtDy
1483                || w.mLastHScale != w.mHScale
1484                || w.mLastVScale != w.mVScale
1485                || mLastHidden) {
1486            displayed = true;
1487            mLastAlpha = mShownAlpha;
1488            mLastLayer = mAnimLayer;
1489            mLastDsDx = mDsDx;
1490            mLastDtDx = mDtDx;
1491            mLastDsDy = mDsDy;
1492            mLastDtDy = mDtDy;
1493            w.mLastHScale = w.mHScale;
1494            w.mLastVScale = w.mVScale;
1495            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1496                    "alpha=" + mShownAlpha + " layer=" + mAnimLayer
1497                    + " matrix=[" + mDsDx + "*" + w.mHScale
1498                    + "," + mDtDx + "*" + w.mVScale
1499                    + "][" + mDsDy + "*" + w.mHScale
1500                    + "," + mDtDy + "*" + w.mVScale + "]", null);
1501            if (mSurfaceControl != null) {
1502                try {
1503                    mSurfaceAlpha = mShownAlpha;
1504                    mSurfaceControl.setAlpha(mShownAlpha);
1505                    mSurfaceLayer = mAnimLayer;
1506                    mSurfaceControl.setLayer(mAnimLayer);
1507                    mSurfaceControl.setMatrix(
1508                            mDsDx * w.mHScale, mDtDx * w.mVScale,
1509                            mDsDy * w.mHScale, mDtDy * w.mVScale);
1510
1511                    if (mLastHidden && mDrawState == HAS_DRAWN) {
1512                        if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1513                                "SHOW (performLayout)", null);
1514                        if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + w
1515                                + " during relayout");
1516                        if (showSurfaceRobustlyLocked()) {
1517                            mLastHidden = false;
1518                            if (mIsWallpaper) {
1519                                mService.dispatchWallpaperVisibility(w, true);
1520                            }
1521                            // This draw means the difference between unique content and mirroring.
1522                            // Run another pass through performLayout to set mHasContent in the
1523                            // LogicalDisplay.
1524                            mAnimator.setPendingLayoutChanges(w.getDisplayId(),
1525                                    WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM);
1526                        } else {
1527                            w.mOrientationChanging = false;
1528                        }
1529                    }
1530                    if (mSurfaceControl != null) {
1531                        w.mToken.hasVisible = true;
1532                    }
1533                } catch (RuntimeException e) {
1534                    Slog.w(TAG, "Error updating surface in " + w, e);
1535                    if (!recoveringMemory) {
1536                        mService.reclaimSomeSurfaceMemoryLocked(this, "update", true);
1537                    }
1538                }
1539            }
1540        } else {
1541            if (DEBUG_ANIM && isAnimating()) {
1542                Slog.v(TAG, "prepareSurface: No changes in animation for " + this);
1543            }
1544            displayed = true;
1545        }
1546
1547        if (displayed) {
1548            if (w.mOrientationChanging) {
1549                if (!w.isDrawnLw()) {
1550                    mAnimator.mBulkUpdateParams &= ~SET_ORIENTATION_CHANGE_COMPLETE;
1551                    mAnimator.mLastWindowFreezeSource = w;
1552                    if (DEBUG_ORIENTATION) Slog.v(TAG,
1553                            "Orientation continue waiting for draw in " + w);
1554                } else {
1555                    w.mOrientationChanging = false;
1556                    if (DEBUG_ORIENTATION) Slog.v(TAG, "Orientation change complete in " + w);
1557                }
1558            }
1559            w.mToken.hasVisible = true;
1560        }
1561    }
1562
1563    void setTransparentRegionHintLocked(final Region region) {
1564        if (mSurfaceControl == null) {
1565            Slog.w(TAG, "setTransparentRegionHint: null mSurface after mHasSurface true");
1566            return;
1567        }
1568        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setTransparentRegion");
1569        SurfaceControl.openTransaction();
1570        try {
1571            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1572                    "transparentRegionHint=" + region, null);
1573            mSurfaceControl.setTransparentRegionHint(region);
1574        } finally {
1575            SurfaceControl.closeTransaction();
1576            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1577                    "<<< CLOSE TRANSACTION setTransparentRegion");
1578        }
1579    }
1580
1581    void setWallpaperOffset(RectF shownFrame) {
1582        final LayoutParams attrs = mWin.getAttrs();
1583        final int left = ((int) shownFrame.left) - attrs.surfaceInsets.left;
1584        final int top = ((int) shownFrame.top) - attrs.surfaceInsets.top;
1585        if (mSurfaceX != left || mSurfaceY != top) {
1586            mSurfaceX = left;
1587            mSurfaceY = top;
1588            if (mAnimating) {
1589                // If this window (or its app token) is animating, then the position
1590                // of the surface will be re-computed on the next animation frame.
1591                // We can't poke it directly here because it depends on whatever
1592                // transformation is being applied by the animation.
1593                return;
1594            }
1595            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setWallpaperOffset");
1596            SurfaceControl.openTransaction();
1597            try {
1598                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1599                        "POS " + left + ", " + top, null);
1600                mSurfaceControl.setPosition(mWin.mFrame.left + left, mWin.mFrame.top + top);
1601                updateSurfaceWindowCrop(false);
1602            } catch (RuntimeException e) {
1603                Slog.w(TAG, "Error positioning surface of " + mWin
1604                        + " pos=(" + left + "," + top + ")", e);
1605            } finally {
1606                SurfaceControl.closeTransaction();
1607                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1608                        "<<< CLOSE TRANSACTION setWallpaperOffset");
1609            }
1610        }
1611    }
1612
1613    void setOpaqueLocked(boolean isOpaque) {
1614        if (mSurfaceControl == null) {
1615            return;
1616        }
1617        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setOpaqueLocked");
1618        SurfaceControl.openTransaction();
1619        try {
1620            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin, "isOpaque=" + isOpaque,
1621                    null);
1622            mSurfaceControl.setOpaque(isOpaque);
1623        } finally {
1624            SurfaceControl.closeTransaction();
1625            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, "<<< CLOSE TRANSACTION setOpaqueLocked");
1626        }
1627    }
1628
1629    // This must be called while inside a transaction.
1630    boolean performShowLocked() {
1631        if (mWin.isHiddenFromUserLocked()) {
1632            return false;
1633        }
1634        if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1635                mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1636            RuntimeException e = null;
1637            if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1638                e = new RuntimeException();
1639                e.fillInStackTrace();
1640            }
1641            Slog.v(TAG, "performShow on " + this
1642                    + ": mDrawState=" + mDrawState + " readyForDisplay="
1643                    + mWin.isReadyForDisplayIgnoringKeyguard()
1644                    + " starting=" + (mWin.mAttrs.type == TYPE_APPLICATION_STARTING)
1645                    + " during animation: policyVis=" + mWin.mPolicyVisibility
1646                    + " attHidden=" + mWin.mAttachedHidden
1647                    + " tok.hiddenRequested="
1648                    + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1649                    + " tok.hidden="
1650                    + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1651                    + " animating=" + mAnimating
1652                    + " tok animating="
1653                    + (mAppAnimator != null ? mAppAnimator.animating : false), e);
1654        }
1655        if (mDrawState == READY_TO_SHOW && mWin.isReadyForDisplayIgnoringKeyguard()) {
1656            if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION)
1657                WindowManagerService.logSurface(mWin, "SHOW (performShowLocked)", null);
1658            if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1659                    mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1660                Slog.v(TAG, "Showing " + this
1661                        + " during animation: policyVis=" + mWin.mPolicyVisibility
1662                        + " attHidden=" + mWin.mAttachedHidden
1663                        + " tok.hiddenRequested="
1664                        + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1665                        + " tok.hidden="
1666                        + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1667                        + " animating=" + mAnimating
1668                        + " tok animating="
1669                        + (mAppAnimator != null ? mAppAnimator.animating : false));
1670            }
1671
1672            mService.enableScreenIfNeededLocked();
1673
1674            applyEnterAnimationLocked();
1675
1676            // Force the show in the next prepareSurfaceLocked() call.
1677            mLastAlpha = -1;
1678            if (DEBUG_SURFACE_TRACE || DEBUG_ANIM)
1679                Slog.v(TAG, "performShowLocked: mDrawState=HAS_DRAWN in " + this);
1680            mDrawState = HAS_DRAWN;
1681            mService.scheduleAnimationLocked();
1682
1683            int i = mWin.mChildWindows.size();
1684            while (i > 0) {
1685                i--;
1686                WindowState c = mWin.mChildWindows.get(i);
1687                if (c.mAttachedHidden) {
1688                    c.mAttachedHidden = false;
1689                    if (c.mWinAnimator.mSurfaceControl != null) {
1690                        c.mWinAnimator.performShowLocked();
1691                        // It hadn't been shown, which means layout not
1692                        // performed on it, so now we want to make sure to
1693                        // do a layout.  If called from within the transaction
1694                        // loop, this will cause it to restart with a new
1695                        // layout.
1696                        final DisplayContent displayContent = c.getDisplayContent();
1697                        if (displayContent != null) {
1698                            displayContent.layoutNeeded = true;
1699                        }
1700                    }
1701                }
1702            }
1703
1704            if (mWin.mAttrs.type != TYPE_APPLICATION_STARTING
1705                    && mWin.mAppToken != null) {
1706                mWin.mAppToken.firstWindowDrawn = true;
1707
1708                if (mWin.mAppToken.startingData != null) {
1709                    if (WindowManagerService.DEBUG_STARTING_WINDOW ||
1710                            WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1711                            "Finish starting " + mWin.mToken
1712                            + ": first real window is shown, no animation");
1713                    // If this initial window is animating, stop it -- we
1714                    // will do an animation to reveal it from behind the
1715                    // starting window, so there is no need for it to also
1716                    // be doing its own stuff.
1717                    clearAnimation();
1718                    mService.mFinishedStarting.add(mWin.mAppToken);
1719                    mService.mH.sendEmptyMessage(H.FINISHED_STARTING);
1720                }
1721                mWin.mAppToken.updateReportedVisibilityLocked();
1722            }
1723
1724            return true;
1725        }
1726
1727        return false;
1728    }
1729
1730    /**
1731     * Have the surface flinger show a surface, robustly dealing with
1732     * error conditions.  In particular, if there is not enough memory
1733     * to show the surface, then we will try to get rid of other surfaces
1734     * in order to succeed.
1735     *
1736     * @return Returns true if the surface was successfully shown.
1737     */
1738    boolean showSurfaceRobustlyLocked() {
1739        try {
1740            if (mSurfaceControl != null) {
1741                mSurfaceShown = true;
1742                mSurfaceControl.show();
1743                if (mWin.mTurnOnScreen) {
1744                    if (DEBUG_VISIBILITY) Slog.v(TAG,
1745                            "Show surface turning screen on: " + mWin);
1746                    mWin.mTurnOnScreen = false;
1747                    mAnimator.mBulkUpdateParams |= SET_TURN_ON_SCREEN;
1748                }
1749            }
1750            return true;
1751        } catch (RuntimeException e) {
1752            Slog.w(TAG, "Failure showing surface " + mSurfaceControl + " in " + mWin, e);
1753        }
1754
1755        mService.reclaimSomeSurfaceMemoryLocked(this, "show", true);
1756
1757        return false;
1758    }
1759
1760    void applyEnterAnimationLocked() {
1761        final int transit;
1762        if (mEnterAnimationPending) {
1763            mEnterAnimationPending = false;
1764            transit = WindowManagerPolicy.TRANSIT_ENTER;
1765        } else {
1766            transit = WindowManagerPolicy.TRANSIT_SHOW;
1767        }
1768        applyAnimationLocked(transit, true);
1769        //TODO (multidisplay): Magnification is supported only for the default display.
1770        if (mService.mAccessibilityController != null
1771                && mWin.getDisplayId() == Display.DEFAULT_DISPLAY) {
1772            mService.mAccessibilityController.onWindowTransitionLocked(mWin, transit);
1773        }
1774    }
1775
1776    /**
1777     * Choose the correct animation and set it to the passed WindowState.
1778     * @param transit If AppTransition.TRANSIT_PREVIEW_DONE and the app window has been drawn
1779     *      then the animation will be app_starting_exit. Any other value loads the animation from
1780     *      the switch statement below.
1781     * @param isEntrance The animation type the last time this was called. Used to keep from
1782     *      loading the same animation twice.
1783     * @return true if an animation has been loaded.
1784     */
1785    boolean applyAnimationLocked(int transit, boolean isEntrance) {
1786        if (mLocalAnimating && mAnimationIsEntrance == isEntrance) {
1787            // If we are trying to apply an animation, but already running
1788            // an animation of the same type, then just leave that one alone.
1789            return true;
1790        }
1791
1792        // Only apply an animation if the display isn't frozen.  If it is
1793        // frozen, there is no reason to animate and it can cause strange
1794        // artifacts when we unfreeze the display if some different animation
1795        // is running.
1796        if (mService.okToDisplay()) {
1797            int anim = mPolicy.selectAnimationLw(mWin, transit);
1798            int attr = -1;
1799            Animation a = null;
1800            if (anim != 0) {
1801                a = anim != -1 ? AnimationUtils.loadAnimation(mContext, anim) : null;
1802            } else {
1803                switch (transit) {
1804                    case WindowManagerPolicy.TRANSIT_ENTER:
1805                        attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1806                        break;
1807                    case WindowManagerPolicy.TRANSIT_EXIT:
1808                        attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1809                        break;
1810                    case WindowManagerPolicy.TRANSIT_SHOW:
1811                        attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1812                        break;
1813                    case WindowManagerPolicy.TRANSIT_HIDE:
1814                        attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1815                        break;
1816                }
1817                if (attr >= 0) {
1818                    a = mService.mAppTransition.loadAnimationAttr(mWin.mAttrs, attr);
1819                }
1820            }
1821            if (WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1822                    "applyAnimation: win=" + this
1823                    + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1824                    + " a=" + a
1825                    + " transit=" + transit
1826                    + " isEntrance=" + isEntrance + " Callers " + Debug.getCallers(3));
1827            if (a != null) {
1828                if (WindowManagerService.DEBUG_ANIM) {
1829                    RuntimeException e = null;
1830                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1831                        e = new RuntimeException();
1832                        e.fillInStackTrace();
1833                    }
1834                    Slog.v(TAG, "Loaded animation " + a + " for " + this, e);
1835                }
1836                setAnimation(a);
1837                mAnimationIsEntrance = isEntrance;
1838            }
1839        } else {
1840            clearAnimation();
1841        }
1842
1843        return mAnimation != null;
1844    }
1845
1846    public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1847        if (mAnimating || mLocalAnimating || mAnimationIsEntrance
1848                || mAnimation != null) {
1849            pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
1850                    pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
1851                    pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
1852                    pw.print(" mAnimation="); pw.println(mAnimation);
1853        }
1854        if (mHasTransformation || mHasLocalTransformation) {
1855            pw.print(prefix); pw.print("XForm: has=");
1856                    pw.print(mHasTransformation);
1857                    pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
1858                    pw.print(" "); mTransformation.printShortString(pw);
1859                    pw.println();
1860        }
1861        if (mSurfaceControl != null) {
1862            if (dumpAll) {
1863                pw.print(prefix); pw.print("mSurface="); pw.println(mSurfaceControl);
1864                pw.print(prefix); pw.print("mDrawState=");
1865                pw.print(drawStateToString());
1866                pw.print(" mLastHidden="); pw.println(mLastHidden);
1867            }
1868            pw.print(prefix); pw.print("Surface: shown="); pw.print(mSurfaceShown);
1869                    pw.print(" layer="); pw.print(mSurfaceLayer);
1870                    pw.print(" alpha="); pw.print(mSurfaceAlpha);
1871                    pw.print(" rect=("); pw.print(mSurfaceX);
1872                    pw.print(","); pw.print(mSurfaceY);
1873                    pw.print(") "); pw.print(mSurfaceW);
1874                    pw.print(" x "); pw.println(mSurfaceH);
1875        }
1876        if (mPendingDestroySurface != null) {
1877            pw.print(prefix); pw.print("mPendingDestroySurface=");
1878                    pw.println(mPendingDestroySurface);
1879        }
1880        if (mSurfaceResized || mSurfaceDestroyDeferred) {
1881            pw.print(prefix); pw.print("mSurfaceResized="); pw.print(mSurfaceResized);
1882                    pw.print(" mSurfaceDestroyDeferred="); pw.println(mSurfaceDestroyDeferred);
1883        }
1884        if (mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND) {
1885            pw.print(prefix); pw.print("mUniverseTransform=");
1886                    mUniverseTransform.printShortString(pw);
1887                    pw.println();
1888        }
1889        if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
1890            pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
1891                    pw.print(" mAlpha="); pw.print(mAlpha);
1892                    pw.print(" mLastAlpha="); pw.println(mLastAlpha);
1893        }
1894        if (mHaveMatrix || mWin.mGlobalScale != 1) {
1895            pw.print(prefix); pw.print("mGlobalScale="); pw.print(mWin.mGlobalScale);
1896                    pw.print(" mDsDx="); pw.print(mDsDx);
1897                    pw.print(" mDtDx="); pw.print(mDtDx);
1898                    pw.print(" mDsDy="); pw.print(mDsDy);
1899                    pw.print(" mDtDy="); pw.println(mDtDy);
1900        }
1901    }
1902
1903    @Override
1904    public String toString() {
1905        StringBuffer sb = new StringBuffer("WindowStateAnimator{");
1906        sb.append(Integer.toHexString(System.identityHashCode(this)));
1907        sb.append(' ');
1908        sb.append(mWin.mAttrs.getTitle());
1909        sb.append('}');
1910        return sb.toString();
1911    }
1912}
1913