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