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