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