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