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