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