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