WindowStateAnimator.java revision 9e809448761878b72b47c0a0e703de95a3cf9815
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 (false && 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 ((DEBUG_SURFACE_TRACE || WindowManagerService.localLOGV) && (mShownAlpha == 1.0 || mShownAlpha == 0.0)) Slog.v(
900                TAG, "computeShownFrameLocked: Animating " + this +
901                " mAlpha=" + mAlpha +
902                " self=" + (selfTransformation ? mTransformation.getAlpha() : "null") +
903                " attached=" + (attachedTransformation == null ? "null" : attachedTransformation.getAlpha()) +
904                " app=" + (appTransformation == null ? "null" : appTransformation.getAlpha()) +
905                " screen=" + (screenAnimation ? mService.mAnimator.mScreenRotationAnimation.getEnterTransformation().getAlpha()
906                        : "null"));
907            return;
908        } else if (mWin.mIsWallpaper &&
909                    (mAnimator.mPendingActions & WindowAnimator.WALLPAPER_ACTION_PENDING) != 0) {
910            return;
911        }
912
913        if (WindowManagerService.localLOGV) Slog.v(
914                TAG, "computeShownFrameLocked: " + this +
915                " not attached, mAlpha=" + mAlpha);
916        mWin.mShownFrame.set(mWin.mFrame);
917        if (mWin.mXOffset != 0 || mWin.mYOffset != 0) {
918            mWin.mShownFrame.offset(mWin.mXOffset, mWin.mYOffset);
919        }
920        mShownAlpha = mAlpha;
921        mHaveMatrix = false;
922        mDsDx = mWin.mGlobalScale;
923        mDtDx = 0;
924        mDsDy = 0;
925        mDtDy = mWin.mGlobalScale;
926    }
927
928    void updateSurfaceWindowCrop(final boolean recoveringMemory) {
929        final WindowState w = mWin;
930
931        // Need to recompute a new system decor rect each time.
932        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
933            // Currently can't do this cropping for scaled windows.  We'll
934            // just keep the crop rect the same as the source surface.
935            w.mSystemDecorRect.set(0, 0, w.mRequestedWidth, w.mRequestedHeight);
936        } else if (w.mLayer >= mService.mSystemDecorLayer) {
937            // Above the decor layer is easy, just use the entire window.
938            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(),
939                    w.mCompatFrame.height());
940        } else {
941            final Rect decorRect = mService.mSystemDecorRect;
942            // Compute the offset of the window in relation to the decor rect.
943            final int offX = w.mXOffset + w.mFrame.left;
944            final int offY = w.mYOffset + w.mFrame.top;
945            // Initialize the decor rect to the entire frame.
946            w.mSystemDecorRect.set(0, 0, w.mFrame.width(), w.mFrame.height());
947            // Intersect with the decor rect, offsetted by window position.
948            w.mSystemDecorRect.intersect(decorRect.left-offX, decorRect.top-offY,
949                    decorRect.right-offX, decorRect.bottom-offY);
950            // If size compatibility is being applied to the window, the
951            // surface is scaled relative to the screen.  Also apply this
952            // scaling to the crop rect.  We aren't using the standard rect
953            // scale function because we want to round things to make the crop
954            // always round to a larger rect to ensure we don't crop too
955            // much and hide part of the window that should be seen.
956            if (w.mEnforceSizeCompat && w.mInvGlobalScale != 1.0f) {
957                final float scale = w.mInvGlobalScale;
958                w.mSystemDecorRect.left = (int) (w.mSystemDecorRect.left * scale - 0.5f);
959                w.mSystemDecorRect.top = (int) (w.mSystemDecorRect.top * scale - 0.5f);
960                w.mSystemDecorRect.right = (int) ((w.mSystemDecorRect.right+1) * scale - 0.5f);
961                w.mSystemDecorRect.bottom = (int) ((w.mSystemDecorRect.bottom+1) * scale - 0.5f);
962            }
963        }
964
965        if (!w.mSystemDecorRect.equals(w.mLastSystemDecorRect)) {
966            w.mLastSystemDecorRect.set(w.mSystemDecorRect);
967            try {
968                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
969                        "CROP " + w.mSystemDecorRect.toShortString(), null);
970                mSurface.setWindowCrop(w.mSystemDecorRect);
971            } catch (RuntimeException e) {
972                Slog.w(TAG, "Error setting crop surface of " + w
973                        + " crop=" + w.mSystemDecorRect.toShortString(), e);
974                if (!recoveringMemory) {
975                    mService.reclaimSomeSurfaceMemoryLocked(this, "crop", true);
976                }
977            }
978        }
979    }
980
981    void setSurfaceBoundaries(final boolean recoveringMemory) {
982        final WindowState w = mWin;
983        int width, height;
984        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
985            // for a scaled surface, we just want to use
986            // the requested size.
987            width  = w.mRequestedWidth;
988            height = w.mRequestedHeight;
989        } else {
990            width = w.mCompatFrame.width();
991            height = w.mCompatFrame.height();
992        }
993
994        if (width < 1) {
995            width = 1;
996        }
997        if (height < 1) {
998            height = 1;
999        }
1000        final boolean surfaceResized = mSurfaceW != width || mSurfaceH != height;
1001        if (surfaceResized) {
1002            mSurfaceW = width;
1003            mSurfaceH = height;
1004        }
1005
1006        final float left = w.mShownFrame.left;
1007        final float top = w.mShownFrame.top;
1008        if (mSurfaceX != left || mSurfaceY != top) {
1009            try {
1010                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1011                        "POS " + left + ", " + top, null);
1012                mSurfaceX = left;
1013                mSurfaceY = top;
1014                mSurface.setPosition(left, top);
1015            } catch (RuntimeException e) {
1016                Slog.w(TAG, "Error positioning surface of " + w
1017                        + " pos=(" + left
1018                        + "," + top + ")", e);
1019                if (!recoveringMemory) {
1020                    mService.reclaimSomeSurfaceMemoryLocked(this, "position", true);
1021                }
1022            }
1023        }
1024
1025        if (surfaceResized) {
1026            try {
1027                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1028                        "SIZE " + width + "x" + height, null);
1029                mSurfaceResized = true;
1030                mSurface.setSize(width, height);
1031                mAnimator.mPendingLayoutChanges |=
1032                        WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
1033                if ((w.mAttrs.flags & LayoutParams.FLAG_DIM_BEHIND) != 0) {
1034                    mAnimator.startDimming(this, w.mExiting ? 0 : w.mAttrs.dimAmount,
1035                            mService.mAppDisplayWidth, mService.mAppDisplayHeight);
1036                }
1037            } catch (RuntimeException e) {
1038                // If something goes wrong with the surface (such
1039                // as running out of memory), don't take down the
1040                // entire system.
1041                Slog.e(TAG, "Error resizing surface of " + w
1042                        + " size=(" + width + "x" + height + ")", e);
1043                if (!recoveringMemory) {
1044                    mService.reclaimSomeSurfaceMemoryLocked(this, "size", true);
1045                }
1046            }
1047        }
1048
1049        updateSurfaceWindowCrop(recoveringMemory);
1050    }
1051
1052    public void prepareSurfaceLocked(final boolean recoveringMemory) {
1053        final WindowState w = mWin;
1054        if (mSurface == null) {
1055            if (w.mOrientationChanging) {
1056                if (DEBUG_ORIENTATION) {
1057                    Slog.v(TAG, "Orientation change skips hidden " + w);
1058                }
1059                w.mOrientationChanging = false;
1060            }
1061            return;
1062        }
1063
1064        boolean displayed = false;
1065
1066        computeShownFrameLocked();
1067
1068        setSurfaceBoundaries(recoveringMemory);
1069
1070        if (mWin.mIsWallpaper && !mWin.mWallpaperVisible) {
1071            // Wallpaper is no longer visible and there is no wp target => hide it.
1072            hide();
1073        } else if (w.mAttachedHidden || !w.isReadyForDisplay()) {
1074            hide();
1075            mAnimator.hideWallpapersLocked(w);
1076
1077            // If we are waiting for this window to handle an
1078            // orientation change, well, it is hidden, so
1079            // doesn't really matter.  Note that this does
1080            // introduce a potential glitch if the window
1081            // becomes unhidden before it has drawn for the
1082            // new orientation.
1083            if (w.mOrientationChanging) {
1084                w.mOrientationChanging = false;
1085                if (DEBUG_ORIENTATION) Slog.v(TAG,
1086                        "Orientation change skips hidden " + w);
1087            }
1088        } else if (mLastLayer != mAnimLayer
1089                || mLastAlpha != mShownAlpha
1090                || mLastDsDx != mDsDx
1091                || mLastDtDx != mDtDx
1092                || mLastDsDy != mDsDy
1093                || mLastDtDy != mDtDy
1094                || w.mLastHScale != w.mHScale
1095                || w.mLastVScale != w.mVScale
1096                || mLastHidden) {
1097            displayed = true;
1098            mLastAlpha = mShownAlpha;
1099            mLastLayer = mAnimLayer;
1100            mLastDsDx = mDsDx;
1101            mLastDtDx = mDtDx;
1102            mLastDsDy = mDsDy;
1103            mLastDtDy = mDtDy;
1104            w.mLastHScale = w.mHScale;
1105            w.mLastVScale = w.mVScale;
1106            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1107                    "alpha=" + mShownAlpha + " layer=" + mAnimLayer
1108                    + " matrix=[" + (mDsDx*w.mHScale)
1109                    + "," + (mDtDx*w.mVScale)
1110                    + "][" + (mDsDy*w.mHScale)
1111                    + "," + (mDtDy*w.mVScale) + "]", null);
1112            if (mSurface != null) {
1113                try {
1114                    mSurfaceAlpha = mShownAlpha;
1115                    mSurface.setAlpha(mShownAlpha);
1116                    mSurfaceLayer = mAnimLayer;
1117                    mSurface.setLayer(mAnimLayer);
1118                    mSurface.setMatrix(
1119                        mDsDx*w.mHScale, mDtDx*w.mVScale,
1120                        mDsDy*w.mHScale, mDtDy*w.mVScale);
1121
1122                    if (mLastHidden && mDrawState == HAS_DRAWN) {
1123                        if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1124                                "SHOW (performLayout)", null);
1125                        if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + w
1126                                + " during relayout");
1127                        if (showSurfaceRobustlyLocked()) {
1128                            mLastHidden = false;
1129                            if (w.mIsWallpaper) {
1130                                mService.dispatchWallpaperVisibility(w, true);
1131                            }
1132                        } else {
1133                            w.mOrientationChanging = false;
1134                        }
1135                    }
1136                    if (mSurface != null) {
1137                        w.mToken.hasVisible = true;
1138                    }
1139                } catch (RuntimeException e) {
1140                    Slog.w(TAG, "Error updating surface in " + w, e);
1141                    if (!recoveringMemory) {
1142                        mService.reclaimSomeSurfaceMemoryLocked(this, "update", true);
1143                    }
1144                }
1145            }
1146        } else {
1147            if (DEBUG_ANIM && isAnimating()) {
1148                Slog.v(TAG, "prepareSurface: No changes in animation for " + this);
1149            }
1150            displayed = true;
1151        }
1152
1153        if (displayed) {
1154            if (w.mOrientationChanging) {
1155                if (!w.isDrawnLw()) {
1156                    mAnimator.mBulkUpdateParams |= CLEAR_ORIENTATION_CHANGE_COMPLETE;
1157                    if (DEBUG_ORIENTATION) Slog.v(TAG,
1158                            "Orientation continue waiting for draw in " + w);
1159                } else {
1160                    w.mOrientationChanging = false;
1161                    if (DEBUG_ORIENTATION) Slog.v(TAG, "Orientation change complete in " + w);
1162                }
1163            }
1164            w.mToken.hasVisible = true;
1165        }
1166    }
1167
1168    void setTransparentRegionHint(final Region region) {
1169        if (mSurface == null) {
1170            Slog.w(TAG, "setTransparentRegionHint: null mSurface after mHasSurface true");
1171            return;
1172        }
1173        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1174            ">>> OPEN TRANSACTION setTransparentRegion");
1175        Surface.openTransaction();
1176        try {
1177            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1178                    "transparentRegionHint=" + region, null);
1179            mSurface.setTransparentRegionHint(region);
1180        } finally {
1181            Surface.closeTransaction();
1182            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1183                    "<<< CLOSE TRANSACTION setTransparentRegion");
1184        }
1185    }
1186
1187    void setWallpaperOffset(int left, int top) {
1188        mSurfaceX = left;
1189        mSurfaceY = top;
1190        if (mAnimating) {
1191            // If this window (or its app token) is animating, then the position
1192            // of the surface will be re-computed on the next animation frame.
1193            // We can't poke it directly here because it depends on whatever
1194            // transformation is being applied by the animation.
1195            return;
1196        }
1197        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1198                ">>> OPEN TRANSACTION setWallpaperOffset");
1199        Surface.openTransaction();
1200        try {
1201            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1202                    "POS " + left + ", " + top, null);
1203            mSurface.setPosition(mWin.mFrame.left + left, mWin.mFrame.top + top);
1204            updateSurfaceWindowCrop(false);
1205        } catch (RuntimeException e) {
1206            Slog.w(TAG, "Error positioning surface of " + mWin
1207                    + " pos=(" + left + "," + top + ")", e);
1208        } finally {
1209            Surface.closeTransaction();
1210            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1211                    "<<< CLOSE TRANSACTION setWallpaperOffset");
1212        }
1213    }
1214
1215    // This must be called while inside a transaction.
1216    boolean performShowLocked() {
1217        if (DEBUG_VISIBILITY) {
1218            RuntimeException e = null;
1219            if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1220                e = new RuntimeException();
1221                e.fillInStackTrace();
1222            }
1223            Slog.v(TAG, "performShow on " + this
1224                    + ": mDrawState=" + mDrawState + " readyForDisplay="
1225                    + mWin.isReadyForDisplayIgnoringKeyguard()
1226                    + " starting=" + (mWin.mAttrs.type == TYPE_APPLICATION_STARTING), e);
1227        }
1228        if (mDrawState == READY_TO_SHOW && mWin.isReadyForDisplayIgnoringKeyguard()) {
1229            if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION)
1230                WindowManagerService.logSurface(mWin, "SHOW (performShowLocked)", null);
1231            if (DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + this
1232                    + " during animation: policyVis=" + mWin.mPolicyVisibility
1233                    + " attHidden=" + mWin.mAttachedHidden
1234                    + " tok.hiddenRequested="
1235                    + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1236                    + " tok.hidden="
1237                    + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1238                    + " animating=" + mAnimating
1239                    + " tok animating="
1240                    + (mWin.mAppToken != null ? mWin.mAppToken.mAppAnimator.animating : false));
1241
1242            mService.enableScreenIfNeededLocked();
1243
1244            applyEnterAnimationLocked();
1245
1246            // Force the show in the next prepareSurfaceLocked() call.
1247            mLastAlpha = -1;
1248            if (DEBUG_SURFACE_TRACE || DEBUG_ANIM)
1249                Slog.v(TAG, "performShowLocked: mDrawState=HAS_DRAWN in " + this);
1250            mDrawState = HAS_DRAWN;
1251            mService.scheduleAnimationLocked();
1252
1253            int i = mWin.mChildWindows.size();
1254            while (i > 0) {
1255                i--;
1256                WindowState c = mWin.mChildWindows.get(i);
1257                if (c.mAttachedHidden) {
1258                    c.mAttachedHidden = false;
1259                    if (c.mWinAnimator.mSurface != null) {
1260                        c.mWinAnimator.performShowLocked();
1261                        // It hadn't been shown, which means layout not
1262                        // performed on it, so now we want to make sure to
1263                        // do a layout.  If called from within the transaction
1264                        // loop, this will cause it to restart with a new
1265                        // layout.
1266                        mService.mLayoutNeeded = true;
1267                    }
1268                }
1269            }
1270
1271            if (mWin.mAttrs.type != TYPE_APPLICATION_STARTING
1272                    && mWin.mAppToken != null) {
1273                mWin.mAppToken.firstWindowDrawn = true;
1274
1275                if (mWin.mAppToken.startingData != null) {
1276                    if (WindowManagerService.DEBUG_STARTING_WINDOW ||
1277                            WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1278                            "Finish starting " + mWin.mToken
1279                            + ": first real window is shown, no animation");
1280                    // If this initial window is animating, stop it -- we
1281                    // will do an animation to reveal it from behind the
1282                    // starting window, so there is no need for it to also
1283                    // be doing its own stuff.
1284                    clearAnimation();
1285                    mService.mFinishedStarting.add(mWin.mAppToken);
1286                    mService.mH.sendEmptyMessage(H.FINISHED_STARTING);
1287                }
1288                mWin.mAppToken.updateReportedVisibilityLocked();
1289            }
1290
1291            return true;
1292        }
1293
1294        return false;
1295    }
1296
1297    /**
1298     * Have the surface flinger show a surface, robustly dealing with
1299     * error conditions.  In particular, if there is not enough memory
1300     * to show the surface, then we will try to get rid of other surfaces
1301     * in order to succeed.
1302     *
1303     * @return Returns true if the surface was successfully shown.
1304     */
1305    boolean showSurfaceRobustlyLocked() {
1306        try {
1307            if (mSurface != null) {
1308                mSurfaceShown = true;
1309                mSurface.show();
1310                if (mWin.mTurnOnScreen) {
1311                    if (DEBUG_VISIBILITY) Slog.v(TAG,
1312                            "Show surface turning screen on: " + mWin);
1313                    mWin.mTurnOnScreen = false;
1314                    mAnimator.mBulkUpdateParams |= SET_TURN_ON_SCREEN;
1315                }
1316            }
1317            return true;
1318        } catch (RuntimeException e) {
1319            Slog.w(TAG, "Failure showing surface " + mSurface + " in " + mWin, e);
1320        }
1321
1322        mService.reclaimSomeSurfaceMemoryLocked(this, "show", true);
1323
1324        return false;
1325    }
1326
1327    void applyEnterAnimationLocked() {
1328        final int transit;
1329        if (mEnterAnimationPending) {
1330            mEnterAnimationPending = false;
1331            transit = WindowManagerPolicy.TRANSIT_ENTER;
1332        } else {
1333            transit = WindowManagerPolicy.TRANSIT_SHOW;
1334        }
1335
1336        applyAnimationLocked(transit, true);
1337    }
1338
1339    // TODO(cmautner): Move back to WindowState?
1340    /**
1341     * Choose the correct animation and set it to the passed WindowState.
1342     * @param transit If WindowManagerPolicy.TRANSIT_PREVIEW_DONE and the app window has been drawn
1343     *      then the animation will be app_starting_exit. Any other value loads the animation from
1344     *      the switch statement below.
1345     * @param isEntrance The animation type the last time this was called. Used to keep from
1346     *      loading the same animation twice.
1347     * @return true if an animation has been loaded.
1348     */
1349    boolean applyAnimationLocked(int transit, boolean isEntrance) {
1350        if (mLocalAnimating && mAnimationIsEntrance == isEntrance) {
1351            // If we are trying to apply an animation, but already running
1352            // an animation of the same type, then just leave that one alone.
1353            return true;
1354        }
1355
1356        // Only apply an animation if the display isn't frozen.  If it is
1357        // frozen, there is no reason to animate and it can cause strange
1358        // artifacts when we unfreeze the display if some different animation
1359        // is running.
1360        if (mService.okToDisplay()) {
1361            int anim = mPolicy.selectAnimationLw(mWin, transit);
1362            int attr = -1;
1363            Animation a = null;
1364            if (anim != 0) {
1365                a = AnimationUtils.loadAnimation(mContext, anim);
1366            } else {
1367                switch (transit) {
1368                    case WindowManagerPolicy.TRANSIT_ENTER:
1369                        attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1370                        break;
1371                    case WindowManagerPolicy.TRANSIT_EXIT:
1372                        attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1373                        break;
1374                    case WindowManagerPolicy.TRANSIT_SHOW:
1375                        attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1376                        break;
1377                    case WindowManagerPolicy.TRANSIT_HIDE:
1378                        attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1379                        break;
1380                }
1381                if (attr >= 0) {
1382                    a = mService.loadAnimation(mWin.mAttrs, attr);
1383                }
1384            }
1385            if (WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1386                    "applyAnimation: win=" + this
1387                    + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1388                    + " a=" + a
1389                    + " mAnimation=" + mAnimation
1390                    + " isEntrance=" + isEntrance + " Callers " + Debug.getCallers(3));
1391            if (a != null) {
1392                if (WindowManagerService.DEBUG_ANIM) {
1393                    RuntimeException e = null;
1394                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1395                        e = new RuntimeException();
1396                        e.fillInStackTrace();
1397                    }
1398                    Slog.v(TAG, "Loaded animation " + a + " for " + this, e);
1399                }
1400                setAnimation(a);
1401                mAnimationIsEntrance = isEntrance;
1402            }
1403        } else {
1404            clearAnimation();
1405        }
1406
1407        return mAnimation != null;
1408    }
1409
1410    public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1411        if (mAnimating || mLocalAnimating || mAnimationIsEntrance
1412                || mAnimation != null) {
1413            pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
1414                    pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
1415                    pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
1416                    pw.print(" mAnimation="); pw.println(mAnimation);
1417        }
1418        if (mHasTransformation || mHasLocalTransformation) {
1419            pw.print(prefix); pw.print("XForm: has=");
1420                    pw.print(mHasTransformation);
1421                    pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
1422                    pw.print(" "); mTransformation.printShortString(pw);
1423                    pw.println();
1424        }
1425        if (mSurface != null) {
1426            if (dumpAll) {
1427                pw.print(prefix); pw.print("mSurface="); pw.println(mSurface);
1428                pw.print(prefix); pw.print("mDrawState="); pw.print(mDrawState);
1429                pw.print(" mLastHidden="); pw.println(mLastHidden);
1430            }
1431            pw.print(prefix); pw.print("Surface: shown="); pw.print(mSurfaceShown);
1432                    pw.print(" layer="); pw.print(mSurfaceLayer);
1433                    pw.print(" alpha="); pw.print(mSurfaceAlpha);
1434                    pw.print(" rect=("); pw.print(mSurfaceX);
1435                    pw.print(","); pw.print(mSurfaceY);
1436                    pw.print(") "); pw.print(mSurfaceW);
1437                    pw.print(" x "); pw.println(mSurfaceH);
1438        }
1439        if (mPendingDestroySurface != null) {
1440            pw.print(prefix); pw.print("mPendingDestroySurface=");
1441                    pw.println(mPendingDestroySurface);
1442        }
1443        if (mSurfaceResized || mSurfaceDestroyDeferred) {
1444            pw.print(prefix); pw.print("mSurfaceResized="); pw.print(mSurfaceResized);
1445                    pw.print(" mSurfaceDestroyDeferred="); pw.println(mSurfaceDestroyDeferred);
1446        }
1447        if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
1448            pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
1449                    pw.print(" mAlpha="); pw.print(mAlpha);
1450                    pw.print(" mLastAlpha="); pw.println(mLastAlpha);
1451        }
1452        if (mHaveMatrix || mWin.mGlobalScale != 1) {
1453            pw.print(prefix); pw.print("mGlobalScale="); pw.print(mWin.mGlobalScale);
1454                    pw.print(" mDsDx="); pw.print(mDsDx);
1455                    pw.print(" mDtDx="); pw.print(mDtDx);
1456                    pw.print(" mDsDy="); pw.print(mDsDy);
1457                    pw.print(" mDtDy="); pw.println(mDtDy);
1458        }
1459    }
1460
1461    @Override
1462    public String toString() {
1463        StringBuffer sb = new StringBuffer("WindowStateAnimator (");
1464        sb.append(mWin.mLastTitle + "): ");
1465        sb.append("mSurface " + mSurface);
1466        sb.append(", mAnimation " + mAnimation);
1467        return sb.toString();
1468    }
1469}
1470