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