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