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