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