WindowSurfacePlacer.java revision d75962eb8377e0d5e500e4cf36f2abce9bbadfcc
1package com.android.server.wm;
2
3import static android.app.ActivityManagerInternal.APP_TRANSITION_SAVED_SURFACE;
4import static android.app.ActivityManagerInternal.APP_TRANSITION_STARTING_WINDOW;
5import static android.app.ActivityManagerInternal.APP_TRANSITION_TIMEOUT;
6import static android.app.ActivityManagerInternal.APP_TRANSITION_WINDOWS_DRAWN;
7import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
8import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER;
9import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_KEYGUARD;
10import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_NO_MOVE_ANIMATION;
11import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_SUSTAINED_PERFORMANCE_MODE;
12import static android.view.WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
13import static android.view.WindowManager.LayoutParams.TYPE_DREAM;
14import static android.view.WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG;
15import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG;
16import static android.view.WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
17import static android.view.WindowManager.LayoutParams.TYPE_WALLPAPER;
18import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_ANIM;
19import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_CONFIG;
20import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_LAYOUT;
21import static android.view.WindowManagerPolicy.FINISH_LAYOUT_REDO_WALLPAPER;
22import static com.android.server.wm.WindowManagerDebugConfig.DEBUG;
23import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ADD_REMOVE;
24import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_APP_TRANSITIONS;
25import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT;
26import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_LAYOUT_REPEATS;
27import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_ORIENTATION;
28import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_POWER;
29import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STARTING_WINDOW;
30import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_TOKEN_MOVEMENT;
31import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_VISIBILITY;
32import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
33import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WINDOW_TRACE;
34import static com.android.server.wm.WindowManagerDebugConfig.SHOW_LIGHT_TRANSACTIONS;
35import static com.android.server.wm.WindowManagerDebugConfig.SHOW_TRANSACTIONS;
36import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
37import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
38import static com.android.server.wm.WindowManagerService.H.DO_TRAVERSAL;
39import static com.android.server.wm.WindowManagerService.H.NOTIFY_ACTIVITY_DRAWN;
40import static com.android.server.wm.WindowManagerService.H.NOTIFY_APP_TRANSITION_STARTING;
41import static com.android.server.wm.WindowManagerService.H.NOTIFY_STARTING_WINDOW_DRAWN;
42import static com.android.server.wm.WindowManagerService.H.REPORT_LOSING_FOCUS;
43import static com.android.server.wm.WindowManagerService.H.REPORT_WINDOWS_CHANGE;
44import static com.android.server.wm.WindowManagerService.H.SEND_NEW_CONFIGURATION;
45import static com.android.server.wm.WindowManagerService.H.UPDATE_DOCKED_STACK_DIVIDER;
46import static com.android.server.wm.WindowManagerService.H.WINDOW_FREEZE_TIMEOUT;
47import static com.android.server.wm.WindowManagerService.LAYOUT_REPEAT_THRESHOLD;
48import static com.android.server.wm.WindowManagerService.MAX_ANIMATION_DURATION;
49import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES;
50import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_WILL_PLACE_SURFACES;
51import static com.android.server.wm.WindowManagerService.WINDOWS_FREEZING_SCREENS_NONE;
52
53import android.graphics.Bitmap;
54import android.graphics.Canvas;
55import android.graphics.PixelFormat;
56import android.graphics.Rect;
57import android.os.Debug;
58import android.os.PowerManager;
59import android.os.RemoteException;
60import android.os.SystemClock;
61import android.os.Trace;
62import android.provider.Settings;
63import android.util.ArraySet;
64import android.util.Slog;
65import android.view.Display;
66import android.view.DisplayInfo;
67import android.view.Surface;
68import android.view.SurfaceControl;
69import android.view.View;
70import android.view.WindowManager.LayoutParams;
71import android.view.animation.Animation;
72
73import com.android.server.wm.WindowManagerService.H;
74
75import java.io.PrintWriter;
76import java.util.ArrayList;
77
78/**
79 * Positions windows and their surfaces.
80 *
81 * It sets positions of windows by calculating their frames and then applies this by positioning
82 * surfaces according to these frames. Z layer is still assigned withing WindowManagerService.
83 */
84class WindowSurfacePlacer {
85    private static final String TAG = TAG_WITH_CLASS_NAME ? "WindowSurfacePlacer" : TAG_WM;
86    private final WindowManagerService mService;
87    private final WallpaperController mWallpaperControllerLocked;
88
89    private boolean mInLayout = false;
90
91    /** Only do a maximum of 6 repeated layouts. After that quit */
92    private int mLayoutRepeatCount;
93
94    static final int SET_UPDATE_ROTATION                = 1 << 0;
95    static final int SET_WALLPAPER_MAY_CHANGE           = 1 << 1;
96    static final int SET_FORCE_HIDING_CHANGED           = 1 << 2;
97    static final int SET_ORIENTATION_CHANGE_COMPLETE    = 1 << 3;
98    static final int SET_TURN_ON_SCREEN                 = 1 << 4;
99    static final int SET_WALLPAPER_ACTION_PENDING       = 1 << 5;
100
101    boolean mWallpaperMayChange = false;
102    boolean mOrientationChangeComplete = true;
103    boolean mWallpaperActionPending = false;
104
105    private boolean mWallpaperForceHidingChanged = false;
106    private Object mLastWindowFreezeSource = null;
107    private Session mHoldScreen = null;
108    private boolean mObscured = false;
109    private boolean mSyswin = false;
110    private float mScreenBrightness = -1;
111    private float mButtonBrightness = -1;
112    private long mUserActivityTimeout = -1;
113    private boolean mUpdateRotation = false;
114    private final Rect mTmpStartRect = new Rect();
115    private final Rect mTmpContentRect = new Rect();
116
117    // Set to true when the display contains content to show the user.
118    // When false, the display manager may choose to mirror or blank the display.
119    private boolean mDisplayHasContent = false;
120
121    // Only set while traversing the default display based on its content.
122    // Affects the behavior of mirroring on secondary displays.
123    private boolean mObscureApplicationContentOnSecondaryDisplays = false;
124
125    private float mPreferredRefreshRate = 0;
126
127    private int mPreferredModeId = 0;
128
129    private boolean mTraversalScheduled;
130    private int mDeferDepth = 0;
131
132    private boolean mSustainedPerformanceModeEnabled = false;
133    private boolean mSustainedPerformanceModeCurrent = false;
134
135    private static final class LayerAndToken {
136        public int layer;
137        public AppWindowToken token;
138    }
139    private final LayerAndToken mTmpLayerAndToken = new LayerAndToken();
140
141    private final ArrayList<SurfaceControl> mPendingDestroyingSurfaces = new ArrayList<>();
142
143    public WindowSurfacePlacer(WindowManagerService service) {
144        mService = service;
145        mWallpaperControllerLocked = mService.mWallpaperControllerLocked;
146    }
147
148    /**
149     * See {@link WindowManagerService#deferSurfaceLayout()}
150     */
151    void deferLayout() {
152        mDeferDepth++;
153    }
154
155    /**
156     * See {@link WindowManagerService#continueSurfaceLayout()}
157     */
158    void continueLayout() {
159        mDeferDepth--;
160        if (mDeferDepth <= 0) {
161            performSurfacePlacement();
162        }
163    }
164
165    final void performSurfacePlacement() {
166        if (mDeferDepth > 0) {
167            return;
168        }
169        int loopCount = 6;
170        do {
171            mTraversalScheduled = false;
172            performSurfacePlacementLoop();
173            mService.mH.removeMessages(DO_TRAVERSAL);
174            loopCount--;
175        } while (mTraversalScheduled && loopCount > 0);
176        mWallpaperActionPending = false;
177    }
178
179    private void performSurfacePlacementLoop() {
180        if (mInLayout) {
181            if (DEBUG) {
182                throw new RuntimeException("Recursive call!");
183            }
184            Slog.w(TAG, "performLayoutAndPlaceSurfacesLocked called while in layout. Callers="
185                    + Debug.getCallers(3));
186            return;
187        }
188
189        if (mService.mWaitingForConfig) {
190            // Our configuration has changed (most likely rotation), but we
191            // don't yet have the complete configuration to report to
192            // applications.  Don't do any window layout until we have it.
193            return;
194        }
195
196        if (!mService.mDisplayReady) {
197            // Not yet initialized, nothing to do.
198            return;
199        }
200
201        Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "wmLayout");
202        mInLayout = true;
203
204        boolean recoveringMemory = false;
205        if (!mService.mForceRemoves.isEmpty()) {
206            recoveringMemory = true;
207            // Wait a little bit for things to settle down, and off we go.
208            while (!mService.mForceRemoves.isEmpty()) {
209                WindowState ws = mService.mForceRemoves.remove(0);
210                Slog.i(TAG, "Force removing: " + ws);
211                mService.removeWindowInnerLocked(ws);
212            }
213            Slog.w(TAG, "Due to memory failure, waiting a bit for next layout");
214            Object tmp = new Object();
215            synchronized (tmp) {
216                try {
217                    tmp.wait(250);
218                } catch (InterruptedException e) {
219                }
220            }
221        }
222
223        try {
224            performSurfacePlacementInner(recoveringMemory);
225
226            mInLayout = false;
227
228            if (mService.needsLayout()) {
229                if (++mLayoutRepeatCount < 6) {
230                    requestTraversal();
231                } else {
232                    Slog.e(TAG, "Performed 6 layouts in a row. Skipping");
233                    mLayoutRepeatCount = 0;
234                }
235            } else {
236                mLayoutRepeatCount = 0;
237            }
238
239            if (mService.mWindowsChanged && !mService.mWindowChangeListeners.isEmpty()) {
240                mService.mH.removeMessages(REPORT_WINDOWS_CHANGE);
241                mService.mH.sendEmptyMessage(REPORT_WINDOWS_CHANGE);
242            }
243        } catch (RuntimeException e) {
244            mInLayout = false;
245            Slog.wtf(TAG, "Unhandled exception while laying out windows", e);
246        }
247
248        Trace.traceEnd(Trace.TRACE_TAG_WINDOW_MANAGER);
249    }
250
251    void debugLayoutRepeats(final String msg, int pendingLayoutChanges) {
252        if (mLayoutRepeatCount >= LAYOUT_REPEAT_THRESHOLD) {
253            Slog.v(TAG, "Layouts looping: " + msg +
254                    ", mPendingLayoutChanges = 0x" + Integer.toHexString(pendingLayoutChanges));
255        }
256    }
257
258    // "Something has changed!  Let's make it correct now."
259    private void performSurfacePlacementInner(boolean recoveringMemory) {
260        if (DEBUG_WINDOW_TRACE) Slog.v(TAG, "performSurfacePlacementInner: entry. Called by "
261                + Debug.getCallers(3));
262
263        int i;
264        boolean updateInputWindowsNeeded = false;
265
266        if (mService.mFocusMayChange) {
267            mService.mFocusMayChange = false;
268            updateInputWindowsNeeded = mService.updateFocusedWindowLocked(
269                    UPDATE_FOCUS_WILL_PLACE_SURFACES, false /*updateInputWindows*/);
270        }
271
272        // Initialize state of exiting tokens.
273        final int numDisplays = mService.mDisplayContents.size();
274        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
275            final DisplayContent displayContent = mService.mDisplayContents.valueAt(displayNdx);
276            for (i=displayContent.mExitingTokens.size()-1; i>=0; i--) {
277                displayContent.mExitingTokens.get(i).hasVisible = false;
278            }
279        }
280
281        for (int stackNdx = mService.mStackIdToStack.size() - 1; stackNdx >= 0; --stackNdx) {
282            // Initialize state of exiting applications.
283            final AppTokenList exitingAppTokens =
284                    mService.mStackIdToStack.valueAt(stackNdx).mExitingAppTokens;
285            for (int tokenNdx = exitingAppTokens.size() - 1; tokenNdx >= 0; --tokenNdx) {
286                exitingAppTokens.get(tokenNdx).hasVisible = false;
287            }
288        }
289
290        mHoldScreen = null;
291        mScreenBrightness = -1;
292        mButtonBrightness = -1;
293        mUserActivityTimeout = -1;
294        mObscureApplicationContentOnSecondaryDisplays = false;
295        mSustainedPerformanceModeCurrent = false;
296        mService.mTransactionSequence++;
297
298        final DisplayContent defaultDisplay = mService.getDefaultDisplayContentLocked();
299        final DisplayInfo defaultInfo = defaultDisplay.getDisplayInfo();
300        final int defaultDw = defaultInfo.logicalWidth;
301        final int defaultDh = defaultInfo.logicalHeight;
302
303        if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
304                ">>> OPEN TRANSACTION performLayoutAndPlaceSurfaces");
305        SurfaceControl.openTransaction();
306        try {
307            applySurfaceChangesTransaction(recoveringMemory, numDisplays, defaultDw, defaultDh);
308        } catch (RuntimeException e) {
309            Slog.wtf(TAG, "Unhandled exception in Window Manager", e);
310        } finally {
311            SurfaceControl.closeTransaction();
312            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
313                    "<<< CLOSE TRANSACTION performLayoutAndPlaceSurfaces");
314        }
315
316        final WindowList defaultWindows = defaultDisplay.getWindowList();
317
318        // If we are ready to perform an app transition, check through
319        // all of the app tokens to be shown and see if they are ready
320        // to go.
321        if (mService.mAppTransition.isReady()) {
322            defaultDisplay.pendingLayoutChanges |= handleAppTransitionReadyLocked(defaultWindows);
323            if (DEBUG_LAYOUT_REPEATS)
324                debugLayoutRepeats("after handleAppTransitionReadyLocked",
325                        defaultDisplay.pendingLayoutChanges);
326        }
327
328        if (!mService.mAnimator.mAppWindowAnimating && mService.mAppTransition.isRunning()) {
329            // We have finished the animation of an app transition.  To do
330            // this, we have delayed a lot of operations like showing and
331            // hiding apps, moving apps in Z-order, etc.  The app token list
332            // reflects the correct Z-order, but the window list may now
333            // be out of sync with it.  So here we will just rebuild the
334            // entire app window list.  Fun!
335            defaultDisplay.pendingLayoutChanges |=
336                    mService.handleAnimatingStoppedAndTransitionLocked();
337            if (DEBUG_LAYOUT_REPEATS)
338                debugLayoutRepeats("after handleAnimStopAndXitionLock",
339                        defaultDisplay.pendingLayoutChanges);
340        }
341
342        if (mWallpaperForceHidingChanged && defaultDisplay.pendingLayoutChanges == 0
343                && !mService.mAppTransition.isReady()) {
344            // At this point, there was a window with a wallpaper that
345            // was force hiding other windows behind it, but now it
346            // is going away.  This may be simple -- just animate
347            // away the wallpaper and its window -- or it may be
348            // hard -- the wallpaper now needs to be shown behind
349            // something that was hidden.
350            defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_LAYOUT;
351            if (DEBUG_LAYOUT_REPEATS)
352                debugLayoutRepeats("after animateAwayWallpaperLocked",
353                        defaultDisplay.pendingLayoutChanges);
354        }
355        mWallpaperForceHidingChanged = false;
356
357        if (mWallpaperMayChange) {
358            if (DEBUG_WALLPAPER_LIGHT)
359                Slog.v(TAG, "Wallpaper may change!  Adjusting");
360            defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
361            if (DEBUG_LAYOUT_REPEATS) debugLayoutRepeats("WallpaperMayChange",
362                    defaultDisplay.pendingLayoutChanges);
363        }
364
365        if (mService.mFocusMayChange) {
366            mService.mFocusMayChange = false;
367            if (mService.updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES,
368                    false /*updateInputWindows*/)) {
369                updateInputWindowsNeeded = true;
370                defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_ANIM;
371            }
372        }
373
374        if (mService.needsLayout()) {
375            defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_LAYOUT;
376            if (DEBUG_LAYOUT_REPEATS) debugLayoutRepeats("mLayoutNeeded",
377                    defaultDisplay.pendingLayoutChanges);
378        }
379
380        for (i = mService.mResizingWindows.size() - 1; i >= 0; i--) {
381            WindowState win = mService.mResizingWindows.get(i);
382            if (win.mAppFreezing) {
383                // Don't remove this window until rotation has completed.
384                continue;
385            }
386            // Discard the saved surface if window size is changed, it can't be reused.
387            if (win.mAppToken != null) {
388                win.mAppToken.destroySavedSurfaces();
389            }
390            win.reportResized();
391            mService.mResizingWindows.remove(i);
392        }
393
394        if (DEBUG_ORIENTATION && mService.mDisplayFrozen) Slog.v(TAG,
395                "With display frozen, orientationChangeComplete=" + mOrientationChangeComplete);
396        if (mOrientationChangeComplete) {
397            if (mService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_NONE) {
398                mService.mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_NONE;
399                mService.mLastFinishedFreezeSource = mLastWindowFreezeSource;
400                mService.mH.removeMessages(WINDOW_FREEZE_TIMEOUT);
401            }
402            mService.stopFreezingDisplayLocked();
403        }
404
405        // Destroy the surface of any windows that are no longer visible.
406        boolean wallpaperDestroyed = false;
407        i = mService.mDestroySurface.size();
408        if (i > 0) {
409            do {
410                i--;
411                WindowState win = mService.mDestroySurface.get(i);
412                win.mDestroying = false;
413                if (mService.mInputMethodWindow == win) {
414                    mService.mInputMethodWindow = null;
415                }
416                if (mWallpaperControllerLocked.isWallpaperTarget(win)) {
417                    wallpaperDestroyed = true;
418                }
419                win.destroyOrSaveSurface();
420            } while (i > 0);
421            mService.mDestroySurface.clear();
422        }
423
424        // Time to remove any exiting tokens?
425        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
426            final DisplayContent displayContent = mService.mDisplayContents.valueAt(displayNdx);
427            ArrayList<WindowToken> exitingTokens = displayContent.mExitingTokens;
428            for (i = exitingTokens.size() - 1; i >= 0; i--) {
429                WindowToken token = exitingTokens.get(i);
430                if (!token.hasVisible) {
431                    exitingTokens.remove(i);
432                    if (token.windowType == TYPE_WALLPAPER) {
433                        mWallpaperControllerLocked.removeWallpaperToken(token);
434                    }
435                }
436            }
437        }
438
439        // Time to remove any exiting applications?
440        for (int stackNdx = mService.mStackIdToStack.size() - 1; stackNdx >= 0; --stackNdx) {
441            // Initialize state of exiting applications.
442            final AppTokenList exitingAppTokens =
443                    mService.mStackIdToStack.valueAt(stackNdx).mExitingAppTokens;
444            for (i = exitingAppTokens.size() - 1; i >= 0; i--) {
445                AppWindowToken token = exitingAppTokens.get(i);
446                if (!token.hasVisible && !mService.mClosingApps.contains(token) &&
447                        (!token.mIsExiting || token.allAppWindows.isEmpty())) {
448                    // Make sure there is no animation running on this token,
449                    // so any windows associated with it will be removed as
450                    // soon as their animations are complete
451                    token.mAppAnimator.clearAnimation();
452                    token.mAppAnimator.animating = false;
453                    if (DEBUG_ADD_REMOVE || DEBUG_TOKEN_MOVEMENT) Slog.v(TAG,
454                            "performLayout: App token exiting now removed" + token);
455                    token.removeAppFromTaskLocked();
456                }
457            }
458        }
459
460        if (wallpaperDestroyed) {
461            defaultDisplay.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
462            defaultDisplay.layoutNeeded = true;
463        }
464
465        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
466            final DisplayContent displayContent = mService.mDisplayContents.valueAt(displayNdx);
467            if (displayContent.pendingLayoutChanges != 0) {
468                displayContent.layoutNeeded = true;
469            }
470        }
471
472        // Finally update all input windows now that the window changes have stabilized.
473        mService.mInputMonitor.updateInputWindowsLw(true /*force*/);
474
475        mService.setHoldScreenLocked(mHoldScreen);
476        if (!mService.mDisplayFrozen) {
477            if (mScreenBrightness < 0 || mScreenBrightness > 1.0f) {
478                mService.mPowerManagerInternal.setScreenBrightnessOverrideFromWindowManager(-1);
479            } else {
480                mService.mPowerManagerInternal.setScreenBrightnessOverrideFromWindowManager(
481                        toBrightnessOverride(mScreenBrightness));
482            }
483            if (mButtonBrightness < 0
484                    || mButtonBrightness > 1.0f) {
485                mService.mPowerManagerInternal.setButtonBrightnessOverrideFromWindowManager(-1);
486            } else {
487                mService.mPowerManagerInternal.setButtonBrightnessOverrideFromWindowManager(
488                        toBrightnessOverride(mButtonBrightness));
489            }
490            mService.mPowerManagerInternal.setUserActivityTimeoutOverrideFromWindowManager(
491                    mUserActivityTimeout);
492        }
493
494        if (mSustainedPerformanceModeCurrent != mSustainedPerformanceModeEnabled) {
495            mSustainedPerformanceModeEnabled = mSustainedPerformanceModeCurrent;
496            mService.mPowerManagerInternal.powerHint(
497                    mService.mPowerManagerInternal.POWER_HINT_SUSTAINED_PERFORMANCE_MODE,
498                    (mSustainedPerformanceModeEnabled ? 1 : 0));
499        }
500
501        if (mService.mTurnOnScreen) {
502            if (mService.mAllowTheaterModeWakeFromLayout
503                    || Settings.Global.getInt(mService.mContext.getContentResolver(),
504                        Settings.Global.THEATER_MODE_ON, 0) == 0) {
505                if (DEBUG_VISIBILITY || DEBUG_POWER) {
506                    Slog.v(TAG, "Turning screen on after layout!");
507                }
508                mService.mPowerManager.wakeUp(SystemClock.uptimeMillis(),
509                        "android.server.wm:TURN_ON");
510            }
511            mService.mTurnOnScreen = false;
512        }
513
514        if (mUpdateRotation) {
515            if (DEBUG_ORIENTATION) Slog.d(TAG, "Performing post-rotate rotation");
516            if (mService.updateRotationUncheckedLocked(false)) {
517                mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
518            } else {
519                mUpdateRotation = false;
520            }
521        }
522
523        if (mService.mWaitingForDrawnCallback != null ||
524                (mOrientationChangeComplete && !defaultDisplay.layoutNeeded &&
525                        !mUpdateRotation)) {
526            mService.checkDrawnWindowsLocked();
527        }
528
529        final int N = mService.mPendingRemove.size();
530        if (N > 0) {
531            if (mService.mPendingRemoveTmp.length < N) {
532                mService.mPendingRemoveTmp = new WindowState[N+10];
533            }
534            mService.mPendingRemove.toArray(mService.mPendingRemoveTmp);
535            mService.mPendingRemove.clear();
536            DisplayContentList displayList = new DisplayContentList();
537            for (i = 0; i < N; i++) {
538                WindowState w = mService.mPendingRemoveTmp[i];
539                mService.removeWindowInnerLocked(w);
540                final DisplayContent displayContent = w.getDisplayContent();
541                if (displayContent != null && !displayList.contains(displayContent)) {
542                    displayList.add(displayContent);
543                }
544            }
545
546            for (DisplayContent displayContent : displayList) {
547                mService.mLayersController.assignLayersLocked(displayContent.getWindowList());
548                displayContent.layoutNeeded = true;
549            }
550        }
551
552        // Remove all deferred displays stacks, tasks, and activities.
553        for (int displayNdx = mService.mDisplayContents.size() - 1; displayNdx >= 0; --displayNdx) {
554            mService.mDisplayContents.valueAt(displayNdx).checkForDeferredActions();
555        }
556
557        if (updateInputWindowsNeeded) {
558            mService.mInputMonitor.updateInputWindowsLw(false /*force*/);
559        }
560        mService.setFocusTaskRegionLocked();
561
562        // Check to see if we are now in a state where the screen should
563        // be enabled, because the window obscured flags have changed.
564        mService.enableScreenIfNeededLocked();
565
566        mService.scheduleAnimationLocked();
567        mService.mWindowPlacerLocked.destroyPendingSurfaces();
568
569        if (DEBUG_WINDOW_TRACE) Slog.e(TAG,
570                "performSurfacePlacementInner exit: animating=" + mService.mAnimator.isAnimating());
571    }
572
573    private void applySurfaceChangesTransaction(boolean recoveringMemory, int numDisplays,
574            int defaultDw, int defaultDh) {
575        if (mService.mWatermark != null) {
576            mService.mWatermark.positionSurface(defaultDw, defaultDh);
577        }
578        if (mService.mStrictModeFlash != null) {
579            mService.mStrictModeFlash.positionSurface(defaultDw, defaultDh);
580        }
581        if (mService.mCircularDisplayMask != null) {
582            mService.mCircularDisplayMask.positionSurface(defaultDw, defaultDh,
583                    mService.mRotation);
584        }
585        if (mService.mEmulatorDisplayOverlay != null) {
586            mService.mEmulatorDisplayOverlay.positionSurface(defaultDw, defaultDh,
587                    mService.mRotation);
588        }
589
590        boolean focusDisplayed = false;
591
592        for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
593            final DisplayContent displayContent = mService.mDisplayContents.valueAt(displayNdx);
594            boolean updateAllDrawn = false;
595            WindowList windows = displayContent.getWindowList();
596            DisplayInfo displayInfo = displayContent.getDisplayInfo();
597            final int displayId = displayContent.getDisplayId();
598            final int dw = displayInfo.logicalWidth;
599            final int dh = displayInfo.logicalHeight;
600            final int innerDw = displayInfo.appWidth;
601            final int innerDh = displayInfo.appHeight;
602            final boolean isDefaultDisplay = (displayId == Display.DEFAULT_DISPLAY);
603
604            // Reset for each display.
605            mDisplayHasContent = false;
606            mPreferredRefreshRate = 0;
607            mPreferredModeId = 0;
608
609            int repeats = 0;
610            do {
611                repeats++;
612                if (repeats > 6) {
613                    Slog.w(TAG, "Animation repeat aborted after too many iterations");
614                    displayContent.layoutNeeded = false;
615                    break;
616                }
617
618                if (DEBUG_LAYOUT_REPEATS) debugLayoutRepeats(
619                        "On entry to LockedInner", displayContent.pendingLayoutChanges);
620
621                if ((displayContent.pendingLayoutChanges & FINISH_LAYOUT_REDO_WALLPAPER) != 0 &&
622                        mWallpaperControllerLocked.adjustWallpaperWindows()) {
623                    mService.mLayersController.assignLayersLocked(windows);
624                    displayContent.layoutNeeded = true;
625                }
626
627                if (isDefaultDisplay
628                        && (displayContent.pendingLayoutChanges & FINISH_LAYOUT_REDO_CONFIG) != 0) {
629                    if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
630                    if (mService.updateOrientationFromAppTokensLocked(true)) {
631                        displayContent.layoutNeeded = true;
632                        mService.mH.sendEmptyMessage(SEND_NEW_CONFIGURATION);
633                    }
634                }
635
636                if ((displayContent.pendingLayoutChanges & FINISH_LAYOUT_REDO_LAYOUT) != 0) {
637                    displayContent.layoutNeeded = true;
638                }
639
640                // FIRST LOOP: Perform a layout, if needed.
641                if (repeats < LAYOUT_REPEAT_THRESHOLD) {
642                    performLayoutLockedInner(displayContent, repeats == 1,
643                            false /* updateInputWindows */);
644                } else {
645                    Slog.w(TAG, "Layout repeat skipped after too many iterations");
646                }
647
648                // FIRST AND ONE HALF LOOP: Make WindowManagerPolicy think
649                // it is animating.
650                displayContent.pendingLayoutChanges = 0;
651
652                if (isDefaultDisplay) {
653                    mService.mPolicy.beginPostLayoutPolicyLw(dw, dh);
654                    for (int i = windows.size() - 1; i >= 0; i--) {
655                        WindowState w = windows.get(i);
656                        if (w.mHasSurface) {
657                            mService.mPolicy.applyPostLayoutPolicyLw(w, w.mAttrs,
658                                    w.mAttachedWindow);
659                        }
660                    }
661                    displayContent.pendingLayoutChanges |=
662                            mService.mPolicy.finishPostLayoutPolicyLw();
663                    if (DEBUG_LAYOUT_REPEATS) debugLayoutRepeats("after finishPostLayoutPolicyLw",
664                            displayContent.pendingLayoutChanges);
665                }
666            } while (displayContent.pendingLayoutChanges != 0);
667
668            mObscured = false;
669            mSyswin = false;
670            displayContent.resetDimming();
671
672            // Only used if default window
673            final boolean someoneLosingFocus = !mService.mLosingFocus.isEmpty();
674
675            for (int i = windows.size() - 1; i >= 0; i--) {
676                WindowState w = windows.get(i);
677                final Task task = w.getTask();
678                final boolean obscuredChanged = w.mObscured != mObscured;
679
680                // Update effect.
681                w.mObscured = mObscured;
682                if (!mObscured) {
683                    handleNotObscuredLocked(w, displayInfo);
684                }
685
686                w.applyDimLayerIfNeeded();
687
688                if (isDefaultDisplay && obscuredChanged
689                        && mWallpaperControllerLocked.isWallpaperTarget(w) && w.isVisibleLw()) {
690                    // This is the wallpaper target and its obscured state
691                    // changed... make sure the current wallaper's visibility
692                    // has been updated accordingly.
693                    mWallpaperControllerLocked.updateWallpaperVisibility();
694                }
695
696                final WindowStateAnimator winAnimator = w.mWinAnimator;
697
698                // If the window has moved due to its containing content frame changing, then
699                // notify the listeners and optionally animate it. Simply checking a change of
700                // position is not enough, because being move due to dock divider is not a trigger
701                // for animation.
702                if (w.hasMoved()) {
703                    // Frame has moved, containing content frame has also moved, and we're not
704                    // currently animating... let's do something.
705                    final int left = w.mFrame.left;
706                    final int top = w.mFrame.top;
707                    final boolean adjustedForMinimizedDockOrIme = task != null
708                                && (task.mStack.isAdjustedForMinimizedDockedStack()
709                                    || task.mStack.isAdjustedForIme());
710                    if ((w.mAttrs.privateFlags & PRIVATE_FLAG_NO_MOVE_ANIMATION) == 0
711                            && !w.isDragResizing() && !adjustedForMinimizedDockOrIme
712                            && (task == null || !w.getTask().mStack.getFreezeMovementAnimations())
713                            && !w.mWinAnimator.mLastHidden) {
714                        winAnimator.setMoveAnimation(left, top);
715                    }
716
717                    //TODO (multidisplay): Accessibility supported only for the default display.
718                    if (mService.mAccessibilityController != null
719                            && displayId == Display.DEFAULT_DISPLAY) {
720                        mService.mAccessibilityController.onSomeWindowResizedOrMovedLocked();
721                    }
722
723                    try {
724                        w.mClient.moved(left, top);
725                    } catch (RemoteException e) {
726                    }
727                    w.mMovedByResize = false;
728                }
729
730                //Slog.i(TAG, "Window " + this + " clearing mContentChanged - done placing");
731                w.mContentChanged = false;
732
733                // Moved from updateWindowsAndWallpaperLocked().
734                if (w.mHasSurface) {
735                    // If we have recently synchronized a previous transaction for this
736                    // window ensure we don't push through an unsynchronized one now.
737                    winAnimator.deferToPendingTransaction();
738
739                    // Take care of the window being ready to display.
740                    final boolean committed = winAnimator.commitFinishDrawingLocked();
741                    if (isDefaultDisplay && committed) {
742                        if (w.mAttrs.type == TYPE_DREAM) {
743                            // HACK: When a dream is shown, it may at that
744                            // point hide the lock screen.  So we need to
745                            // redo the layout to let the phone window manager
746                            // make this happen.
747                            displayContent.pendingLayoutChanges |=
748                                    FINISH_LAYOUT_REDO_LAYOUT;
749                            if (DEBUG_LAYOUT_REPEATS) {
750                                debugLayoutRepeats("dream and commitFinishDrawingLocked true",
751                                        displayContent.pendingLayoutChanges);
752                            }
753                        }
754                        if ((w.mAttrs.flags & FLAG_SHOW_WALLPAPER) != 0) {
755                            if (DEBUG_WALLPAPER_LIGHT)
756                                Slog.v(TAG, "First draw done in potential wallpaper target " + w);
757                            mWallpaperMayChange = true;
758                            displayContent.pendingLayoutChanges |= FINISH_LAYOUT_REDO_WALLPAPER;
759                            if (DEBUG_LAYOUT_REPEATS) {
760                                debugLayoutRepeats("wallpaper and commitFinishDrawingLocked true",
761                                        displayContent.pendingLayoutChanges);
762                            }
763                        }
764                    }
765                    if (!winAnimator.isAnimationStarting()) {
766                        // Updates the shown frame before we set up the surface. This is needed
767                        // because the resizing could change the top-left position (in addition to
768                        // size) of the window. setSurfaceBoundariesLocked uses mShownPosition to
769                        // position the surface.
770                        //
771                        // If an animation is being started, we can't call this method because the
772                        // animation hasn't processed its initial transformation yet, but in general
773                        // we do want to update the position if the window is animating.
774                        winAnimator.computeShownFrameLocked();
775                    }
776                    winAnimator.setSurfaceBoundariesLocked(recoveringMemory);
777                }
778
779                final AppWindowToken atoken = w.mAppToken;
780                if (DEBUG_STARTING_WINDOW && atoken != null && w == atoken.startingWindow) {
781                    Slog.d(TAG, "updateWindows: starting " + w
782                            + " isOnScreen=" + w.isOnScreen() + " allDrawn=" + atoken.allDrawn
783                            + " freezingScreen=" + atoken.mAppAnimator.freezingScreen);
784                }
785                if (atoken != null && (!atoken.allDrawn || atoken.mAppAnimator.freezingScreen)) {
786                    if (atoken.lastTransactionSequence != mService.mTransactionSequence) {
787                        atoken.lastTransactionSequence = mService.mTransactionSequence;
788                        atoken.numInterestingWindows = atoken.numDrawnWindows = 0;
789                        atoken.startingDisplayed = false;
790                    }
791                    if ((w.isOnScreenIgnoringKeyguard()
792                            || winAnimator.mAttrType == TYPE_BASE_APPLICATION)
793                            && !w.mAnimatingExit && !w.mDestroying) {
794                        if (DEBUG_VISIBILITY || DEBUG_ORIENTATION) {
795                            Slog.v(TAG, "Eval win " + w + ": isDrawn="
796                                    + w.isDrawnLw()
797                                    + ", isAnimationSet=" + winAnimator.isAnimationSet());
798                            if (!w.isDrawnLw()) {
799                                Slog.v(TAG, "Not displayed: s="
800                                        + winAnimator.mSurfaceController
801                                        + " pv=" + w.mPolicyVisibility
802                                        + " mDrawState=" + winAnimator.drawStateToString()
803                                        + " ah=" + w.mAttachedHidden
804                                        + " th=" + atoken.hiddenRequested
805                                        + " a=" + winAnimator.mAnimating);
806                            }
807                        }
808                        if (w != atoken.startingWindow) {
809                            if (!w.mAppDied &&
810                                    (!atoken.mAppAnimator.freezingScreen || !w.mAppFreezing)) {
811                                atoken.numInterestingWindows++;
812                                if (w.isDrawnLw()) {
813                                    atoken.numDrawnWindows++;
814                                    if (DEBUG_VISIBILITY || DEBUG_ORIENTATION)
815                                        Slog.v(TAG, "tokenMayBeDrawn: " + atoken
816                                                + " freezingScreen="
817                                                + atoken.mAppAnimator.freezingScreen
818                                                + " mAppFreezing=" + w.mAppFreezing);
819                                    updateAllDrawn = true;
820                                }
821                            }
822                        } else if (w.isDrawnLw()) {
823                            mService.mH.sendEmptyMessage(NOTIFY_STARTING_WINDOW_DRAWN);
824                            atoken.startingDisplayed = true;
825                        }
826                    }
827                }
828
829                if (isDefaultDisplay && someoneLosingFocus && w == mService.mCurrentFocus
830                        && w.isDisplayedLw()) {
831                    focusDisplayed = true;
832                }
833
834                mService.updateResizingWindows(w);
835            }
836
837            mService.mDisplayManagerInternal.setDisplayProperties(displayId,
838                    mDisplayHasContent,
839                    mPreferredRefreshRate,
840                    mPreferredModeId,
841                    true /* inTraversal, must call performTraversalInTrans... below */);
842
843            mService.getDisplayContentLocked(displayId).stopDimmingIfNeeded();
844
845            if (updateAllDrawn) {
846                updateAllDrawnLocked(displayContent);
847            }
848        }
849
850        if (focusDisplayed) {
851            mService.mH.sendEmptyMessage(REPORT_LOSING_FOCUS);
852        }
853
854        // Give the display manager a chance to adjust properties
855        // like display rotation if it needs to.
856        mService.mDisplayManagerInternal.performTraversalInTransactionFromWindowManager();
857    }
858
859    boolean isInLayout() {
860        return mInLayout;
861    }
862
863    final void performLayoutLockedInner(final DisplayContent displayContent,
864            boolean initial, boolean updateInputWindows) {
865        if (!displayContent.layoutNeeded) {
866            return;
867        }
868        displayContent.layoutNeeded = false;
869        WindowList windows = displayContent.getWindowList();
870        boolean isDefaultDisplay = displayContent.isDefaultDisplay;
871
872        DisplayInfo displayInfo = displayContent.getDisplayInfo();
873        final int dw = displayInfo.logicalWidth;
874        final int dh = displayInfo.logicalHeight;
875
876        if (mService.mInputConsumer != null) {
877            mService.mInputConsumer.layout(dw, dh);
878        }
879
880        if (mService.mWallpaperInputConsumer != null) {
881            mService.mWallpaperInputConsumer.layout(dw, dh);
882        }
883
884        final int N = windows.size();
885        int i;
886
887        if (DEBUG_LAYOUT) {
888            Slog.v(TAG, "-------------------------------------");
889            Slog.v(TAG, "performLayout: needed="
890                    + displayContent.layoutNeeded + " dw=" + dw + " dh=" + dh);
891        }
892
893        mService.mPolicy.beginLayoutLw(isDefaultDisplay, dw, dh, mService.mRotation,
894                mService.mCurConfiguration.uiMode);
895        if (isDefaultDisplay) {
896            // Not needed on non-default displays.
897            mService.mSystemDecorLayer = mService.mPolicy.getSystemDecorLayerLw();
898            mService.mScreenRect.set(0, 0, dw, dh);
899        }
900
901        mService.mPolicy.getContentRectLw(mTmpContentRect);
902        displayContent.resize(mTmpContentRect);
903
904        int seq = mService.mLayoutSeq+1;
905        if (seq < 0) seq = 0;
906        mService.mLayoutSeq = seq;
907
908        boolean behindDream = false;
909
910        // First perform layout of any root windows (not attached
911        // to another window).
912        int topAttached = -1;
913        for (i = N-1; i >= 0; i--) {
914            final WindowState win = windows.get(i);
915
916            // Don't do layout of a window if it is not visible, or
917            // soon won't be visible, to avoid wasting time and funky
918            // changes while a window is animating away.
919            final boolean gone = (behindDream && mService.mPolicy.canBeForceHidden(win, win.mAttrs))
920                    || win.isGoneForLayoutLw();
921
922            if (DEBUG_LAYOUT && !win.mLayoutAttached) {
923                Slog.v(TAG, "1ST PASS " + win
924                        + ": gone=" + gone + " mHaveFrame=" + win.mHaveFrame
925                        + " mLayoutAttached=" + win.mLayoutAttached
926                        + " screen changed=" + win.isConfigChanged());
927                final AppWindowToken atoken = win.mAppToken;
928                if (gone) Slog.v(TAG, "  GONE: mViewVisibility="
929                        + win.mViewVisibility + " mRelayoutCalled="
930                        + win.mRelayoutCalled + " hidden="
931                        + win.mRootToken.hidden + " hiddenRequested="
932                        + (atoken != null && atoken.hiddenRequested)
933                        + " mAttachedHidden=" + win.mAttachedHidden);
934                else Slog.v(TAG, "  VIS: mViewVisibility="
935                        + win.mViewVisibility + " mRelayoutCalled="
936                        + win.mRelayoutCalled + " hidden="
937                        + win.mRootToken.hidden + " hiddenRequested="
938                        + (atoken != null && atoken.hiddenRequested)
939                        + " mAttachedHidden=" + win.mAttachedHidden);
940            }
941
942            // If this view is GONE, then skip it -- keep the current
943            // frame, and let the caller know so they can ignore it
944            // if they want.  (We do the normal layout for INVISIBLE
945            // windows, since that means "perform layout as normal,
946            // just don't display").
947            if (!gone || !win.mHaveFrame || win.mLayoutNeeded
948                    || ((win.isConfigChanged() || win.setInsetsChanged())
949                            && !win.isGoneForLayoutLw() &&
950                            ((win.mAttrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0 ||
951                            (win.mHasSurface && win.mAppToken != null &&
952                            win.mAppToken.layoutConfigChanges)))) {
953                if (!win.mLayoutAttached) {
954                    if (initial) {
955                        //Slog.i(TAG, "Window " + this + " clearing mContentChanged - initial");
956                        win.mContentChanged = false;
957                    }
958                    if (win.mAttrs.type == TYPE_DREAM) {
959                        // Don't layout windows behind a dream, so that if it
960                        // does stuff like hide the status bar we won't get a
961                        // bad transition when it goes away.
962                        behindDream = true;
963                    }
964                    win.mLayoutNeeded = false;
965                    win.prelayout();
966                    mService.mPolicy.layoutWindowLw(win, null);
967                    win.mLayoutSeq = seq;
968
969                    // Window frames may have changed. Update dim layer with the new bounds.
970                    final Task task = win.getTask();
971                    if (task != null) {
972                        displayContent.mDimLayerController.updateDimLayer(task);
973                    }
974
975                    if (DEBUG_LAYOUT) Slog.v(TAG,
976                            "  LAYOUT: mFrame="
977                            + win.mFrame + " mContainingFrame="
978                            + win.mContainingFrame + " mDisplayFrame="
979                            + win.mDisplayFrame);
980                } else {
981                    if (topAttached < 0) topAttached = i;
982                }
983            }
984        }
985
986        boolean attachedBehindDream = false;
987
988        // Now perform layout of attached windows, which usually
989        // depend on the position of the window they are attached to.
990        // XXX does not deal with windows that are attached to windows
991        // that are themselves attached.
992        for (i = topAttached; i >= 0; i--) {
993            final WindowState win = windows.get(i);
994
995            if (win.mLayoutAttached) {
996                if (DEBUG_LAYOUT) Slog.v(TAG,
997                        "2ND PASS " + win + " mHaveFrame=" + win.mHaveFrame + " mViewVisibility="
998                        + win.mViewVisibility + " mRelayoutCalled=" + win.mRelayoutCalled);
999                // If this view is GONE, then skip it -- keep the current
1000                // frame, and let the caller know so they can ignore it
1001                // if they want.  (We do the normal layout for INVISIBLE
1002                // windows, since that means "perform layout as normal,
1003                // just don't display").
1004                if (attachedBehindDream && mService.mPolicy.canBeForceHidden(win, win.mAttrs)) {
1005                    continue;
1006                }
1007                if ((win.mViewVisibility != View.GONE && win.mRelayoutCalled)
1008                        || !win.mHaveFrame || win.mLayoutNeeded) {
1009                    if (initial) {
1010                        //Slog.i(TAG, "Window " + this + " clearing mContentChanged - initial");
1011                        win.mContentChanged = false;
1012                    }
1013                    win.mLayoutNeeded = false;
1014                    win.prelayout();
1015                    mService.mPolicy.layoutWindowLw(win, win.mAttachedWindow);
1016                    win.mLayoutSeq = seq;
1017                    if (DEBUG_LAYOUT) Slog.v(TAG,
1018                            "  LAYOUT: mFrame=" + win.mFrame + " mContainingFrame="
1019                            + win.mContainingFrame + " mDisplayFrame=" + win.mDisplayFrame);
1020                }
1021            } else if (win.mAttrs.type == TYPE_DREAM) {
1022                // Don't layout windows behind a dream, so that if it
1023                // does stuff like hide the status bar we won't get a
1024                // bad transition when it goes away.
1025                attachedBehindDream = behindDream;
1026            }
1027        }
1028
1029        // Window frames may have changed. Tell the input dispatcher about it.
1030        mService.mInputMonitor.setUpdateInputWindowsNeededLw();
1031        if (updateInputWindows) {
1032            mService.mInputMonitor.updateInputWindowsLw(false /*force*/);
1033        }
1034
1035        mService.mPolicy.finishLayoutLw();
1036        mService.mH.sendEmptyMessage(UPDATE_DOCKED_STACK_DIVIDER);
1037    }
1038
1039    /**
1040     * @param windows List of windows on default display.
1041     * @return bitmap indicating if another pass through layout must be made.
1042     */
1043    private int handleAppTransitionReadyLocked(WindowList windows) {
1044        int appsCount = mService.mOpeningApps.size();
1045        if (!transitionGoodToGo(appsCount)) {
1046            return 0;
1047        }
1048        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "**** GOOD TO GO");
1049        int transit = mService.mAppTransition.getAppTransition();
1050        if (mService.mSkipAppTransitionAnimation) {
1051            transit = AppTransition.TRANSIT_UNSET;
1052        }
1053        mService.mSkipAppTransitionAnimation = false;
1054        mService.mNoAnimationNotifyOnTransitionFinished.clear();
1055
1056        mService.mH.removeMessages(H.APP_TRANSITION_TIMEOUT);
1057
1058        mService.rebuildAppWindowListLocked();
1059
1060        mWallpaperMayChange = false;
1061
1062        // The top-most window will supply the layout params,
1063        // and we will determine it below.
1064        LayoutParams animLp = null;
1065        int bestAnimLayer = -1;
1066        boolean fullscreenAnim = false;
1067        boolean voiceInteraction = false;
1068
1069        final WindowState lowerWallpaperTarget =
1070                mWallpaperControllerLocked.getLowerWallpaperTarget();
1071        final WindowState upperWallpaperTarget =
1072                mWallpaperControllerLocked.getUpperWallpaperTarget();
1073
1074        boolean openingAppHasWallpaper = false;
1075        boolean closingAppHasWallpaper = false;
1076        final AppWindowToken lowerWallpaperAppToken;
1077        final AppWindowToken upperWallpaperAppToken;
1078        if (lowerWallpaperTarget == null) {
1079            lowerWallpaperAppToken = upperWallpaperAppToken = null;
1080        } else {
1081            lowerWallpaperAppToken = lowerWallpaperTarget.mAppToken;
1082            upperWallpaperAppToken = upperWallpaperTarget.mAppToken;
1083        }
1084
1085        int i;
1086        // Do a first pass through the tokens for two
1087        // things:
1088        // (1) Determine if both the closing and opening
1089        // app token sets are wallpaper targets, in which
1090        // case special animations are needed
1091        // (since the wallpaper needs to stay static
1092        // behind them).
1093        // (2) Find the layout params of the top-most
1094        // application window in the tokens, which is
1095        // what will control the animation theme.
1096        final int closingAppsCount = mService.mClosingApps.size();
1097        appsCount = closingAppsCount + mService.mOpeningApps.size();
1098        for (i = 0; i < appsCount; i++) {
1099            final AppWindowToken wtoken;
1100            if (i < closingAppsCount) {
1101                wtoken = mService.mClosingApps.valueAt(i);
1102                if (wtoken == lowerWallpaperAppToken || wtoken == upperWallpaperAppToken) {
1103                    closingAppHasWallpaper = true;
1104                }
1105            } else {
1106                wtoken = mService.mOpeningApps.valueAt(i - closingAppsCount);
1107                if (wtoken == lowerWallpaperAppToken || wtoken == upperWallpaperAppToken) {
1108                    openingAppHasWallpaper = true;
1109                }
1110            }
1111
1112            voiceInteraction |= wtoken.voiceInteraction;
1113
1114            if (wtoken.appFullscreen) {
1115                WindowState ws = wtoken.findMainWindow();
1116                if (ws != null) {
1117                    animLp = ws.mAttrs;
1118                    bestAnimLayer = ws.mLayer;
1119                    fullscreenAnim = true;
1120                }
1121            } else if (!fullscreenAnim) {
1122                WindowState ws = wtoken.findMainWindow();
1123                if (ws != null) {
1124                    if (ws.mLayer > bestAnimLayer) {
1125                        animLp = ws.mAttrs;
1126                        bestAnimLayer = ws.mLayer;
1127                    }
1128                }
1129            }
1130        }
1131
1132        transit = maybeUpdateTransitToWallpaper(transit, openingAppHasWallpaper,
1133                closingAppHasWallpaper, lowerWallpaperTarget, upperWallpaperTarget);
1134
1135        // If all closing windows are obscured, then there is
1136        // no need to do an animation.  This is the case, for
1137        // example, when this transition is being done behind
1138        // the lock screen.
1139        if (!mService.mPolicy.allowAppAnimationsLw()) {
1140            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1141                    "Animations disallowed by keyguard or dream.");
1142            animLp = null;
1143        }
1144
1145        processApplicationsAnimatingInPlace(transit);
1146
1147        mTmpLayerAndToken.token = null;
1148        handleClosingApps(transit, animLp, voiceInteraction, mTmpLayerAndToken);
1149        final AppWindowToken topClosingApp = mTmpLayerAndToken.token;
1150        final int topClosingLayer = mTmpLayerAndToken.layer;
1151
1152        final AppWindowToken topOpeningApp = handleOpeningApps(transit,
1153                animLp, voiceInteraction, topClosingLayer);
1154
1155        final AppWindowAnimator openingAppAnimator = (topOpeningApp == null) ?  null :
1156                topOpeningApp.mAppAnimator;
1157        final AppWindowAnimator closingAppAnimator = (topClosingApp == null) ? null :
1158                topClosingApp.mAppAnimator;
1159
1160        mService.mAppTransition.goodToGo(openingAppAnimator, closingAppAnimator,
1161                mService.mOpeningApps, mService.mClosingApps);
1162        mService.mAppTransition.postAnimationCallback();
1163        mService.mAppTransition.clear();
1164
1165        mService.mOpeningApps.clear();
1166        mService.mClosingApps.clear();
1167
1168        // This has changed the visibility of windows, so perform
1169        // a new layout to get them all up-to-date.
1170        mService.getDefaultDisplayContentLocked().layoutNeeded = true;
1171
1172        // TODO(multidisplay): IMEs are only supported on the default display.
1173        if (windows == mService.getDefaultWindowListLocked()
1174                && !mService.moveInputMethodWindowsIfNeededLocked(true)) {
1175            mService.mLayersController.assignLayersLocked(windows);
1176        }
1177        mService.updateFocusedWindowLocked(UPDATE_FOCUS_PLACING_SURFACES,
1178                true /*updateInputWindows*/);
1179        mService.mFocusMayChange = false;
1180        mService.notifyActivityDrawnForKeyguard();
1181        return FINISH_LAYOUT_REDO_LAYOUT | FINISH_LAYOUT_REDO_CONFIG;
1182    }
1183
1184    private AppWindowToken handleOpeningApps(int transit, LayoutParams animLp,
1185            boolean voiceInteraction, int topClosingLayer) {
1186        AppWindowToken topOpeningApp = null;
1187        final int appsCount = mService.mOpeningApps.size();
1188        for (int i = 0; i < appsCount; i++) {
1189            AppWindowToken wtoken = mService.mOpeningApps.valueAt(i);
1190            final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
1191            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Now opening app" + wtoken);
1192
1193            if (!appAnimator.usingTransferredAnimation) {
1194                appAnimator.clearThumbnail();
1195                appAnimator.setNullAnimation();
1196            }
1197            wtoken.inPendingTransaction = false;
1198
1199            if (!mService.setTokenVisibilityLocked(
1200                    wtoken, animLp, true, transit, false, voiceInteraction)){
1201                // This token isn't going to be animating. Add it to the list of tokens to
1202                // be notified of app transition complete since the notification will not be
1203                // sent be the app window animator.
1204                mService.mNoAnimationNotifyOnTransitionFinished.add(wtoken.token);
1205            }
1206            wtoken.updateReportedVisibilityLocked();
1207            wtoken.waitingToShow = false;
1208
1209            appAnimator.mAllAppWinAnimators.clear();
1210            final int windowsCount = wtoken.allAppWindows.size();
1211            for (int j = 0; j < windowsCount; j++) {
1212                appAnimator.mAllAppWinAnimators.add(wtoken.allAppWindows.get(j).mWinAnimator);
1213            }
1214            if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1215                    ">>> OPEN TRANSACTION handleAppTransitionReadyLocked()");
1216            SurfaceControl.openTransaction();
1217            try {
1218                mService.mAnimator.orAnimating(appAnimator.showAllWindowsLocked());
1219            } finally {
1220                SurfaceControl.closeTransaction();
1221                if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG,
1222                        "<<< CLOSE TRANSACTION handleAppTransitionReadyLocked()");
1223            }
1224            mService.mAnimator.mAppWindowAnimating |= appAnimator.isAnimating();
1225
1226            int topOpeningLayer = 0;
1227            if (animLp != null) {
1228                int layer = -1;
1229                for (int j = 0; j < wtoken.windows.size(); j++) {
1230                    final WindowState win = wtoken.windows.get(j);
1231                    // Clearing the mAnimatingExit flag before entering animation. It will be set to true
1232                    // if app window is removed, or window relayout to invisible. We don't want to
1233                    // clear it out for windows that get replaced, because the animation depends on
1234                    // the flag to remove the replaced window.
1235                    //
1236                    // We also don't clear the mAnimatingExit flag for windows which have the
1237                    // mRemoveOnExit flag. This indicates an explicit remove request has been issued
1238                    // by the client. We should let animation proceed and not clear this flag or
1239                    // they won't eventually be removed by WindowStateAnimator#finishExit.
1240                    if (!win.mWillReplaceWindow && !win.mRemoveOnExit) {
1241                        win.mAnimatingExit = false;
1242                    }
1243                    if (win.mWinAnimator.mAnimLayer > layer) {
1244                        layer = win.mWinAnimator.mAnimLayer;
1245                    }
1246                }
1247                if (topOpeningApp == null || layer > topOpeningLayer) {
1248                    topOpeningApp = wtoken;
1249                    topOpeningLayer = layer;
1250                }
1251            }
1252            if (mService.mAppTransition.isNextAppTransitionThumbnailUp()) {
1253                createThumbnailAppAnimator(transit, wtoken, topOpeningLayer, topClosingLayer);
1254            }
1255        }
1256        return topOpeningApp;
1257    }
1258
1259    private void handleClosingApps(int transit, LayoutParams animLp, boolean voiceInteraction,
1260            LayerAndToken layerAndToken) {
1261        final int appsCount;
1262        appsCount = mService.mClosingApps.size();
1263        for (int i = 0; i < appsCount; i++) {
1264            AppWindowToken wtoken = mService.mClosingApps.valueAt(i);
1265            final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
1266            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "Now closing app " + wtoken);
1267            appAnimator.clearThumbnail();
1268            appAnimator.setNullAnimation();
1269            wtoken.inPendingTransaction = false;
1270            mService.setTokenVisibilityLocked(wtoken, animLp, false, transit, false,
1271                    voiceInteraction);
1272            wtoken.updateReportedVisibilityLocked();
1273            // Force the allDrawn flag, because we want to start
1274            // this guy's animations regardless of whether it's
1275            // gotten drawn.
1276            wtoken.allDrawn = true;
1277            wtoken.deferClearAllDrawn = false;
1278            // Ensure that apps that are mid-starting are also scheduled to have their
1279            // starting windows removed after the animation is complete
1280            if (wtoken.startingWindow != null && !wtoken.startingWindow.mAnimatingExit) {
1281                mService.scheduleRemoveStartingWindowLocked(wtoken);
1282            }
1283            mService.mAnimator.mAppWindowAnimating |= appAnimator.isAnimating();
1284
1285            if (animLp != null) {
1286                int layer = -1;
1287                for (int j = 0; j < wtoken.windows.size(); j++) {
1288                    WindowState win = wtoken.windows.get(j);
1289                    if (win.mWinAnimator.mAnimLayer > layer) {
1290                        layer = win.mWinAnimator.mAnimLayer;
1291                    }
1292                }
1293                if (layerAndToken.token == null || layer > layerAndToken.layer) {
1294                    layerAndToken.token = wtoken;
1295                    layerAndToken.layer = layer;
1296                }
1297            }
1298            if (mService.mAppTransition.isNextAppTransitionThumbnailDown()) {
1299                createThumbnailAppAnimator(transit, wtoken, 0, layerAndToken.layer);
1300            }
1301        }
1302    }
1303
1304    private boolean transitionGoodToGo(int appsCount) {
1305        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1306                "Checking " + appsCount + " opening apps (frozen="
1307                        + mService.mDisplayFrozen + " timeout="
1308                        + mService.mAppTransition.isTimeout() + ")...");
1309        int reason = APP_TRANSITION_TIMEOUT;
1310        if (!mService.mAppTransition.isTimeout()) {
1311            for (int i = 0; i < appsCount; i++) {
1312                AppWindowToken wtoken = mService.mOpeningApps.valueAt(i);
1313                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1314                        "Check opening app=" + wtoken + ": allDrawn="
1315                        + wtoken.allDrawn + " startingDisplayed="
1316                        + wtoken.startingDisplayed + " startingMoved="
1317                        + wtoken.startingMoved + " isRelaunching()="
1318                        + wtoken.isRelaunching());
1319
1320                if (wtoken.isRelaunching()) {
1321                    return false;
1322                }
1323
1324                final boolean drawnBeforeRestoring = wtoken.allDrawn;
1325                wtoken.restoreSavedSurfaces();
1326
1327                if (!wtoken.allDrawn && !wtoken.startingDisplayed && !wtoken.startingMoved) {
1328                    return false;
1329                }
1330                if (wtoken.allDrawn) {
1331                    reason = drawnBeforeRestoring ? APP_TRANSITION_WINDOWS_DRAWN
1332                            : APP_TRANSITION_SAVED_SURFACE;
1333                } else {
1334                    reason = APP_TRANSITION_STARTING_WINDOW;
1335                }
1336            }
1337
1338            // We also need to wait for the specs to be fetched, if needed.
1339            if (mService.mAppTransition.isFetchingAppTransitionsSpecs()) {
1340                if (DEBUG_APP_TRANSITIONS) Slog.v(TAG, "isFetchingAppTransitionSpecs=true");
1341                return false;
1342            }
1343
1344            // If the wallpaper is visible, we need to check it's ready too.
1345            boolean wallpaperReady = !mWallpaperControllerLocked.isWallpaperVisible() ||
1346                    mWallpaperControllerLocked.wallpaperTransitionReady();
1347            if (wallpaperReady) {
1348                mService.mH.obtainMessage(NOTIFY_APP_TRANSITION_STARTING, reason, 0).sendToTarget();
1349                return true;
1350            }
1351            return false;
1352        }
1353        mService.mH.obtainMessage(NOTIFY_APP_TRANSITION_STARTING, reason, 0).sendToTarget();
1354        return true;
1355    }
1356
1357    private int maybeUpdateTransitToWallpaper(int transit, boolean openingAppHasWallpaper,
1358            boolean closingAppHasWallpaper, WindowState lowerWallpaperTarget,
1359            WindowState upperWallpaperTarget) {
1360        // if wallpaper is animating in or out set oldWallpaper to null else to wallpaper
1361        final WindowState wallpaperTarget = mWallpaperControllerLocked.getWallpaperTarget();
1362        final WindowState oldWallpaper =
1363                mWallpaperControllerLocked.isWallpaperTargetAnimating()
1364                        ? null : wallpaperTarget;
1365        final ArraySet<AppWindowToken> openingApps = mService.mOpeningApps;
1366        final ArraySet<AppWindowToken> closingApps = mService.mClosingApps;
1367        if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1368                "New wallpaper target=" + wallpaperTarget
1369                        + ", oldWallpaper=" + oldWallpaper
1370                        + ", lower target=" + lowerWallpaperTarget
1371                        + ", upper target=" + upperWallpaperTarget
1372                        + ", openingApps=" + openingApps
1373                        + ", closingApps=" + closingApps);
1374        mService.mAnimateWallpaperWithTarget = false;
1375        if (closingAppHasWallpaper && openingAppHasWallpaper) {
1376            if (DEBUG_APP_TRANSITIONS)
1377                Slog.v(TAG, "Wallpaper animation!");
1378            switch (transit) {
1379                case AppTransition.TRANSIT_ACTIVITY_OPEN:
1380                case AppTransition.TRANSIT_TASK_OPEN:
1381                case AppTransition.TRANSIT_TASK_TO_FRONT:
1382                    transit = AppTransition.TRANSIT_WALLPAPER_INTRA_OPEN;
1383                    break;
1384                case AppTransition.TRANSIT_ACTIVITY_CLOSE:
1385                case AppTransition.TRANSIT_TASK_CLOSE:
1386                case AppTransition.TRANSIT_TASK_TO_BACK:
1387                    transit = AppTransition.TRANSIT_WALLPAPER_INTRA_CLOSE;
1388                    break;
1389            }
1390            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1391                    "New transit: " + AppTransition.appTransitionToString(transit));
1392        } else if (oldWallpaper != null && !mService.mOpeningApps.isEmpty()
1393                && !openingApps.contains(oldWallpaper.mAppToken)
1394                && closingApps.contains(oldWallpaper.mAppToken)) {
1395            // We are transitioning from an activity with a wallpaper to one without.
1396            transit = AppTransition.TRANSIT_WALLPAPER_CLOSE;
1397            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1398                    "New transit away from wallpaper: "
1399                    + AppTransition.appTransitionToString(transit));
1400        } else if (wallpaperTarget != null && wallpaperTarget.isVisibleLw() &&
1401                openingApps.contains(wallpaperTarget.mAppToken)) {
1402            // We are transitioning from an activity without
1403            // a wallpaper to now showing the wallpaper
1404            transit = AppTransition.TRANSIT_WALLPAPER_OPEN;
1405            if (DEBUG_APP_TRANSITIONS) Slog.v(TAG,
1406                    "New transit into wallpaper: "
1407                    + AppTransition.appTransitionToString(transit));
1408        } else {
1409            mService.mAnimateWallpaperWithTarget = true;
1410        }
1411        return transit;
1412    }
1413
1414    /**
1415     * @param w WindowState this method is applied to.
1416     * @param dispInfo info of the display that the window's obscuring state is checked against.
1417     */
1418    private void handleNotObscuredLocked(final WindowState w, final DisplayInfo dispInfo) {
1419        final LayoutParams attrs = w.mAttrs;
1420        final int attrFlags = attrs.flags;
1421        final boolean canBeSeen = w.isDisplayedLw();
1422        final int privateflags = attrs.privateFlags;
1423
1424        if (canBeSeen && w.isObscuringFullscreen(dispInfo)) {
1425            // This window completely covers everything behind it,
1426            // so we want to leave all of them as undimmed (for
1427            // performance reasons).
1428            mObscured = true;
1429        }
1430
1431        if (w.mHasSurface) {
1432            if ((attrFlags&FLAG_KEEP_SCREEN_ON) != 0) {
1433                mHoldScreen = w.mSession;
1434            }
1435            if (!mSyswin && w.mAttrs.screenBrightness >= 0
1436                    && mScreenBrightness < 0) {
1437                mScreenBrightness = w.mAttrs.screenBrightness;
1438            }
1439            if (!mSyswin && w.mAttrs.buttonBrightness >= 0
1440                    && mButtonBrightness < 0) {
1441                mButtonBrightness = w.mAttrs.buttonBrightness;
1442            }
1443            if (!mSyswin && w.mAttrs.userActivityTimeout >= 0
1444                    && mUserActivityTimeout < 0) {
1445                mUserActivityTimeout = w.mAttrs.userActivityTimeout;
1446            }
1447
1448            final int type = attrs.type;
1449            if (canBeSeen
1450                    && (type == TYPE_SYSTEM_DIALOG
1451                     || type == TYPE_SYSTEM_ERROR
1452                     || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0)) {
1453                mSyswin = true;
1454            }
1455
1456            if (canBeSeen) {
1457                // This function assumes that the contents of the default display are
1458                // processed first before secondary displays.
1459                final DisplayContent displayContent = w.getDisplayContent();
1460                if (displayContent != null && displayContent.isDefaultDisplay) {
1461                    // While a dream or keyguard is showing, obscure ordinary application
1462                    // content on secondary displays (by forcibly enabling mirroring unless
1463                    // there is other content we want to show) but still allow opaque
1464                    // keyguard dialogs to be shown.
1465                    if (type == TYPE_DREAM || (attrs.privateFlags & PRIVATE_FLAG_KEYGUARD) != 0) {
1466                        mObscureApplicationContentOnSecondaryDisplays = true;
1467                    }
1468                    mDisplayHasContent = true;
1469                } else if (displayContent != null &&
1470                        (!mObscureApplicationContentOnSecondaryDisplays
1471                        || (mObscured && type == TYPE_KEYGUARD_DIALOG))) {
1472                    // Allow full screen keyguard presentation dialogs to be seen.
1473                    mDisplayHasContent = true;
1474                }
1475                if (mPreferredRefreshRate == 0
1476                        && w.mAttrs.preferredRefreshRate != 0) {
1477                    mPreferredRefreshRate = w.mAttrs.preferredRefreshRate;
1478                }
1479                if (mPreferredModeId == 0
1480                        && w.mAttrs.preferredDisplayModeId != 0) {
1481                    mPreferredModeId = w.mAttrs.preferredDisplayModeId;
1482                }
1483                if ((privateflags & PRIVATE_FLAG_SUSTAINED_PERFORMANCE_MODE) != 0) {
1484                    mSustainedPerformanceModeCurrent = true;
1485                }
1486            }
1487        }
1488    }
1489
1490    private void updateAllDrawnLocked(DisplayContent displayContent) {
1491        // See if any windows have been drawn, so they (and others
1492        // associated with them) can now be shown.
1493        ArrayList<TaskStack> stacks = displayContent.getStacks();
1494        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
1495            final ArrayList<Task> tasks = stacks.get(stackNdx).getTasks();
1496            for (int taskNdx = tasks.size() - 1; taskNdx >= 0; --taskNdx) {
1497                final AppTokenList tokens = tasks.get(taskNdx).mAppTokens;
1498                for (int tokenNdx = tokens.size() - 1; tokenNdx >= 0; --tokenNdx) {
1499                    final AppWindowToken wtoken = tokens.get(tokenNdx);
1500                    if (!wtoken.allDrawn) {
1501                        int numInteresting = wtoken.numInterestingWindows;
1502                        if (numInteresting > 0 && wtoken.numDrawnWindows >= numInteresting) {
1503                            if (DEBUG_VISIBILITY)
1504                                Slog.v(TAG, "allDrawn: " + wtoken
1505                                    + " interesting=" + numInteresting
1506                                    + " drawn=" + wtoken.numDrawnWindows);
1507                            wtoken.allDrawn = true;
1508                            // Force an additional layout pass where WindowStateAnimator#
1509                            // commitFinishDrawingLocked() will call performShowLocked().
1510                            displayContent.layoutNeeded = true;
1511                            mService.mH.obtainMessage(NOTIFY_ACTIVITY_DRAWN,
1512                                    wtoken.token).sendToTarget();
1513                        }
1514                    }
1515                }
1516            }
1517        }
1518    }
1519
1520    private static int toBrightnessOverride(float value) {
1521        return (int)(value * PowerManager.BRIGHTNESS_ON);
1522    }
1523
1524    private void processApplicationsAnimatingInPlace(int transit) {
1525        if (transit == AppTransition.TRANSIT_TASK_IN_PLACE) {
1526            // Find the focused window
1527            final WindowState win = mService.findFocusedWindowLocked(
1528                    mService.getDefaultDisplayContentLocked());
1529            if (win != null) {
1530                final AppWindowToken wtoken = win.mAppToken;
1531                final AppWindowAnimator appAnimator = wtoken.mAppAnimator;
1532                if (DEBUG_APP_TRANSITIONS)
1533                    Slog.v(TAG, "Now animating app in place " + wtoken);
1534                appAnimator.clearThumbnail();
1535                appAnimator.setNullAnimation();
1536                mService.updateTokenInPlaceLocked(wtoken, transit);
1537                wtoken.updateReportedVisibilityLocked();
1538
1539                appAnimator.mAllAppWinAnimators.clear();
1540                final int N = wtoken.allAppWindows.size();
1541                for (int j = 0; j < N; j++) {
1542                    appAnimator.mAllAppWinAnimators.add(wtoken.allAppWindows.get(j).mWinAnimator);
1543                }
1544                mService.mAnimator.mAppWindowAnimating |= appAnimator.isAnimating();
1545                mService.mAnimator.orAnimating(appAnimator.showAllWindowsLocked());
1546            }
1547        }
1548    }
1549
1550    private void createThumbnailAppAnimator(int transit, AppWindowToken appToken,
1551            int openingLayer, int closingLayer) {
1552        AppWindowAnimator openingAppAnimator = (appToken == null) ? null : appToken.mAppAnimator;
1553        if (openingAppAnimator == null || openingAppAnimator.animation == null) {
1554            return;
1555        }
1556        final int taskId = appToken.mTask.mTaskId;
1557        Bitmap thumbnailHeader = mService.mAppTransition.getAppTransitionThumbnailHeader(taskId);
1558        if (thumbnailHeader == null || thumbnailHeader.getConfig() == Bitmap.Config.ALPHA_8) {
1559            if (DEBUG_APP_TRANSITIONS) Slog.d(TAG, "No thumbnail header bitmap for: " + taskId);
1560            return;
1561        }
1562        // This thumbnail animation is very special, we need to have
1563        // an extra surface with the thumbnail included with the animation.
1564        Rect dirty = new Rect(0, 0, thumbnailHeader.getWidth(), thumbnailHeader.getHeight());
1565        try {
1566            // TODO(multi-display): support other displays
1567            final DisplayContent displayContent = mService.getDefaultDisplayContentLocked();
1568            final Display display = displayContent.getDisplay();
1569            final DisplayInfo displayInfo = displayContent.getDisplayInfo();
1570
1571            // Create a new surface for the thumbnail
1572            SurfaceControl surfaceControl = new SurfaceControl(mService.mFxSession,
1573                    "thumbnail anim", dirty.width(), dirty.height(),
1574                    PixelFormat.TRANSLUCENT, SurfaceControl.HIDDEN);
1575            surfaceControl.setLayerStack(display.getLayerStack());
1576            if (SHOW_TRANSACTIONS) {
1577                Slog.i(TAG, "  THUMBNAIL " + surfaceControl + ": CREATE");
1578            }
1579
1580            // Draw the thumbnail onto the surface
1581            Surface drawSurface = new Surface();
1582            drawSurface.copyFrom(surfaceControl);
1583            Canvas c = drawSurface.lockCanvas(dirty);
1584            c.drawBitmap(thumbnailHeader, 0, 0, null);
1585            drawSurface.unlockCanvasAndPost(c);
1586            drawSurface.release();
1587
1588            // Get the thumbnail animation
1589            Animation anim;
1590            if (mService.mAppTransition.isNextThumbnailTransitionAspectScaled()) {
1591                // If this is a multi-window scenario, we use the windows frame as
1592                // destination of the thumbnail header animation. If this is a full screen
1593                // window scenario, we use the whole display as the target.
1594                WindowState win = appToken.findMainWindow();
1595                Rect appRect = win != null ? win.getContentFrameLw() :
1596                        new Rect(0, 0, displayInfo.appWidth, displayInfo.appHeight);
1597                Rect insets = win != null ? win.mContentInsets : null;
1598                // For the new aspect-scaled transition, we want it to always show
1599                // above the animating opening/closing window, and we want to
1600                // synchronize its thumbnail surface with the surface for the
1601                // open/close animation (only on the way down)
1602                anim = mService.mAppTransition.createThumbnailAspectScaleAnimationLocked(appRect,
1603                        insets, thumbnailHeader, taskId, mService.mCurConfiguration.uiMode,
1604                        mService.mCurConfiguration.orientation);
1605                openingAppAnimator.thumbnailForceAboveLayer = Math.max(openingLayer, closingLayer);
1606                openingAppAnimator.deferThumbnailDestruction =
1607                        !mService.mAppTransition.isNextThumbnailTransitionScaleUp();
1608            } else {
1609                anim = mService.mAppTransition.createThumbnailScaleAnimationLocked(
1610                        displayInfo.appWidth, displayInfo.appHeight, transit, thumbnailHeader);
1611            }
1612            anim.restrictDuration(MAX_ANIMATION_DURATION);
1613            anim.scaleCurrentDuration(mService.getTransitionAnimationScaleLocked());
1614
1615            openingAppAnimator.thumbnail = surfaceControl;
1616            openingAppAnimator.thumbnailLayer = openingLayer;
1617            openingAppAnimator.thumbnailAnimation = anim;
1618            mService.mAppTransition.getNextAppTransitionStartRect(taskId, mTmpStartRect);
1619        } catch (Surface.OutOfResourcesException e) {
1620            Slog.e(TAG, "Can't allocate thumbnail/Canvas surface w="
1621                    + dirty.width() + " h=" + dirty.height(), e);
1622            openingAppAnimator.clearThumbnail();
1623        }
1624    }
1625
1626    boolean copyAnimToLayoutParamsLocked() {
1627        boolean doRequest = false;
1628
1629        final int bulkUpdateParams = mService.mAnimator.mBulkUpdateParams;
1630        if ((bulkUpdateParams & SET_UPDATE_ROTATION) != 0) {
1631            mUpdateRotation = true;
1632            doRequest = true;
1633        }
1634        if ((bulkUpdateParams & SET_WALLPAPER_MAY_CHANGE) != 0) {
1635            mWallpaperMayChange = true;
1636            doRequest = true;
1637        }
1638        if ((bulkUpdateParams & SET_FORCE_HIDING_CHANGED) != 0) {
1639            mWallpaperForceHidingChanged = true;
1640            doRequest = true;
1641        }
1642        if ((bulkUpdateParams & SET_ORIENTATION_CHANGE_COMPLETE) == 0) {
1643            mOrientationChangeComplete = false;
1644        } else {
1645            mOrientationChangeComplete = true;
1646            mLastWindowFreezeSource = mService.mAnimator.mLastWindowFreezeSource;
1647            if (mService.mWindowsFreezingScreen != WINDOWS_FREEZING_SCREENS_NONE) {
1648                doRequest = true;
1649            }
1650        }
1651        if ((bulkUpdateParams & SET_TURN_ON_SCREEN) != 0) {
1652            mService.mTurnOnScreen = true;
1653        }
1654        if ((bulkUpdateParams & SET_WALLPAPER_ACTION_PENDING) != 0) {
1655            mWallpaperActionPending = true;
1656        }
1657
1658        return doRequest;
1659    }
1660
1661    void requestTraversal() {
1662        if (!mTraversalScheduled) {
1663            mTraversalScheduled = true;
1664            mService.mH.sendEmptyMessage(DO_TRAVERSAL);
1665        }
1666    }
1667
1668    /**
1669     * Puts the {@param surface} into a pending list to be destroyed after the current transaction
1670     * has been committed.
1671     */
1672    void destroyAfterTransaction(SurfaceControl surface) {
1673        mPendingDestroyingSurfaces.add(surface);
1674    }
1675
1676    /**
1677     * Destroys any surfaces that have been put into the pending list with
1678     * {@link #destroyAfterTransaction}.
1679     */
1680    void destroyPendingSurfaces() {
1681        for (int i = mPendingDestroyingSurfaces.size() - 1; i >= 0; i--) {
1682            mPendingDestroyingSurfaces.get(i).destroy();
1683        }
1684        mPendingDestroyingSurfaces.clear();
1685    }
1686
1687    public void dump(PrintWriter pw, String prefix) {
1688        pw.print(prefix); pw.print("mTraversalScheduled="); pw.println(mTraversalScheduled);
1689    }
1690}
1691