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