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