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