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