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