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