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