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