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