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