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