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