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