AppWindowAnimator.java revision 92e432c30e2304272c2f5b1b33366f32c3d763cf
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.wm;
18
19import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ANIM;
20import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYERS;
21import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
22import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
23import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
24import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
25import static com.android.server.wm.WindowManagerService.TYPE_LAYER_OFFSET;
26
27import android.graphics.Matrix;
28import android.util.Slog;
29import android.util.TimeUtils;
30import android.view.Choreographer;
31import android.view.Display;
32import android.view.SurfaceControl;
33import android.view.WindowManagerPolicy;
34import android.view.animation.Animation;
35import android.view.animation.Transformation;
36
37import java.io.PrintWriter;
38import java.util.ArrayList;
39
40public class AppWindowAnimator {
41    static final String TAG = TAG_WITH_CLASS_NAME ? "AppWindowAnimator" : TAG_WM;
42
43    private static final int PROLONG_ANIMATION_DISABLED = 0;
44    static final int PROLONG_ANIMATION_AT_END = 1;
45    static final int PROLONG_ANIMATION_AT_START = 2;
46
47    final AppWindowToken mAppToken;
48    final WindowManagerService mService;
49    final WindowAnimator mAnimator;
50
51    boolean animating;
52    boolean wasAnimating;
53    Animation animation;
54    boolean hasTransformation;
55    final Transformation transformation = new Transformation();
56
57    // Have we been asked to have this token keep the screen frozen?
58    // Protect with mAnimator.
59    boolean freezingScreen;
60
61    /**
62     * How long we last kept the screen frozen.
63     */
64    int lastFreezeDuration;
65
66    // Offset to the window of all layers in the token, for use by
67    // AppWindowToken animations.
68    int animLayerAdjustment;
69
70    // Propagated from AppWindowToken.allDrawn, to determine when
71    // the state changes.
72    boolean allDrawn;
73
74    // Special surface for thumbnail animation.  If deferThumbnailDestruction is enabled, then we
75    // will make sure that the thumbnail is destroyed after the other surface is completed.  This
76    // requires that the duration of the two animations are the same.
77    SurfaceControl thumbnail;
78    int thumbnailTransactionSeq;
79    int thumbnailX;
80    int thumbnailY;
81    int thumbnailLayer;
82    int thumbnailForceAboveLayer;
83    Animation thumbnailAnimation;
84    final Transformation thumbnailTransformation = new Transformation();
85    // This flag indicates that the destruction of the thumbnail surface is synchronized with
86    // another animation, so defer the destruction of this thumbnail surface for a single frame
87    // after the secondary animation completes.
88    boolean deferThumbnailDestruction;
89    // This flag is set if the animator has deferThumbnailDestruction set and has reached the final
90    // frame of animation.  It will extend the animation by one frame and then clean up afterwards.
91    boolean deferFinalFrameCleanup;
92    // If true when the animation hits the last frame, it will keep running on that last frame.
93    // This is used to synchronize animation with Recents and we wait for Recents to tell us to
94    // finish or for a new animation be set as fail-safe mechanism.
95    private int mProlongAnimation;
96    // Whether the prolong animation can be removed when animation is set. The purpose of this is
97    // that if recents doesn't tell us to remove the prolonged animation, we will get rid of it
98    // when new animation is set.
99    private boolean mClearProlongedAnimation;
100
101    /** WindowStateAnimator from mAppAnimator.allAppWindows as of last performLayout */
102    ArrayList<WindowStateAnimator> mAllAppWinAnimators = new ArrayList<>();
103
104    /** True if the current animation was transferred from another AppWindowAnimator.
105     *  See {@link #transferCurrentAnimation}*/
106    boolean usingTransferredAnimation = false;
107
108    private boolean mSkipFirstFrame = false;
109
110    static final Animation sDummyAnimation = new DummyAnimation();
111
112    public AppWindowAnimator(final AppWindowToken atoken) {
113        mAppToken = atoken;
114        mService = atoken.service;
115        mAnimator = mService.mAnimator;
116    }
117
118    public void setAnimation(Animation anim, int width, int height, boolean skipFirstFrame) {
119        if (WindowManagerService.localLOGV) Slog.v(TAG, "Setting animation in " + mAppToken
120                + ": " + anim + " wxh=" + width + "x" + height
121                + " isVisible=" + mAppToken.isVisible());
122        animation = anim;
123        animating = false;
124        if (!anim.isInitialized()) {
125            anim.initialize(width, height, width, height);
126        }
127        anim.restrictDuration(WindowManagerService.MAX_ANIMATION_DURATION);
128        anim.scaleCurrentDuration(mService.getTransitionAnimationScaleLocked());
129        int zorder = anim.getZAdjustment();
130        int adj = 0;
131        if (zorder == Animation.ZORDER_TOP) {
132            adj = TYPE_LAYER_OFFSET;
133        } else if (zorder == Animation.ZORDER_BOTTOM) {
134            adj = -TYPE_LAYER_OFFSET;
135        }
136
137        if (animLayerAdjustment != adj) {
138            animLayerAdjustment = adj;
139            updateLayers();
140        }
141        // Start out animation gone if window is gone, or visible if window is visible.
142        transformation.clear();
143        transformation.setAlpha(mAppToken.isVisible() ? 1 : 0);
144        hasTransformation = true;
145
146        this.mSkipFirstFrame = skipFirstFrame;
147
148        if (!mAppToken.appFullscreen) {
149            anim.setBackgroundColor(0);
150        }
151        if (mClearProlongedAnimation) {
152            mProlongAnimation = PROLONG_ANIMATION_DISABLED;
153        } else {
154            mClearProlongedAnimation = true;
155        }
156    }
157
158    public void setDummyAnimation() {
159        if (WindowManagerService.localLOGV) Slog.v(TAG, "Setting dummy animation in " + mAppToken
160                + " isVisible=" + mAppToken.isVisible());
161        animation = sDummyAnimation;
162        hasTransformation = true;
163        transformation.clear();
164        transformation.setAlpha(mAppToken.isVisible() ? 1 : 0);
165    }
166
167    public void clearAnimation() {
168        if (animation != null) {
169            animation = null;
170            animating = true;
171        }
172        clearThumbnail();
173        if (mAppToken.deferClearAllDrawn) {
174            mAppToken.allDrawn = false;
175            mAppToken.deferClearAllDrawn = false;
176        }
177        usingTransferredAnimation = false;
178    }
179
180    public boolean isAnimating() {
181        return animation != null || mAppToken.inPendingTransaction;
182    }
183
184    public void clearThumbnail() {
185        if (thumbnail != null) {
186            thumbnail.destroy();
187            thumbnail = null;
188        }
189        deferThumbnailDestruction = false;
190    }
191
192    void transferCurrentAnimation(
193            AppWindowAnimator toAppAnimator, WindowStateAnimator transferWinAnimator) {
194
195        if (animation != null) {
196            toAppAnimator.animation = animation;
197            animation = null;
198            toAppAnimator.animating = animating;
199            toAppAnimator.animLayerAdjustment = animLayerAdjustment;
200            animLayerAdjustment = 0;
201            toAppAnimator.updateLayers();
202            updateLayers();
203            toAppAnimator.usingTransferredAnimation = true;
204        }
205        if (transferWinAnimator != null) {
206            mAllAppWinAnimators.remove(transferWinAnimator);
207            toAppAnimator.mAllAppWinAnimators.add(transferWinAnimator);
208            transferWinAnimator.mAppAnimator = toAppAnimator;
209        }
210    }
211
212    void updateLayers() {
213        final int windowCount = mAppToken.allAppWindows.size();
214        final int adj = animLayerAdjustment;
215        thumbnailLayer = -1;
216        final WallpaperController wallpaperController = mService.mWallpaperControllerLocked;
217        for (int i = 0; i < windowCount; i++) {
218            final WindowState w = mAppToken.allAppWindows.get(i);
219            final WindowStateAnimator winAnimator = w.mWinAnimator;
220            winAnimator.mAnimLayer = w.mLayer + adj;
221            if (winAnimator.mAnimLayer > thumbnailLayer) {
222                thumbnailLayer = winAnimator.mAnimLayer;
223            }
224            if (DEBUG_LAYERS) Slog.v(TAG, "Updating layer " + w + ": " + winAnimator.mAnimLayer);
225            if (w == mService.mInputMethodTarget && !mService.mInputMethodTargetWaitingAnim) {
226                mService.mLayersController.setInputMethodAnimLayerAdjustment(adj);
227            }
228            wallpaperController.setAnimLayerAdjustment(w, adj);
229        }
230    }
231
232    private void stepThumbnailAnimation(long currentTime) {
233        thumbnailTransformation.clear();
234        final long animationFrameTime = getAnimationFrameTime(thumbnailAnimation, currentTime);
235        thumbnailAnimation.getTransformation(animationFrameTime, thumbnailTransformation);
236        thumbnailTransformation.getMatrix().preTranslate(thumbnailX, thumbnailY);
237
238        ScreenRotationAnimation screenRotationAnimation =
239                mAnimator.getScreenRotationAnimationLocked(Display.DEFAULT_DISPLAY);
240        final boolean screenAnimation = screenRotationAnimation != null
241                && screenRotationAnimation.isAnimating();
242        if (screenAnimation) {
243            thumbnailTransformation.postCompose(screenRotationAnimation.getEnterTransformation());
244        }
245        // cache often used attributes locally
246        final float tmpFloats[] = mService.mTmpFloats;
247        thumbnailTransformation.getMatrix().getValues(tmpFloats);
248        if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(thumbnail,
249                "thumbnail", "POS " + tmpFloats[Matrix.MTRANS_X]
250                + ", " + tmpFloats[Matrix.MTRANS_Y], null);
251        thumbnail.setPosition(tmpFloats[Matrix.MTRANS_X], tmpFloats[Matrix.MTRANS_Y]);
252        if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(thumbnail,
253                "thumbnail", "alpha=" + thumbnailTransformation.getAlpha()
254                + " layer=" + thumbnailLayer
255                + " matrix=[" + tmpFloats[Matrix.MSCALE_X]
256                + "," + tmpFloats[Matrix.MSKEW_Y]
257                + "][" + tmpFloats[Matrix.MSKEW_X]
258                + "," + tmpFloats[Matrix.MSCALE_Y] + "]", null);
259        thumbnail.setAlpha(thumbnailTransformation.getAlpha());
260        if (thumbnailForceAboveLayer > 0) {
261            thumbnail.setLayer(thumbnailForceAboveLayer + 1);
262        } else {
263            // The thumbnail is layered below the window immediately above this
264            // token's anim layer.
265            thumbnail.setLayer(thumbnailLayer + WindowManagerService.WINDOW_LAYER_MULTIPLIER
266                    - WindowManagerService.LAYER_OFFSET_THUMBNAIL);
267        }
268        thumbnail.setMatrix(tmpFloats[Matrix.MSCALE_X], tmpFloats[Matrix.MSKEW_Y],
269                tmpFloats[Matrix.MSKEW_X], tmpFloats[Matrix.MSCALE_Y]);
270    }
271
272    /**
273     * Sometimes we need to synchronize the first frame of animation with some external event, e.g.
274     * Recents hiding some of its content. To achieve this, we prolong the start of the animaiton
275     * and keep producing the first frame of the animation.
276     */
277    private long getAnimationFrameTime(Animation animation, long currentTime) {
278        if (mProlongAnimation == PROLONG_ANIMATION_AT_START) {
279            animation.setStartTime(currentTime);
280            return currentTime + 1;
281        }
282        return currentTime;
283    }
284
285    private boolean stepAnimation(long currentTime) {
286        if (animation == null) {
287            return false;
288        }
289        transformation.clear();
290        final long animationFrameTime = getAnimationFrameTime(animation, currentTime);
291        boolean hasMoreFrames = animation.getTransformation(animationFrameTime, transformation);
292        if (!hasMoreFrames) {
293            if (deferThumbnailDestruction && !deferFinalFrameCleanup) {
294                // We are deferring the thumbnail destruction, so extend the animation for one more
295                // (dummy) frame before we clean up
296                deferFinalFrameCleanup = true;
297                hasMoreFrames = true;
298            } else {
299                if (false && DEBUG_ANIM) Slog.v(TAG,
300                        "Stepped animation in " + mAppToken + ": more=" + hasMoreFrames +
301                        ", xform=" + transformation + ", mProlongAnimation=" + mProlongAnimation);
302                deferFinalFrameCleanup = false;
303                if (mProlongAnimation == PROLONG_ANIMATION_AT_END) {
304                    hasMoreFrames = true;
305                } else {
306                    animation = null;
307                    clearThumbnail();
308                    if (DEBUG_ANIM) Slog.v(TAG, "Finished animation in " + mAppToken + " @ "
309                            + currentTime);
310                }
311            }
312        }
313        hasTransformation = hasMoreFrames;
314        return hasMoreFrames;
315    }
316
317    private long getStartTimeCorrection() {
318        if (mSkipFirstFrame) {
319
320            // If the transition is an animation in which the first frame doesn't change the screen
321            // contents at all, we can just skip it and start at the second frame. So we shift the
322            // start time of the animation forward by minus the frame duration.
323            return -Choreographer.getInstance().getFrameIntervalNanos() / TimeUtils.NANOS_PER_MS;
324        } else {
325            return 0;
326        }
327    }
328
329    // This must be called while inside a transaction.
330    boolean stepAnimationLocked(long currentTime, final int displayId) {
331        if (mService.okToDisplay()) {
332            // We will run animations as long as the display isn't frozen.
333
334            if (animation == sDummyAnimation) {
335                // This guy is going to animate, but not yet.  For now count
336                // it as not animating for purposes of scheduling transactions;
337                // when it is really time to animate, this will be set to
338                // a real animation and the next call will execute normally.
339                return false;
340            }
341
342            if ((mAppToken.allDrawn || mAppToken.mAnimatingWithSavedSurface
343                    || animating || mAppToken.startingDisplayed)
344                    && animation != null) {
345                if (!animating) {
346                    if (DEBUG_ANIM) Slog.v(TAG,
347                        "Starting animation in " + mAppToken +
348                        " @ " + currentTime + " scale="
349                        + mService.getTransitionAnimationScaleLocked()
350                        + " allDrawn=" + mAppToken.allDrawn + " animating=" + animating);
351                    long correction = getStartTimeCorrection();
352                    animation.setStartTime(currentTime + correction);
353                    animating = true;
354                    if (thumbnail != null) {
355                        thumbnail.show();
356                        thumbnailAnimation.setStartTime(currentTime + correction);
357                    }
358                    mSkipFirstFrame = false;
359                }
360                if (stepAnimation(currentTime)) {
361                    // animation isn't over, step any thumbnail and that's
362                    // it for now.
363                    if (thumbnail != null) {
364                        stepThumbnailAnimation(currentTime);
365                    }
366                    return true;
367                }
368            }
369        } else if (animation != null) {
370            // If the display is frozen, and there is a pending animation,
371            // clear it and make sure we run the cleanup code.
372            animating = true;
373            animation = null;
374        }
375
376        hasTransformation = false;
377
378        if (!animating && animation == null) {
379            return false;
380        }
381
382        mAnimator.setAppLayoutChanges(this, WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM,
383                "AppWindowToken", displayId);
384
385        clearAnimation();
386        animating = false;
387        if (animLayerAdjustment != 0) {
388            animLayerAdjustment = 0;
389            updateLayers();
390        }
391        if (mService.mInputMethodTarget != null
392                && mService.mInputMethodTarget.mAppToken == mAppToken) {
393            mService.moveInputMethodWindowsIfNeededLocked(true);
394        }
395
396        if (DEBUG_ANIM) Slog.v(TAG,
397                "Animation done in " + mAppToken
398                + ": reportedVisible=" + mAppToken.reportedVisible);
399
400        transformation.clear();
401
402        final int numAllAppWinAnimators = mAllAppWinAnimators.size();
403        for (int i = 0; i < numAllAppWinAnimators; i++) {
404            mAllAppWinAnimators.get(i).finishExit();
405        }
406        mService.mAppTransition.notifyAppTransitionFinishedLocked(mAppToken.token);
407        return false;
408    }
409
410    // This must be called while inside a transaction.
411    boolean showAllWindowsLocked() {
412        boolean isAnimating = false;
413        final int NW = mAllAppWinAnimators.size();
414        for (int i=0; i<NW; i++) {
415            WindowStateAnimator winAnimator = mAllAppWinAnimators.get(i);
416            if (DEBUG_VISIBILITY) Slog.v(TAG, "performing show on: " + winAnimator);
417            winAnimator.performShowLocked();
418            isAnimating |= winAnimator.isAnimating();
419        }
420        return isAnimating;
421    }
422
423    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
424        pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
425        pw.print(prefix); pw.print("mAnimator="); pw.println(mAnimator);
426        pw.print(prefix); pw.print("freezingScreen="); pw.print(freezingScreen);
427                pw.print(" allDrawn="); pw.print(allDrawn);
428                pw.print(" animLayerAdjustment="); pw.println(animLayerAdjustment);
429        if (lastFreezeDuration != 0) {
430            pw.print(prefix); pw.print("lastFreezeDuration=");
431                    TimeUtils.formatDuration(lastFreezeDuration, pw); pw.println();
432        }
433        if (animating || animation != null) {
434            pw.print(prefix); pw.print("animating="); pw.println(animating);
435            pw.print(prefix); pw.print("animation="); pw.println(animation);
436        }
437        if (hasTransformation) {
438            pw.print(prefix); pw.print("XForm: ");
439                    transformation.printShortString(pw);
440                    pw.println();
441        }
442        if (thumbnail != null) {
443            pw.print(prefix); pw.print("thumbnail="); pw.print(thumbnail);
444                    pw.print(" x="); pw.print(thumbnailX);
445                    pw.print(" y="); pw.print(thumbnailY);
446                    pw.print(" layer="); pw.println(thumbnailLayer);
447            pw.print(prefix); pw.print("thumbnailAnimation="); pw.println(thumbnailAnimation);
448            pw.print(prefix); pw.print("thumbnailTransformation=");
449                    pw.println(thumbnailTransformation.toShortString());
450        }
451        for (int i=0; i<mAllAppWinAnimators.size(); i++) {
452            WindowStateAnimator wanim = mAllAppWinAnimators.get(i);
453            pw.print(prefix); pw.print("App Win Anim #"); pw.print(i);
454                    pw.print(": "); pw.println(wanim);
455        }
456    }
457
458    void startProlongAnimation(int prolongType) {
459        mProlongAnimation = prolongType;
460        mClearProlongedAnimation = false;
461    }
462
463    void endProlongedAnimation() {
464        mProlongAnimation = PROLONG_ANIMATION_DISABLED;
465    }
466
467    // This is an animation that does nothing: it just immediately finishes
468    // itself every time it is called.  It is used as a stub animation in cases
469    // where we want to synchronize multiple things that may be animating.
470    static final class DummyAnimation extends Animation {
471        @Override
472        public boolean getTransformation(long currentTime, Transformation outTransformation) {
473            return false;
474        }
475    }
476
477}
478