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