WindowStateAnimator.java revision c7294607fc0debc54e92abac18bec2601a21ce27
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        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            return true;
601        }
602
603        return false;
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.transformFromScreenToSurfaceSpace(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                if (task != null && !task.isFullscreen()) {
1338                    final TaskStack stack = task.mStack;
1339                    if (stack != null && !stack.isFullscreen()) {
1340                        stack.getDimBounds(mTmpStackBounds);
1341                        finalClipRect.set(mTmpStackBounds);
1342                    }
1343                }
1344            }
1345            return;
1346        }
1347
1348        final Task task = w.getTask();
1349        if (task == null || !task.cropWindowsToStackBounds()) {
1350            return;
1351        }
1352
1353        final int stackClip = resolveStackClip();
1354
1355        // It's animating and we don't want to clip it to stack bounds during animation - abort.
1356        if (isAnimationSet() && stackClip == STACK_CLIP_NONE) {
1357            return;
1358        }
1359
1360        final WindowState winShowWhenLocked = (WindowState) mPolicy.getWinShowWhenLockedLw();
1361        if (w == winShowWhenLocked && mPolicy.isKeyguardShowingOrOccluded()) {
1362            return;
1363        }
1364
1365        final TaskStack stack = task.mStack;
1366        stack.getDimBounds(mTmpStackBounds);
1367        final Rect surfaceInsets = w.getAttrs().surfaceInsets;
1368        // When we resize we use the big surface approach, which means we can't trust the
1369        // window frame bounds anymore. Instead, the window will be placed at 0, 0, but to avoid
1370        // hardcoding it, we use surface coordinates.
1371        final int frameX = isFreeformResizing ? (int) mSurfaceController.getX() :
1372                w.mFrame.left + mWin.mXOffset - surfaceInsets.left;
1373        final int frameY = isFreeformResizing ? (int) mSurfaceController.getY() :
1374                w.mFrame.top + mWin.mYOffset - surfaceInsets.top;
1375
1376        // If we are animating, we either apply the clip before applying all the animation
1377        // transformation or after all the transformation.
1378        final boolean useFinalClipRect = isAnimationSet() && stackClip == STACK_CLIP_AFTER_ANIM
1379                || mDestroyPreservedSurfaceUponRedraw;
1380
1381        // We need to do some acrobatics with surface position, because their clip region is
1382        // relative to the inside of the surface, but the stack bounds aren't.
1383        if (useFinalClipRect) {
1384            finalClipRect.set(mTmpStackBounds);
1385        } else {
1386            if (StackId.hasWindowShadow(stack.mStackId)
1387                    && !StackId.isTaskResizeAllowed(stack.mStackId)) {
1388                // The windows in this stack display drop shadows and the fill the entire stack
1389                // area. Adjust the stack bounds we will use to cropping take into account the
1390                // offsets we use to display the drop shadow so it doesn't get cropped.
1391                mTmpStackBounds.inset(-surfaceInsets.left, -surfaceInsets.top,
1392                        -surfaceInsets.right, -surfaceInsets.bottom);
1393            }
1394
1395            clipRect.left = Math.max(0,
1396                    Math.max(mTmpStackBounds.left, frameX + clipRect.left) - frameX);
1397            clipRect.top = Math.max(0,
1398                    Math.max(mTmpStackBounds.top, frameY + clipRect.top) - frameY);
1399            clipRect.right = Math.max(0,
1400                    Math.min(mTmpStackBounds.right, frameX + clipRect.right) - frameX);
1401            clipRect.bottom = Math.max(0,
1402                    Math.min(mTmpStackBounds.bottom, frameY + clipRect.bottom) - frameY);
1403        }
1404    }
1405
1406    void setSurfaceBoundariesLocked(final boolean recoveringMemory) {
1407        final WindowState w = mWin;
1408        final Task task = w.getTask();
1409
1410        // We got resized, so block all updates until we got the new surface.
1411        if (w.mResizedWhileNotDragResizing && !w.isGoneForLayoutLw()) {
1412            return;
1413        }
1414
1415        mTmpSize.set(w.mShownPosition.x, w.mShownPosition.y, 0, 0);
1416        calculateSurfaceBounds(w, w.getAttrs());
1417
1418        float extraHScale = (float) 1.0;
1419        float extraVScale = (float) 1.0;
1420
1421        mSurfaceResized = mSurfaceController.setSizeInTransaction(
1422                mTmpSize.width(), mTmpSize.height(), recoveringMemory);
1423        mForceScaleUntilResize = mForceScaleUntilResize && !mSurfaceResized;
1424
1425
1426        calculateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect);
1427        if ((task != null && task.mStack.getForceScaleToCrop()) || mForceScaleUntilResize) {
1428            int hInsets = w.getAttrs().surfaceInsets.left + w.getAttrs().surfaceInsets.right;
1429            int vInsets = w.getAttrs().surfaceInsets.top + w.getAttrs().surfaceInsets.bottom;
1430            // We want to calculate the scaling based on the content area, not based on
1431            // the entire surface, so that we scale in sync with windows that don't have insets.
1432            extraHScale = (mTmpClipRect.width() - hInsets) / (float)(mTmpSize.width() - hInsets);
1433            extraVScale = (mTmpClipRect.height() - vInsets) / (float)(mTmpSize.height() - vInsets);
1434
1435            // In the case of ForceScaleToCrop we scale entire tasks together,
1436            // and so we need to scale our offsets relative to the task bounds
1437            // or parent and child windows would fall out of alignment.
1438            int posX = (int) (mTmpSize.left - w.mAttrs.x * (1 - extraHScale));
1439            int posY = (int) (mTmpSize.top - w.mAttrs.y * (1 - extraVScale));
1440            // Imagine we are scaling down. As we scale the buffer down, we decrease the
1441            // distance between the surface top left, and the start of the surface contents
1442            // (previously it was surfaceInsets.left pixels in screen space but now it
1443            // will be surfaceInsets.left*extraHScale). This means in order to keep the
1444            // non inset content at the same position, we have to shift the whole window
1445            // forward. Likewise for scaling up, we've increased this distance, and we need
1446            // to shift by a negative number to compensate.
1447            posX += w.getAttrs().surfaceInsets.left * (1 - extraHScale);
1448            posY += w.getAttrs().surfaceInsets.top * (1 - extraVScale);
1449
1450            mSurfaceController.setPositionInTransaction(posX, posY, recoveringMemory);
1451
1452            // Since we are scaled to fit in our previously desired crop, we can now
1453            // expose the whole window in buffer space, and not risk extending
1454            // past where the system would have cropped us
1455            mTmpClipRect.set(0, 0, mTmpSize.width(), mTmpSize.height());
1456            mTmpFinalClipRect.setEmpty();
1457
1458            // Various surfaces in the scaled stack may resize at different times.
1459            // We need to ensure for each surface, that we disable transformation matrix
1460            // scaling in the same transaction which we resize the surface in.
1461            // As we are in SCALING_MODE_SCALE_TO_WINDOW, SurfaceFlinger will
1462            // then take over the scaling until the new buffer arrives, and things
1463            // will be seamless.
1464            mForceScaleUntilResize = true;
1465        } else {
1466            mSurfaceController.setPositionInTransaction(mTmpSize.left, mTmpSize.top,
1467                    recoveringMemory);
1468        }
1469
1470        updateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect, recoveringMemory);
1471
1472        mSurfaceController.setMatrixInTransaction(mDsDx * w.mHScale * extraHScale,
1473                mDtDx * w.mVScale * extraVScale,
1474                mDsDy * w.mHScale * extraHScale,
1475                mDtDy * w.mVScale * extraVScale, recoveringMemory);
1476
1477        if (mSurfaceResized) {
1478            mReportSurfaceResized = true;
1479            mAnimator.setPendingLayoutChanges(w.getDisplayId(),
1480                    WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER);
1481            w.applyDimLayerIfNeeded();
1482        }
1483
1484    }
1485
1486    void prepareSurfaceLocked(final boolean recoveringMemory) {
1487        final WindowState w = mWin;
1488        if (!hasSurface()) {
1489            if (w.mOrientationChanging) {
1490                if (DEBUG_ORIENTATION) {
1491                    Slog.v(TAG, "Orientation change skips hidden " + w);
1492                }
1493                w.mOrientationChanging = false;
1494            }
1495            return;
1496        }
1497
1498        // Do not change surface properties of opening apps if we are waiting for the
1499        // transition to be ready. transitionGoodToGo could be not ready even after all
1500        // opening apps are drawn. It's only waiting on isFetchingAppTransitionsSpecs()
1501        // to get the animation spec. (For example, go into Recents and immediately open
1502        // the same app again before the app's surface is destroyed or saved, the surface
1503        // is always ready in the whole process.) If we go ahead here, the opening app
1504        // will be shown with the full size before the correct animation spec arrives.
1505        if (isWaitingForOpening()) {
1506            return;
1507        }
1508
1509        boolean displayed = false;
1510
1511        computeShownFrameLocked();
1512
1513        setSurfaceBoundariesLocked(recoveringMemory);
1514
1515        if (mIsWallpaper && !mWin.mWallpaperVisible) {
1516            // Wallpaper is no longer visible and there is no wp target => hide it.
1517            hide("prepareSurfaceLocked");
1518        } else if (w.mAttachedHidden || !w.isOnScreen()) {
1519            hide("prepareSurfaceLocked");
1520            mWallpaperControllerLocked.hideWallpapers(w);
1521
1522            // If we are waiting for this window to handle an
1523            // orientation change, well, it is hidden, so
1524            // doesn't really matter.  Note that this does
1525            // introduce a potential glitch if the window
1526            // becomes unhidden before it has drawn for the
1527            // new orientation.
1528            if (w.mOrientationChanging) {
1529                w.mOrientationChanging = false;
1530                if (DEBUG_ORIENTATION) Slog.v(TAG,
1531                        "Orientation change skips hidden " + w);
1532            }
1533        } else if (mLastLayer != mAnimLayer
1534                || mLastAlpha != mShownAlpha
1535                || mLastDsDx != mDsDx
1536                || mLastDtDx != mDtDx
1537                || mLastDsDy != mDsDy
1538                || mLastDtDy != mDtDy
1539                || w.mLastHScale != w.mHScale
1540                || w.mLastVScale != w.mVScale
1541                || mLastHidden) {
1542            displayed = true;
1543            mLastAlpha = mShownAlpha;
1544            mLastLayer = mAnimLayer;
1545            mLastDsDx = mDsDx;
1546            mLastDtDx = mDtDx;
1547            mLastDsDy = mDsDy;
1548            mLastDtDy = mDtDy;
1549            w.mLastHScale = w.mHScale;
1550            w.mLastVScale = w.mVScale;
1551            if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
1552                    "controller=" + mSurfaceController +
1553                    "alpha=" + mShownAlpha + " layer=" + mAnimLayer
1554                    + " matrix=[" + mDsDx + "*" + w.mHScale
1555                    + "," + mDtDx + "*" + w.mVScale
1556                    + "][" + mDsDy + "*" + w.mHScale
1557                    + "," + mDtDy + "*" + w.mVScale + "]", false);
1558
1559            boolean prepared =
1560                mSurfaceController.prepareToShowInTransaction(mShownAlpha, mAnimLayer,
1561                        mDsDx * w.mHScale, mDtDx * w.mVScale,
1562                        mDsDy * w.mHScale, mDtDy * w.mVScale,
1563                        recoveringMemory);
1564
1565            if (prepared && mLastHidden && mDrawState == HAS_DRAWN) {
1566                if (showSurfaceRobustlyLocked()) {
1567                    markPreservedSurfaceForDestroy();
1568                    mAnimator.requestRemovalOfReplacedWindows(w);
1569                    mLastHidden = false;
1570                    if (mIsWallpaper) {
1571                        mWallpaperControllerLocked.dispatchWallpaperVisibility(w, true);
1572                    }
1573                    // This draw means the difference between unique content and mirroring.
1574                    // Run another pass through performLayout to set mHasContent in the
1575                    // LogicalDisplay.
1576                    mAnimator.setPendingLayoutChanges(w.getDisplayId(),
1577                            WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM);
1578                } else {
1579                    w.mOrientationChanging = false;
1580                }
1581            }
1582            if (hasSurface()) {
1583                w.mToken.hasVisible = true;
1584            }
1585        } else {
1586            if (DEBUG_ANIM && isAnimationSet()) {
1587                Slog.v(TAG, "prepareSurface: No changes in animation for " + this);
1588            }
1589            displayed = true;
1590        }
1591
1592        if (displayed) {
1593            if (w.mOrientationChanging) {
1594                if (!w.isDrawnLw()) {
1595                    mAnimator.mBulkUpdateParams &= ~SET_ORIENTATION_CHANGE_COMPLETE;
1596                    mAnimator.mLastWindowFreezeSource = w;
1597                    if (DEBUG_ORIENTATION) Slog.v(TAG,
1598                            "Orientation continue waiting for draw in " + w);
1599                } else {
1600                    w.mOrientationChanging = false;
1601                    if (DEBUG_ORIENTATION) Slog.v(TAG, "Orientation change complete in " + w);
1602                }
1603            }
1604            w.mToken.hasVisible = true;
1605        }
1606    }
1607
1608    void setTransparentRegionHintLocked(final Region region) {
1609        if (mSurfaceController == null) {
1610            Slog.w(TAG, "setTransparentRegionHint: null mSurface after mHasSurface true");
1611            return;
1612        }
1613        mSurfaceController.setTransparentRegionHint(region);
1614    }
1615
1616    void setWallpaperOffset(Point shownPosition) {
1617        final LayoutParams attrs = mWin.getAttrs();
1618        final int left = shownPosition.x - attrs.surfaceInsets.left;
1619        final int top = shownPosition.y - attrs.surfaceInsets.top;
1620
1621        try {
1622            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG, ">>> OPEN TRANSACTION setWallpaperOffset");
1623            SurfaceControl.openTransaction();
1624            mSurfaceController.setPositionInTransaction(mWin.mFrame.left + left,
1625                    mWin.mFrame.top + top, false);
1626            calculateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect);
1627            updateSurfaceWindowCrop(mTmpClipRect, mTmpFinalClipRect, false);
1628        } catch (RuntimeException e) {
1629            Slog.w(TAG, "Error positioning surface of " + mWin
1630                    + " pos=(" + left + "," + top + ")", e);
1631        } finally {
1632            SurfaceControl.closeTransaction();
1633            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1634                    "<<< CLOSE TRANSACTION setWallpaperOffset");
1635        }
1636    }
1637
1638    /**
1639     * Try to change the pixel format without recreating the surface. This
1640     * will be common in the case of changing from PixelFormat.OPAQUE to
1641     * PixelFormat.TRANSLUCENT in the hardware-accelerated case as both
1642     * requested formats resolve to the same underlying SurfaceControl format
1643     * @return True if format was succesfully changed, false otherwise
1644     */
1645    boolean tryChangeFormatInPlaceLocked() {
1646        if (mSurfaceController == null) {
1647            return false;
1648        }
1649        final LayoutParams attrs = mWin.getAttrs();
1650        final boolean isHwAccelerated = (attrs.flags & FLAG_HARDWARE_ACCELERATED) != 0;
1651        final int format = isHwAccelerated ? PixelFormat.TRANSLUCENT : attrs.format;
1652        if (format == mSurfaceFormat) {
1653            setOpaqueLocked(!PixelFormat.formatHasAlpha(attrs.format));
1654            return true;
1655        }
1656        return false;
1657    }
1658
1659    void setOpaqueLocked(boolean isOpaque) {
1660        if (mSurfaceController == null) {
1661            return;
1662        }
1663        mSurfaceController.setOpaque(isOpaque);
1664    }
1665
1666    void setSecureLocked(boolean isSecure) {
1667        if (mSurfaceController == null) {
1668            return;
1669        }
1670        mSurfaceController.setSecure(isSecure);
1671    }
1672
1673    // This must be called while inside a transaction.
1674    boolean performShowLocked() {
1675        if (mWin.isHiddenFromUserLocked()) {
1676            if (DEBUG_VISIBILITY) Slog.w(TAG, "hiding " + mWin + ", belonging to " + mWin.mOwnerUid);
1677            mWin.hideLw(false);
1678            return false;
1679        }
1680        if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1681                mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1682            Slog.v(TAG, "performShow on " + this
1683                    + ": mDrawState=" + drawStateToString() + " readyForDisplay="
1684                    + mWin.isReadyForDisplayIgnoringKeyguard()
1685                    + " starting=" + (mWin.mAttrs.type == TYPE_APPLICATION_STARTING)
1686                    + " during animation: policyVis=" + mWin.mPolicyVisibility
1687                    + " attHidden=" + mWin.mAttachedHidden
1688                    + " tok.hiddenRequested="
1689                    + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1690                    + " tok.hidden="
1691                    + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1692                    + " animating=" + mAnimating
1693                    + " tok animating="
1694                    + (mAppAnimator != null ? mAppAnimator.animating : false) + " Callers="
1695                    + Debug.getCallers(3));
1696        }
1697        if (mDrawState == READY_TO_SHOW && mWin.isReadyForDisplayIgnoringKeyguard()) {
1698            if (DEBUG_VISIBILITY || (DEBUG_STARTING_WINDOW &&
1699                    mWin.mAttrs.type == WindowManager.LayoutParams.TYPE_APPLICATION_STARTING)) {
1700                Slog.v(TAG, "Showing " + this
1701                        + " during animation: policyVis=" + mWin.mPolicyVisibility
1702                        + " attHidden=" + mWin.mAttachedHidden
1703                        + " tok.hiddenRequested="
1704                        + (mWin.mAppToken != null ? mWin.mAppToken.hiddenRequested : false)
1705                        + " tok.hidden="
1706                        + (mWin.mAppToken != null ? mWin.mAppToken.hidden : false)
1707                        + " animating=" + mAnimating
1708                        + " tok animating="
1709                        + (mAppAnimator != null ? mAppAnimator.animating : false));
1710            }
1711
1712            mService.enableScreenIfNeededLocked();
1713
1714            applyEnterAnimationLocked();
1715
1716            // Force the show in the next prepareSurfaceLocked() call.
1717            mLastAlpha = -1;
1718            if (DEBUG_SURFACE_TRACE || DEBUG_ANIM)
1719                Slog.v(TAG, "performShowLocked: mDrawState=HAS_DRAWN in " + mWin);
1720            mDrawState = HAS_DRAWN;
1721            mService.scheduleAnimationLocked();
1722
1723            int i = mWin.mChildWindows.size();
1724            while (i > 0) {
1725                i--;
1726                WindowState c = mWin.mChildWindows.get(i);
1727                if (c.mAttachedHidden) {
1728                    c.mAttachedHidden = false;
1729                    if (c.mWinAnimator.mSurfaceController != null) {
1730                        c.mWinAnimator.performShowLocked();
1731                        // It hadn't been shown, which means layout not
1732                        // performed on it, so now we want to make sure to
1733                        // do a layout.  If called from within the transaction
1734                        // loop, this will cause it to restart with a new
1735                        // layout.
1736                        final DisplayContent displayContent = c.getDisplayContent();
1737                        if (displayContent != null) {
1738                            displayContent.layoutNeeded = true;
1739                        }
1740                    }
1741                }
1742            }
1743
1744            if (mWin.mAttrs.type != TYPE_APPLICATION_STARTING && mWin.mAppToken != null) {
1745                mWin.mAppToken.onFirstWindowDrawn(mWin, this);
1746            }
1747
1748            return true;
1749        }
1750        return false;
1751    }
1752
1753    /**
1754     * Have the surface flinger show a surface, robustly dealing with
1755     * error conditions.  In particular, if there is not enough memory
1756     * to show the surface, then we will try to get rid of other surfaces
1757     * in order to succeed.
1758     *
1759     * @return Returns true if the surface was successfully shown.
1760     */
1761    private boolean showSurfaceRobustlyLocked() {
1762        final Task task = mWin.getTask();
1763        if (task != null && StackId.windowsAreScaleable(task.mStack.mStackId)) {
1764            mSurfaceController.forceScaleableInTransaction(true);
1765        }
1766
1767        boolean shown = mSurfaceController.showRobustlyInTransaction();
1768        if (!shown)
1769            return false;
1770
1771        if (mWin.mTurnOnScreen) {
1772            if (DEBUG_VISIBILITY) Slog.v(TAG, "Show surface turning screen on: " + mWin);
1773            mWin.mTurnOnScreen = false;
1774            mAnimator.mBulkUpdateParams |= SET_TURN_ON_SCREEN;
1775        }
1776        return true;
1777    }
1778
1779    void applyEnterAnimationLocked() {
1780        // If we are the new part of a window replacement transition and we have requested
1781        // not to animate, we instead want to make it seamless, so we don't want to apply
1782        // an enter transition.
1783        if (mWin.mSkipEnterAnimationForSeamlessReplacement) {
1784            return;
1785        }
1786        final int transit;
1787        if (mEnterAnimationPending) {
1788            mEnterAnimationPending = false;
1789            transit = WindowManagerPolicy.TRANSIT_ENTER;
1790        } else {
1791            transit = WindowManagerPolicy.TRANSIT_SHOW;
1792        }
1793        applyAnimationLocked(transit, true);
1794        //TODO (multidisplay): Magnification is supported only for the default display.
1795        if (mService.mAccessibilityController != null
1796                && mWin.getDisplayId() == DEFAULT_DISPLAY) {
1797            mService.mAccessibilityController.onWindowTransitionLocked(mWin, transit);
1798        }
1799    }
1800
1801    /**
1802     * Choose the correct animation and set it to the passed WindowState.
1803     * @param transit If AppTransition.TRANSIT_PREVIEW_DONE and the app window has been drawn
1804     *      then the animation will be app_starting_exit. Any other value loads the animation from
1805     *      the switch statement below.
1806     * @param isEntrance The animation type the last time this was called. Used to keep from
1807     *      loading the same animation twice.
1808     * @return true if an animation has been loaded.
1809     */
1810    boolean applyAnimationLocked(int transit, boolean isEntrance) {
1811        if ((mLocalAnimating && mAnimationIsEntrance == isEntrance)
1812                || mKeyguardGoingAwayAnimation) {
1813            // If we are trying to apply an animation, but already running
1814            // an animation of the same type, then just leave that one alone.
1815
1816            // If we are in a keyguard exit animation, and the window should animate away, modify
1817            // keyguard exit animation such that it also fades out.
1818            if (mAnimation != null && mKeyguardGoingAwayAnimation
1819                    && transit == WindowManagerPolicy.TRANSIT_PREVIEW_DONE) {
1820                applyFadeoutDuringKeyguardExitAnimation();
1821            }
1822            return true;
1823        }
1824
1825        // Only apply an animation if the display isn't frozen.  If it is
1826        // frozen, there is no reason to animate and it can cause strange
1827        // artifacts when we unfreeze the display if some different animation
1828        // is running.
1829        if (mService.okToDisplay()) {
1830            int anim = mPolicy.selectAnimationLw(mWin, transit);
1831            int attr = -1;
1832            Animation a = null;
1833            if (anim != 0) {
1834                a = anim != -1 ? AnimationUtils.loadAnimation(mContext, anim) : null;
1835            } else {
1836                switch (transit) {
1837                    case WindowManagerPolicy.TRANSIT_ENTER:
1838                        attr = com.android.internal.R.styleable.WindowAnimation_windowEnterAnimation;
1839                        break;
1840                    case WindowManagerPolicy.TRANSIT_EXIT:
1841                        attr = com.android.internal.R.styleable.WindowAnimation_windowExitAnimation;
1842                        break;
1843                    case WindowManagerPolicy.TRANSIT_SHOW:
1844                        attr = com.android.internal.R.styleable.WindowAnimation_windowShowAnimation;
1845                        break;
1846                    case WindowManagerPolicy.TRANSIT_HIDE:
1847                        attr = com.android.internal.R.styleable.WindowAnimation_windowHideAnimation;
1848                        break;
1849                }
1850                if (attr >= 0) {
1851                    a = mService.mAppTransition.loadAnimationAttr(mWin.mAttrs, attr);
1852                }
1853            }
1854            if (DEBUG_ANIM) Slog.v(TAG,
1855                    "applyAnimation: win=" + this
1856                    + " anim=" + anim + " attr=0x" + Integer.toHexString(attr)
1857                    + " a=" + a
1858                    + " transit=" + transit
1859                    + " isEntrance=" + isEntrance + " Callers " + Debug.getCallers(3));
1860            if (a != null) {
1861                if (DEBUG_ANIM) logWithStack(TAG, "Loaded animation " + a + " for " + this);
1862                setAnimation(a);
1863                mAnimationIsEntrance = isEntrance;
1864            }
1865        } else {
1866            clearAnimation();
1867        }
1868        if (mWin.mAttrs.type == TYPE_INPUT_METHOD) {
1869            mService.adjustForImeIfNeeded(mWin.mDisplayContent);
1870            if (isEntrance) {
1871                mWin.setDisplayLayoutNeeded();
1872                mService.mWindowPlacerLocked.requestTraversal();
1873            }
1874        }
1875        return mAnimation != null;
1876    }
1877
1878    private void applyFadeoutDuringKeyguardExitAnimation() {
1879        long startTime = mAnimation.getStartTime();
1880        long duration = mAnimation.getDuration();
1881        long elapsed = mLastAnimationTime - startTime;
1882        long fadeDuration = duration - elapsed;
1883        if (fadeDuration <= 0) {
1884            // Never mind, this would be no visible animation, so abort the animation change.
1885            return;
1886        }
1887        AnimationSet newAnimation = new AnimationSet(false /* shareInterpolator */);
1888        newAnimation.setDuration(duration);
1889        newAnimation.setStartTime(startTime);
1890        newAnimation.addAnimation(mAnimation);
1891        Animation fadeOut = AnimationUtils.loadAnimation(
1892                mContext, com.android.internal.R.anim.app_starting_exit);
1893        fadeOut.setDuration(fadeDuration);
1894        fadeOut.setStartOffset(elapsed);
1895        newAnimation.addAnimation(fadeOut);
1896        newAnimation.initialize(mWin.mFrame.width(), mWin.mFrame.height(), mAnimDx, mAnimDy);
1897        mAnimation = newAnimation;
1898    }
1899
1900    public void dump(PrintWriter pw, String prefix, boolean dumpAll) {
1901        if (mAnimating || mLocalAnimating || mAnimationIsEntrance
1902                || mAnimation != null) {
1903            pw.print(prefix); pw.print("mAnimating="); pw.print(mAnimating);
1904                    pw.print(" mLocalAnimating="); pw.print(mLocalAnimating);
1905                    pw.print(" mAnimationIsEntrance="); pw.print(mAnimationIsEntrance);
1906                    pw.print(" mAnimation="); pw.print(mAnimation);
1907                    pw.print(" mStackClip="); pw.println(mStackClip);
1908        }
1909        if (mHasTransformation || mHasLocalTransformation) {
1910            pw.print(prefix); pw.print("XForm: has=");
1911                    pw.print(mHasTransformation);
1912                    pw.print(" hasLocal="); pw.print(mHasLocalTransformation);
1913                    pw.print(" "); mTransformation.printShortString(pw);
1914                    pw.println();
1915        }
1916        if (mSurfaceController != null) {
1917            mSurfaceController.dump(pw, prefix, dumpAll);
1918        }
1919        if (dumpAll) {
1920            pw.print(prefix); pw.print("mDrawState="); pw.print(drawStateToString());
1921            pw.print(prefix); pw.print(" mLastHidden="); pw.println(mLastHidden);
1922            pw.print(prefix); pw.print("mSystemDecorRect="); mSystemDecorRect.printShortString(pw);
1923            pw.print(" last="); mLastSystemDecorRect.printShortString(pw);
1924            pw.print(" mHasClipRect="); pw.print(mHasClipRect);
1925            pw.print(" mLastClipRect="); mLastClipRect.printShortString(pw);
1926
1927            if (!mLastFinalClipRect.isEmpty()) {
1928                pw.print(" mLastFinalClipRect="); mLastFinalClipRect.printShortString(pw);
1929            }
1930            pw.println();
1931        }
1932
1933        if (mPendingDestroySurface != null) {
1934            pw.print(prefix); pw.print("mPendingDestroySurface=");
1935                    pw.println(mPendingDestroySurface);
1936        }
1937        if (mSurfaceResized || mSurfaceDestroyDeferred) {
1938            pw.print(prefix); pw.print("mSurfaceResized="); pw.print(mSurfaceResized);
1939                    pw.print(" mSurfaceDestroyDeferred="); pw.println(mSurfaceDestroyDeferred);
1940        }
1941        if (mShownAlpha != 1 || mAlpha != 1 || mLastAlpha != 1) {
1942            pw.print(prefix); pw.print("mShownAlpha="); pw.print(mShownAlpha);
1943                    pw.print(" mAlpha="); pw.print(mAlpha);
1944                    pw.print(" mLastAlpha="); pw.println(mLastAlpha);
1945        }
1946        if (mHaveMatrix || mWin.mGlobalScale != 1) {
1947            pw.print(prefix); pw.print("mGlobalScale="); pw.print(mWin.mGlobalScale);
1948                    pw.print(" mDsDx="); pw.print(mDsDx);
1949                    pw.print(" mDtDx="); pw.print(mDtDx);
1950                    pw.print(" mDsDy="); pw.print(mDsDy);
1951                    pw.print(" mDtDy="); pw.println(mDtDy);
1952        }
1953        if (mAnimationStartDelayed) {
1954            pw.print(prefix); pw.print("mAnimationStartDelayed="); pw.print(mAnimationStartDelayed);
1955        }
1956    }
1957
1958    @Override
1959    public String toString() {
1960        StringBuffer sb = new StringBuffer("WindowStateAnimator{");
1961        sb.append(Integer.toHexString(System.identityHashCode(this)));
1962        sb.append(' ');
1963        sb.append(mWin.mAttrs.getTitle());
1964        sb.append('}');
1965        return sb.toString();
1966    }
1967
1968    void reclaimSomeSurfaceMemory(String operation, boolean secure) {
1969        mService.reclaimSomeSurfaceMemoryLocked(this, operation, secure);
1970    }
1971
1972    boolean getShown() {
1973        if (mSurfaceController != null) {
1974            return mSurfaceController.getShown();
1975        }
1976        return false;
1977    }
1978
1979    void destroySurface() {
1980        try {
1981            if (mSurfaceController != null) {
1982                mSurfaceController.destroyInTransaction();
1983            }
1984        } catch (RuntimeException e) {
1985            Slog.w(TAG, "Exception thrown when destroying surface " + this
1986                    + " surface " + mSurfaceController + " session " + mSession + ": " + e);
1987        } finally {
1988            mWin.setHasSurface(false);
1989            mSurfaceController = null;
1990            mDrawState = NO_SURFACE;
1991        }
1992    }
1993
1994    void setMoveAnimation(int left, int top) {
1995        final Animation a = AnimationUtils.loadAnimation(mContext,
1996                com.android.internal.R.anim.window_move_from_decor);
1997        setAnimation(a);
1998        mAnimDx = mWin.mLastFrame.left - left;
1999        mAnimDy = mWin.mLastFrame.top - top;
2000        mAnimateMove = true;
2001    }
2002
2003    void deferTransactionUntilParentFrame(long frameNumber) {
2004        if (!mWin.isChildWindow()) {
2005            return;
2006        }
2007        mDeferTransactionUntilFrame = frameNumber;
2008        mDeferTransactionTime = System.currentTimeMillis();
2009        mSurfaceController.deferTransactionUntil(
2010                mWin.mAttachedWindow.mWinAnimator.mSurfaceController.getHandle(),
2011                frameNumber);
2012    }
2013
2014    // Defer the current transaction to the frame number of the last saved transaction.
2015    // We do this to avoid shooting through an unsynchronized transaction while something is
2016    // pending. This is generally fine, as either we will get in on the synchronization,
2017    // or SurfaceFlinger will see that the frame has already occured. The only
2018    // potential problem is in frame number resets so we reset things with a timeout
2019    // every so often to be careful.
2020    void deferToPendingTransaction() {
2021        if (mDeferTransactionUntilFrame < 0) {
2022            return;
2023        }
2024        long time = System.currentTimeMillis();
2025        if (time > mDeferTransactionTime + PENDING_TRANSACTION_FINISH_WAIT_TIME) {
2026            mDeferTransactionTime = -1;
2027            mDeferTransactionUntilFrame = -1;
2028        } else {
2029            mSurfaceController.deferTransactionUntil(
2030                    mWin.mAttachedWindow.mWinAnimator.mSurfaceController.getHandle(),
2031                    mDeferTransactionUntilFrame);
2032        }
2033    }
2034
2035    /**
2036     * Sometimes we need to synchronize the first frame of animation with some external event.
2037     * To achieve this, we prolong the start of the animation and keep producing the first frame of
2038     * the animation.
2039     */
2040    private long getAnimationFrameTime(Animation animation, long currentTime) {
2041        if (mAnimationStartDelayed) {
2042            animation.setStartTime(currentTime);
2043            return currentTime + 1;
2044        }
2045        return currentTime;
2046    }
2047
2048    void startDelayingAnimationStart() {
2049        mAnimationStartDelayed = true;
2050    }
2051
2052    void endDelayingAnimationStart() {
2053        mAnimationStartDelayed = false;
2054    }
2055}
2056