AppWindowAnimator.java revision 3dac63a18d9115405404561d327010604420b07b
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        // Since we are finally starting our animation, we don't need the logic anymore to prevent
158        // the app from showing again if we just moved between stacks. See
159        // {@link WindowState#notifyMovedInStack}.
160        for (int i = mAppToken.allAppWindows.size() - 1; i >= 0; i--) {
161            mAppToken.allAppWindows.get(i).resetJustMovedInStack();
162        }
163    }
164
165    public void setDummyAnimation() {
166        if (WindowManagerService.localLOGV) Slog.v(TAG, "Setting dummy animation in " + mAppToken
167                + " isVisible=" + mAppToken.isVisible());
168        animation = sDummyAnimation;
169        hasTransformation = true;
170        transformation.clear();
171        transformation.setAlpha(mAppToken.isVisible() ? 1 : 0);
172    }
173
174    public void clearAnimation() {
175        if (animation != null) {
176            animation = null;
177            animating = true;
178        }
179        clearThumbnail();
180        if (mAppToken.deferClearAllDrawn) {
181            mAppToken.allDrawn = false;
182            mAppToken.deferClearAllDrawn = false;
183        }
184        usingTransferredAnimation = false;
185    }
186
187    public boolean isAnimating() {
188        return animation != null || mAppToken.inPendingTransaction;
189    }
190
191    public void clearThumbnail() {
192        if (thumbnail != null) {
193            thumbnail.hide();
194            mService.mWindowPlacerLocked.destroyAfterTransaction(thumbnail);
195            thumbnail = null;
196        }
197        deferThumbnailDestruction = false;
198    }
199
200    void transferCurrentAnimation(
201            AppWindowAnimator toAppAnimator, WindowStateAnimator transferWinAnimator) {
202
203        if (animation != null) {
204            toAppAnimator.animation = animation;
205            animation = null;
206            toAppAnimator.animating = animating;
207            toAppAnimator.animLayerAdjustment = animLayerAdjustment;
208            animLayerAdjustment = 0;
209            toAppAnimator.updateLayers();
210            updateLayers();
211            toAppAnimator.usingTransferredAnimation = true;
212        }
213        if (transferWinAnimator != null) {
214            mAllAppWinAnimators.remove(transferWinAnimator);
215            toAppAnimator.mAllAppWinAnimators.add(transferWinAnimator);
216            transferWinAnimator.mAppAnimator = toAppAnimator;
217        }
218    }
219
220    void updateLayers() {
221        final int windowCount = mAppToken.allAppWindows.size();
222        final int adj = animLayerAdjustment;
223        thumbnailLayer = -1;
224        final WallpaperController wallpaperController = mService.mWallpaperControllerLocked;
225        for (int i = 0; i < windowCount; i++) {
226            final WindowState w = mAppToken.allAppWindows.get(i);
227            final WindowStateAnimator winAnimator = w.mWinAnimator;
228            winAnimator.mAnimLayer = w.mLayer + adj;
229            if (winAnimator.mAnimLayer > thumbnailLayer) {
230                thumbnailLayer = winAnimator.mAnimLayer;
231            }
232            if (DEBUG_LAYERS) Slog.v(TAG, "Updating layer " + w + ": " + winAnimator.mAnimLayer);
233            if (w == mService.mInputMethodTarget && !mService.mInputMethodTargetWaitingAnim) {
234                mService.mLayersController.setInputMethodAnimLayerAdjustment(adj);
235            }
236            wallpaperController.setAnimLayerAdjustment(w, adj);
237        }
238    }
239
240    private void stepThumbnailAnimation(long currentTime) {
241        thumbnailTransformation.clear();
242        final long animationFrameTime = getAnimationFrameTime(thumbnailAnimation, currentTime);
243        thumbnailAnimation.getTransformation(animationFrameTime, thumbnailTransformation);
244        thumbnailTransformation.getMatrix().preTranslate(thumbnailX, thumbnailY);
245
246        ScreenRotationAnimation screenRotationAnimation =
247                mAnimator.getScreenRotationAnimationLocked(Display.DEFAULT_DISPLAY);
248        final boolean screenAnimation = screenRotationAnimation != null
249                && screenRotationAnimation.isAnimating();
250        if (screenAnimation) {
251            thumbnailTransformation.postCompose(screenRotationAnimation.getEnterTransformation());
252        }
253        // cache often used attributes locally
254        final float tmpFloats[] = mService.mTmpFloats;
255        thumbnailTransformation.getMatrix().getValues(tmpFloats);
256        if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(thumbnail,
257                "thumbnail", "POS " + tmpFloats[Matrix.MTRANS_X]
258                + ", " + tmpFloats[Matrix.MTRANS_Y]);
259        thumbnail.setPosition(tmpFloats[Matrix.MTRANS_X], tmpFloats[Matrix.MTRANS_Y]);
260        if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(thumbnail,
261                "thumbnail", "alpha=" + thumbnailTransformation.getAlpha()
262                + " layer=" + thumbnailLayer
263                + " matrix=[" + tmpFloats[Matrix.MSCALE_X]
264                + "," + tmpFloats[Matrix.MSKEW_Y]
265                + "][" + tmpFloats[Matrix.MSKEW_X]
266                + "," + tmpFloats[Matrix.MSCALE_Y] + "]");
267        thumbnail.setAlpha(thumbnailTransformation.getAlpha());
268        if (thumbnailForceAboveLayer > 0) {
269            thumbnail.setLayer(thumbnailForceAboveLayer + 1);
270        } else {
271            // The thumbnail is layered below the window immediately above this
272            // token's anim layer.
273            thumbnail.setLayer(thumbnailLayer + WindowManagerService.WINDOW_LAYER_MULTIPLIER
274                    - WindowManagerService.LAYER_OFFSET_THUMBNAIL);
275        }
276        thumbnail.setMatrix(tmpFloats[Matrix.MSCALE_X], tmpFloats[Matrix.MSKEW_Y],
277                tmpFloats[Matrix.MSKEW_X], tmpFloats[Matrix.MSCALE_Y]);
278    }
279
280    /**
281     * Sometimes we need to synchronize the first frame of animation with some external event, e.g.
282     * Recents hiding some of its content. To achieve this, we prolong the start of the animaiton
283     * and keep producing the first frame of the animation.
284     */
285    private long getAnimationFrameTime(Animation animation, long currentTime) {
286        if (mProlongAnimation == PROLONG_ANIMATION_AT_START) {
287            animation.setStartTime(currentTime);
288            return currentTime + 1;
289        }
290        return currentTime;
291    }
292
293    private boolean stepAnimation(long currentTime) {
294        if (animation == null) {
295            return false;
296        }
297        transformation.clear();
298        final long animationFrameTime = getAnimationFrameTime(animation, currentTime);
299        boolean hasMoreFrames = animation.getTransformation(animationFrameTime, transformation);
300        if (!hasMoreFrames) {
301            if (deferThumbnailDestruction && !deferFinalFrameCleanup) {
302                // We are deferring the thumbnail destruction, so extend the animation for one more
303                // (dummy) frame before we clean up
304                deferFinalFrameCleanup = true;
305                hasMoreFrames = true;
306            } else {
307                if (false && DEBUG_ANIM) Slog.v(TAG,
308                        "Stepped animation in " + mAppToken + ": more=" + hasMoreFrames +
309                        ", xform=" + transformation + ", mProlongAnimation=" + mProlongAnimation);
310                deferFinalFrameCleanup = false;
311                if (mProlongAnimation == PROLONG_ANIMATION_AT_END) {
312                    hasMoreFrames = true;
313                } else {
314                    animation = null;
315                    clearThumbnail();
316                    if (DEBUG_ANIM) Slog.v(TAG, "Finished animation in " + mAppToken + " @ "
317                            + currentTime);
318                }
319            }
320        }
321        hasTransformation = hasMoreFrames;
322        return hasMoreFrames;
323    }
324
325    private long getStartTimeCorrection() {
326        if (mSkipFirstFrame) {
327
328            // If the transition is an animation in which the first frame doesn't change the screen
329            // contents at all, we can just skip it and start at the second frame. So we shift the
330            // start time of the animation forward by minus the frame duration.
331            return -Choreographer.getInstance().getFrameIntervalNanos() / TimeUtils.NANOS_PER_MS;
332        } else {
333            return 0;
334        }
335    }
336
337    // This must be called while inside a transaction.
338    boolean stepAnimationLocked(long currentTime, final int displayId) {
339        if (mService.okToDisplay()) {
340            // We will run animations as long as the display isn't frozen.
341
342            if (animation == sDummyAnimation) {
343                // This guy is going to animate, but not yet.  For now count
344                // it as not animating for purposes of scheduling transactions;
345                // when it is really time to animate, this will be set to
346                // a real animation and the next call will execute normally.
347                return false;
348            }
349
350            if ((mAppToken.allDrawn || animating || mAppToken.startingDisplayed)
351                    && animation != null) {
352                if (!animating) {
353                    if (DEBUG_ANIM) Slog.v(TAG,
354                        "Starting animation in " + mAppToken +
355                        " @ " + currentTime + " scale="
356                        + mService.getTransitionAnimationScaleLocked()
357                        + " allDrawn=" + mAppToken.allDrawn + " animating=" + animating);
358                    long correction = getStartTimeCorrection();
359                    animation.setStartTime(currentTime + correction);
360                    animating = true;
361                    if (thumbnail != null) {
362                        thumbnail.show();
363                        thumbnailAnimation.setStartTime(currentTime + correction);
364                    }
365                    mSkipFirstFrame = false;
366                }
367                if (stepAnimation(currentTime)) {
368                    // animation isn't over, step any thumbnail and that's
369                    // it for now.
370                    if (thumbnail != null) {
371                        stepThumbnailAnimation(currentTime);
372                    }
373                    return true;
374                }
375            }
376        } else if (animation != null) {
377            // If the display is frozen, and there is a pending animation,
378            // clear it and make sure we run the cleanup code.
379            animating = true;
380            animation = null;
381        }
382
383        hasTransformation = false;
384
385        if (!animating && animation == null) {
386            return false;
387        }
388
389        mAnimator.setAppLayoutChanges(this, WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM,
390                "AppWindowToken", displayId);
391
392        clearAnimation();
393        animating = false;
394        if (animLayerAdjustment != 0) {
395            animLayerAdjustment = 0;
396            updateLayers();
397        }
398        if (mService.mInputMethodTarget != null
399                && mService.mInputMethodTarget.mAppToken == mAppToken) {
400            mService.moveInputMethodWindowsIfNeededLocked(true);
401        }
402
403        if (DEBUG_ANIM) Slog.v(TAG,
404                "Animation done in " + mAppToken
405                + ": reportedVisible=" + mAppToken.reportedVisible);
406
407        transformation.clear();
408
409        final int numAllAppWinAnimators = mAllAppWinAnimators.size();
410        for (int i = 0; i < numAllAppWinAnimators; i++) {
411            mAllAppWinAnimators.get(i).finishExit();
412        }
413        mService.mAppTransition.notifyAppTransitionFinishedLocked(mAppToken.token);
414        return false;
415    }
416
417    // This must be called while inside a transaction.
418    boolean showAllWindowsLocked() {
419        boolean isAnimating = false;
420        final int NW = mAllAppWinAnimators.size();
421        for (int i=0; i<NW; i++) {
422            WindowStateAnimator winAnimator = mAllAppWinAnimators.get(i);
423            if (DEBUG_VISIBILITY) Slog.v(TAG, "performing show on: " + winAnimator);
424            winAnimator.performShowLocked();
425            isAnimating |= winAnimator.isAnimating();
426        }
427        return isAnimating;
428    }
429
430    void dump(PrintWriter pw, String prefix, boolean dumpAll) {
431        pw.print(prefix); pw.print("mAppToken="); pw.println(mAppToken);
432        pw.print(prefix); pw.print("mAnimator="); pw.println(mAnimator);
433        pw.print(prefix); pw.print("freezingScreen="); pw.print(freezingScreen);
434                pw.print(" allDrawn="); pw.print(allDrawn);
435                pw.print(" animLayerAdjustment="); pw.println(animLayerAdjustment);
436        if (lastFreezeDuration != 0) {
437            pw.print(prefix); pw.print("lastFreezeDuration=");
438                    TimeUtils.formatDuration(lastFreezeDuration, pw); pw.println();
439        }
440        if (animating || animation != null) {
441            pw.print(prefix); pw.print("animating="); pw.println(animating);
442            pw.print(prefix); pw.print("animation="); pw.println(animation);
443        }
444        if (hasTransformation) {
445            pw.print(prefix); pw.print("XForm: ");
446                    transformation.printShortString(pw);
447                    pw.println();
448        }
449        if (thumbnail != null) {
450            pw.print(prefix); pw.print("thumbnail="); pw.print(thumbnail);
451                    pw.print(" x="); pw.print(thumbnailX);
452                    pw.print(" y="); pw.print(thumbnailY);
453                    pw.print(" layer="); pw.println(thumbnailLayer);
454            pw.print(prefix); pw.print("thumbnailAnimation="); pw.println(thumbnailAnimation);
455            pw.print(prefix); pw.print("thumbnailTransformation=");
456                    pw.println(thumbnailTransformation.toShortString());
457        }
458        for (int i=0; i<mAllAppWinAnimators.size(); i++) {
459            WindowStateAnimator wanim = mAllAppWinAnimators.get(i);
460            pw.print(prefix); pw.print("App Win Anim #"); pw.print(i);
461                    pw.print(": "); pw.println(wanim);
462        }
463    }
464
465    void startProlongAnimation(int prolongType) {
466        mProlongAnimation = prolongType;
467        mClearProlongedAnimation = false;
468    }
469
470    void endProlongedAnimation() {
471        mProlongAnimation = PROLONG_ANIMATION_DISABLED;
472    }
473
474    // This is an animation that does nothing: it just immediately finishes
475    // itself every time it is called.  It is used as a stub animation in cases
476    // where we want to synchronize multiple things that may be animating.
477    static final class DummyAnimation extends Animation {
478        @Override
479        public boolean getTransformation(long currentTime, Transformation outTransformation) {
480            return false;
481        }
482    }
483
484}
485