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