WindowStateAnimator.java revision 3671410b9e09e1c5ec05dfc58651a8efaa7790dd
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 is easy, just use the entire display.
1059            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(), w.mCompatFrame.height());
1060            w.mSystemDecorRect.intersect(-w.mFrame.left, -w.mFrame.top,
1061                    displayInfo.logicalWidth - w.mFrame.left,
1062                    displayInfo.logicalHeight - w.mFrame.top);
1063        } else if (w.mLayer >= mService.mSystemDecorLayer) {
1064            // Above the decor layer is easy, just use the entire window.
1065            // Unless we have a universe background...  in which case all the
1066            // windows need to be cropped by the screen, so they don't cover
1067            // the universe background.
1068            if (mAnimator.mUniverseBackground == null) {
1069                w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(),
1070                        w.mCompatFrame.height());
1071            } else {
1072                applyDecorRect(mService.mScreenRect);
1073            }
1074        } else if (w.mAttrs.type == WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND) {
1075            // The universe background isn't cropped.
1076            w.mSystemDecorRect.set(0, 0, w.mCompatFrame.width(),
1077                    w.mCompatFrame.height());
1078        } else {
1079            applyDecorRect(mService.mSystemDecorRect);
1080        }
1081
1082        if (!w.mSystemDecorRect.equals(w.mLastSystemDecorRect)) {
1083            w.mLastSystemDecorRect.set(w.mSystemDecorRect);
1084            try {
1085                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1086                        "CROP " + w.mSystemDecorRect.toShortString(), null);
1087                mSurface.setWindowCrop(w.mSystemDecorRect);
1088            } catch (RuntimeException e) {
1089                Slog.w(TAG, "Error setting crop surface of " + w
1090                        + " crop=" + w.mSystemDecorRect.toShortString(), e);
1091                if (!recoveringMemory) {
1092                    mService.reclaimSomeSurfaceMemoryLocked(this, "crop", true);
1093                }
1094            }
1095        }
1096    }
1097
1098    void setSurfaceBoundariesLocked(final boolean recoveringMemory) {
1099        final WindowState w = mWin;
1100        int width, height;
1101        if ((w.mAttrs.flags & LayoutParams.FLAG_SCALED) != 0) {
1102            // for a scaled surface, we just want to use
1103            // the requested size.
1104            width  = w.mRequestedWidth;
1105            height = w.mRequestedHeight;
1106        } else {
1107            width = w.mCompatFrame.width();
1108            height = w.mCompatFrame.height();
1109        }
1110
1111        if (width < 1) {
1112            width = 1;
1113        }
1114        if (height < 1) {
1115            height = 1;
1116        }
1117        final boolean surfaceResized = mSurfaceW != width || mSurfaceH != height;
1118        if (surfaceResized) {
1119            mSurfaceW = width;
1120            mSurfaceH = height;
1121        }
1122
1123        final float left = w.mShownFrame.left;
1124        final float top = w.mShownFrame.top;
1125        if (mSurfaceX != left || mSurfaceY != top) {
1126            try {
1127                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1128                        "POS " + left + ", " + top, null);
1129                mSurfaceX = left;
1130                mSurfaceY = top;
1131                mSurface.setPosition(left, top);
1132            } catch (RuntimeException e) {
1133                Slog.w(TAG, "Error positioning surface of " + w
1134                        + " pos=(" + left
1135                        + "," + top + ")", e);
1136                if (!recoveringMemory) {
1137                    mService.reclaimSomeSurfaceMemoryLocked(this, "position", true);
1138                }
1139            }
1140        }
1141
1142        if (surfaceResized) {
1143            try {
1144                if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1145                        "SIZE " + width + "x" + height, null);
1146                mSurfaceResized = true;
1147                mSurface.setSize(width, height);
1148                final int displayId = w.mDisplayContent.getDisplayId();
1149                mAnimator.setPendingLayoutChanges(displayId,
1150                        WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER);
1151                if ((w.mAttrs.flags & LayoutParams.FLAG_DIM_BEHIND) != 0) {
1152                    final DisplayInfo displayInfo = mWin.mDisplayContent.getDisplayInfo();
1153                    mService.startDimmingLocked(this, w.mExiting ? 0 : w.mAttrs.dimAmount,
1154                            displayInfo.appWidth, displayInfo.appHeight);
1155                }
1156            } catch (RuntimeException e) {
1157                // If something goes wrong with the surface (such
1158                // as running out of memory), don't take down the
1159                // entire system.
1160                Slog.e(TAG, "Error resizing surface of " + w
1161                        + " size=(" + width + "x" + height + ")", e);
1162                if (!recoveringMemory) {
1163                    mService.reclaimSomeSurfaceMemoryLocked(this, "size", true);
1164                }
1165            }
1166        }
1167
1168        updateSurfaceWindowCrop(recoveringMemory);
1169    }
1170
1171    public void prepareSurfaceLocked(final boolean recoveringMemory) {
1172        final WindowState w = mWin;
1173        if (mSurface == null) {
1174            if (w.mOrientationChanging) {
1175                if (DEBUG_ORIENTATION) {
1176                    Slog.v(TAG, "Orientation change skips hidden " + w);
1177                }
1178                w.mOrientationChanging = false;
1179            }
1180            return;
1181        }
1182
1183        boolean displayed = false;
1184
1185        computeShownFrameLocked();
1186
1187        setSurfaceBoundariesLocked(recoveringMemory);
1188
1189        if (mIsWallpaper && !mWin.mWallpaperVisible) {
1190            // Wallpaper is no longer visible and there is no wp target => hide it.
1191            hide();
1192        } else if (w.mAttachedHidden || !w.isReadyForDisplay()) {
1193            hide();
1194            mAnimator.hideWallpapersLocked(w);
1195
1196            // If we are waiting for this window to handle an
1197            // orientation change, well, it is hidden, so
1198            // doesn't really matter.  Note that this does
1199            // introduce a potential glitch if the window
1200            // becomes unhidden before it has drawn for the
1201            // new orientation.
1202            if (w.mOrientationChanging) {
1203                w.mOrientationChanging = false;
1204                if (DEBUG_ORIENTATION) Slog.v(TAG,
1205                        "Orientation change skips hidden " + w);
1206            }
1207        } else if (mLastLayer != mAnimLayer
1208                || mLastAlpha != mShownAlpha
1209                || mLastDsDx != mDsDx
1210                || mLastDtDx != mDtDx
1211                || mLastDsDy != mDsDy
1212                || mLastDtDy != mDtDy
1213                || w.mLastHScale != w.mHScale
1214                || w.mLastVScale != w.mVScale
1215                || mLastHidden) {
1216            displayed = true;
1217            mLastAlpha = mShownAlpha;
1218            mLastLayer = mAnimLayer;
1219            mLastDsDx = mDsDx;
1220            mLastDtDx = mDtDx;
1221            mLastDsDy = mDsDy;
1222            mLastDtDy = mDtDy;
1223            w.mLastHScale = w.mHScale;
1224            w.mLastVScale = w.mVScale;
1225            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1226                    "alpha=" + mShownAlpha + " layer=" + mAnimLayer
1227                    + " matrix=[" + (mDsDx*w.mHScale)
1228                    + "," + (mDtDx*w.mVScale)
1229                    + "][" + (mDsDy*w.mHScale)
1230                    + "," + (mDtDy*w.mVScale) + "]", null);
1231            if (mSurface != null) {
1232                try {
1233                    mSurfaceAlpha = mShownAlpha;
1234                    mSurface.setAlpha(mShownAlpha);
1235                    mSurfaceLayer = mAnimLayer;
1236                    mSurface.setLayer(mAnimLayer);
1237                    mSurface.setMatrix(
1238                        mDsDx*w.mHScale, mDtDx*w.mVScale,
1239                        mDsDy*w.mHScale, mDtDy*w.mVScale);
1240
1241                    if (mLastHidden && mDrawState == HAS_DRAWN) {
1242                        if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1243                                "SHOW (performLayout)", null);
1244                        if (WindowManagerService.DEBUG_VISIBILITY) Slog.v(TAG, "Showing " + w
1245                                + " during relayout");
1246                        if (showSurfaceRobustlyLocked()) {
1247                            mLastHidden = false;
1248                            if (mIsWallpaper) {
1249                                mService.dispatchWallpaperVisibility(w, true);
1250                            }
1251                        } else {
1252                            w.mOrientationChanging = false;
1253                        }
1254                    }
1255                    if (mSurface != null) {
1256                        w.mToken.hasVisible = true;
1257                    }
1258                } catch (RuntimeException e) {
1259                    Slog.w(TAG, "Error updating surface in " + w, e);
1260                    if (!recoveringMemory) {
1261                        mService.reclaimSomeSurfaceMemoryLocked(this, "update", true);
1262                    }
1263                }
1264            }
1265        } else {
1266            if (DEBUG_ANIM && isAnimating()) {
1267                Slog.v(TAG, "prepareSurface: No changes in animation for " + this);
1268            }
1269            displayed = true;
1270        }
1271
1272        if (displayed) {
1273            if (w.mOrientationChanging) {
1274                if (!w.isDrawnLw()) {
1275                    mAnimator.mBulkUpdateParams &= ~SET_ORIENTATION_CHANGE_COMPLETE;
1276                    if (DEBUG_ORIENTATION) Slog.v(TAG,
1277                            "Orientation continue waiting for draw in " + w);
1278                } else {
1279                    w.mOrientationChanging = false;
1280                    if (DEBUG_ORIENTATION) Slog.v(TAG, "Orientation change complete in " + w);
1281                }
1282            }
1283            w.mToken.hasVisible = true;
1284        }
1285    }
1286
1287    void setTransparentRegionHint(final Region region) {
1288        if (mSurface == null) {
1289            Slog.w(TAG, "setTransparentRegionHint: null mSurface after mHasSurface true");
1290            return;
1291        }
1292        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1293            ">>> OPEN TRANSACTION setTransparentRegion");
1294        Surface.openTransaction();
1295        try {
1296            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1297                    "transparentRegionHint=" + region, null);
1298            mSurface.setTransparentRegionHint(region);
1299        } finally {
1300            Surface.closeTransaction();
1301            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1302                    "<<< CLOSE TRANSACTION setTransparentRegion");
1303        }
1304    }
1305
1306    void setWallpaperOffset(int left, int top) {
1307        mSurfaceX = left;
1308        mSurfaceY = top;
1309        if (mAnimating) {
1310            // If this window (or its app token) is animating, then the position
1311            // of the surface will be re-computed on the next animation frame.
1312            // We can't poke it directly here because it depends on whatever
1313            // transformation is being applied by the animation.
1314            return;
1315        }
1316        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1317                ">>> OPEN TRANSACTION setWallpaperOffset");
1318        Surface.openTransaction();
1319        try {
1320            if (WindowManagerService.SHOW_TRANSACTIONS) WindowManagerService.logSurface(mWin,
1321                    "POS " + left + ", " + top, null);
1322            mSurface.setPosition(mWin.mFrame.left + left, mWin.mFrame.top + top);
1323            updateSurfaceWindowCrop(false);
1324        } catch (RuntimeException e) {
1325            Slog.w(TAG, "Error positioning surface of " + mWin
1326                    + " pos=(" + left + "," + top + ")", e);
1327        } finally {
1328            Surface.closeTransaction();
1329            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1330                    "<<< CLOSE TRANSACTION setWallpaperOffset");
1331        }
1332    }
1333
1334    // This must be called while inside a transaction.
1335    boolean performShowLocked() {
1336        if (mWin.isOtherUsersAppWindow()) {
1337            Slog.w(TAG, "Current user " + mService.mCurrentUserId + " trying to display "
1338                    + this + ", type " + mWin.mAttrs.type + ", belonging to " + mWin.mOwnerUid);
1339            return false;
1340        }
1341        if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1342                mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1343            RuntimeException e = null;
1344            if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1345                e = new RuntimeException();
1346                e.fillInStackTrace();
1347            }
1348            Slog.v(TAG, "performShow on " + this
1349                    + ": mDrawState=" + mDrawState + " readyForDisplay="
1350                    + mWin.isReadyForDisplayIgnoringKeyguard()
1351                    + " starting=" + (mWin.mAttrs.type == TYPE_APPLICATION_STARTING)
1352                    + " during animation: policyVis=" + mWin.mPolicyVisibility
1353                    + " attHidden=" + mWin.mAttachedHidden
1354                    + " tok.hiddenRequested="
1355                    + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1356                    + " tok.hidden="
1357                    + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1358                    + " animating=" + mAnimating
1359                    + " tok animating="
1360                    + (mAppAnimator != null ? mAppAnimator.animating : false), e);
1361        }
1362        if (mDrawState == READY_TO_SHOW && mWin.isReadyForDisplayIgnoringKeyguard()) {
1363            if (SHOW_TRANSACTIONS || DEBUG_ORIENTATION)
1364                WindowManagerService.logSurface(mWin, "SHOW (performShowLocked)", null);
1365            if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1366                    mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1367                Slog.v(TAG, "Showing " + this
1368                        + " during animation: policyVis=" + mWin.mPolicyVisibility
1369                        + " attHidden=" + mWin.mAttachedHidden
1370                        + " tok.hiddenRequested="
1371                        + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1372                        + " tok.hidden="
1373                        + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1374                        + " animating=" + mAnimating
1375                        + " tok animating="
1376                        + (mAppAnimator != null ? mAppAnimator.animating : false));
1377            }
1378
1379            mService.enableScreenIfNeededLocked();
1380
1381            applyEnterAnimationLocked();
1382
1383            // Force the show in the next prepareSurfaceLocked() call.
1384            mLastAlpha = -1;
1385            if (DEBUG_SURFACE_TRACE || DEBUG_ANIM)
1386                Slog.v(TAG, "performShowLocked: mDrawState=HAS_DRAWN in " + this);
1387            mDrawState = HAS_DRAWN;
1388            mService.updateLayoutToAnimationLocked();
1389
1390            int i = mWin.mChildWindows.size();
1391            while (i > 0) {
1392                i--;
1393                WindowState c = mWin.mChildWindows.get(i);
1394                if (c.mAttachedHidden) {
1395                    c.mAttachedHidden = false;
1396                    if (c.mWinAnimator.mSurface != null) {
1397                        c.mWinAnimator.performShowLocked();
1398                        // It hadn't been shown, which means layout not
1399                        // performed on it, so now we want to make sure to
1400                        // do a layout.  If called from within the transaction
1401                        // loop, this will cause it to restart with a new
1402                        // layout.
1403                        c.mDisplayContent.layoutNeeded = true;
1404                    }
1405                }
1406            }
1407
1408            if (mWin.mAttrs.type != TYPE_APPLICATION_STARTING
1409                    && mWin.mAppToken != null) {
1410                mWin.mAppToken.firstWindowDrawn = true;
1411
1412                if (mWin.mAppToken.startingData != null) {
1413                    if (WindowManagerService.DEBUG_STARTING_WINDOW ||
1414                            WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1415                            "Finish starting " + mWin.mToken
1416                            + ": first real window is shown, no animation");
1417                    // If this initial window is animating, stop it -- we
1418                    // will do an animation to reveal it from behind the
1419                    // starting window, so there is no need for it to also
1420                    // be doing its own stuff.
1421                    clearAnimation();
1422                    mService.mFinishedStarting.add(mWin.mAppToken);
1423                    mService.mH.sendEmptyMessage(H.FINISHED_STARTING);
1424                }
1425                mWin.mAppToken.updateReportedVisibilityLocked();
1426            }
1427
1428            return true;
1429        }
1430
1431        return false;
1432    }
1433
1434    /**
1435     * Have the surface flinger show a surface, robustly dealing with
1436     * error conditions.  In particular, if there is not enough memory
1437     * to show the surface, then we will try to get rid of other surfaces
1438     * in order to succeed.
1439     *
1440     * @return Returns true if the surface was successfully shown.
1441     */
1442    boolean showSurfaceRobustlyLocked() {
1443        try {
1444            if (mSurface != null) {
1445                mSurfaceShown = true;
1446                mSurface.show();
1447                if (mWin.mTurnOnScreen) {
1448                    if (DEBUG_VISIBILITY) Slog.v(TAG,
1449                            "Show surface turning screen on: " + mWin);
1450                    mWin.mTurnOnScreen = false;
1451                    mAnimator.mBulkUpdateParams |= SET_TURN_ON_SCREEN;
1452                }
1453            }
1454            return true;
1455        } catch (RuntimeException e) {
1456            Slog.w(TAG, "Failure showing surface " + mSurface + " in " + mWin, e);
1457        }
1458
1459        mService.reclaimSomeSurfaceMemoryLocked(this, "show", true);
1460
1461        return false;
1462    }
1463
1464    void applyEnterAnimationLocked() {
1465        final int transit;
1466        if (mEnterAnimationPending) {
1467            mEnterAnimationPending = false;
1468            transit = WindowManagerPolicy.TRANSIT_ENTER;
1469        } else {
1470            transit = WindowManagerPolicy.TRANSIT_SHOW;
1471        }
1472        applyAnimationLocked(transit, true);
1473        mService.scheduleNotifyWindowTranstionIfNeededLocked(mWin, transit);
1474    }
1475
1476    // TODO(cmautner): Move back to WindowState?
1477    /**
1478     * Choose the correct animation and set it to the passed WindowState.
1479     * @param transit If WindowManagerPolicy.TRANSIT_PREVIEW_DONE and the app window has been drawn
1480     *      then the animation will be app_starting_exit. Any other value loads the animation from
1481     *      the switch statement below.
1482     * @param isEntrance The animation type the last time this was called. Used to keep from
1483     *      loading the same animation twice.
1484     * @return true if an animation has been loaded.
1485     */
1486    boolean applyAnimationLocked(int transit, boolean isEntrance) {
1487        if (mLocalAnimating && mAnimationIsEntrance == isEntrance) {
1488            // If we are trying to apply an animation, but already running
1489            // an animation of the same type, then just leave that one alone.
1490            return true;
1491        }
1492
1493        // Only apply an animation if the display isn't frozen.  If it is
1494        // frozen, there is no reason to animate and it can cause strange
1495        // artifacts when we unfreeze the display if some different animation
1496        // is running.
1497        if (mService.okToDisplay()) {
1498            int anim = mPolicy.selectAnimationLw(mWin, transit);
1499            int attr = -1;
1500            Animation a = null;
1501            if (anim != 0) {
1502                a = AnimationUtils.loadAnimation(mContext, anim);
1503            } else {
1504                switch (transit) {
1505                    case WindowManagerPolicy.TRANSIT_ENTER:
1506                        attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1507                        break;
1508                    case WindowManagerPolicy.TRANSIT_EXIT:
1509                        attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1510                        break;
1511                    case WindowManagerPolicy.TRANSIT_SHOW:
1512                        attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1513                        break;
1514                    case WindowManagerPolicy.TRANSIT_HIDE:
1515                        attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1516                        break;
1517                }
1518                if (attr >= 0) {
1519                    a = mService.loadAnimation(mWin.mAttrs, attr);
1520                }
1521            }
1522            if (WindowManagerService.DEBUG_ANIM) Slog.v(TAG,
1523                    "applyAnimation: win=" + this
1524                    + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1525                    + " a=" + a
1526                    + " transit=" + transit
1527                    + " isEntrance=" + isEntrance + " Callers " + Debug.getCallers(3));
1528            if (a != null) {
1529                if (WindowManagerService.DEBUG_ANIM) {
1530                    RuntimeException e = null;
1531                    if (!WindowManagerService.HIDE_STACK_CRAWLS) {
1532                        e = new RuntimeException();
1533                        e.fillInStackTrace();
1534                    }
1535                    Slog.v(TAG, "Loaded animation " + a + " for " + this, e);
1536                }
1537                setAnimation(a);
1538                mAnimationIsEntrance = isEntrance;
1539            }
1540        } else {
1541            clearAnimation();
1542        }
1543
1544        return mAnimation != null;
1545    }
1546
1547    public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1548        if (mAnimating || mLocalAnimating || mAnimationIsEntrance
1549                || mAnimation != null) {
1550            pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
1551                    pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
1552                    pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
1553                    pw.print(" mAnimation="); pw.println(mAnimation);
1554        }
1555        if (mHasTransformation || mHasLocalTransformation) {
1556            pw.print(prefix); pw.print("XForm: has=");
1557                    pw.print(mHasTransformation);
1558                    pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
1559                    pw.print(" "); mTransformation.printShortString(pw);
1560                    pw.println();
1561        }
1562        if (mSurface != null) {
1563            if (dumpAll) {
1564                pw.print(prefix); pw.print("mSurface="); pw.println(mSurface);
1565                pw.print(prefix); pw.print("mDrawState=");
1566                pw.print(drawStateToString(mDrawState));
1567                pw.print(" mLastHidden="); pw.println(mLastHidden);
1568            }
1569            pw.print(prefix); pw.print("Surface: shown="); pw.print(mSurfaceShown);
1570                    pw.print(" layer="); pw.print(mSurfaceLayer);
1571                    pw.print(" alpha="); pw.print(mSurfaceAlpha);
1572                    pw.print(" rect=("); pw.print(mSurfaceX);
1573                    pw.print(","); pw.print(mSurfaceY);
1574                    pw.print(") "); pw.print(mSurfaceW);
1575                    pw.print(" x "); pw.println(mSurfaceH);
1576        }
1577        if (mPendingDestroySurface != null) {
1578            pw.print(prefix); pw.print("mPendingDestroySurface=");
1579                    pw.println(mPendingDestroySurface);
1580        }
1581        if (mSurfaceResized || mSurfaceDestroyDeferred) {
1582            pw.print(prefix); pw.print("mSurfaceResized="); pw.print(mSurfaceResized);
1583                    pw.print(" mSurfaceDestroyDeferred="); pw.println(mSurfaceDestroyDeferred);
1584        }
1585        if (mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_UNIVERSE_BACKGROUND) {
1586            pw.print(prefix); pw.print("mUniverseTransform=");
1587                    mUniverseTransform.printShortString(pw);
1588                    pw.println();
1589        }
1590        if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
1591            pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
1592                    pw.print(" mAlpha="); pw.print(mAlpha);
1593                    pw.print(" mLastAlpha="); pw.println(mLastAlpha);
1594        }
1595        if (mHaveMatrix || mWin.mGlobalScale != 1) {
1596            pw.print(prefix); pw.print("mGlobalScale="); pw.print(mWin.mGlobalScale);
1597                    pw.print(" mDsDx="); pw.print(mDsDx);
1598                    pw.print(" mDtDx="); pw.print(mDtDx);
1599                    pw.print(" mDsDy="); pw.print(mDsDy);
1600                    pw.print(" mDtDy="); pw.println(mDtDy);
1601        }
1602    }
1603
1604    @Override
1605    public String toString() {
1606        StringBuffer sb = new StringBuffer("WindowStateAnimator (");
1607        sb.append(mWin.mLastTitle + "): ");
1608        sb.append("mSurface " + mSurface);
1609        sb.append(", mAnimation " + mAnimation);
1610        return sb.toString();
1611    }
1612}
1613