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