1/*
2 * Copyright (C) 2010 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 com.android.server.input.InputManagerService;
20import com.android.server.input.InputApplicationHandle;
21import com.android.server.input.InputWindowHandle;
22import com.android.server.wm.WindowManagerService.AllWindowsIterator;
23
24import android.app.ActivityManagerNative;
25import android.graphics.Rect;
26import android.os.RemoteException;
27import android.util.Log;
28import android.util.Slog;
29import android.view.Display;
30import android.view.InputChannel;
31import android.view.KeyEvent;
32import android.view.WindowManager;
33
34import java.util.ArrayList;
35import java.util.Arrays;
36
37final class InputMonitor implements InputManagerService.WindowManagerCallbacks {
38    private final WindowManagerService mService;
39
40    // Current window with input focus for keys and other non-touch events.  May be null.
41    private WindowState mInputFocus;
42
43    // When true, prevents input dispatch from proceeding until set to false again.
44    private boolean mInputDispatchFrozen;
45
46    // When true, input dispatch proceeds normally.  Otherwise all events are dropped.
47    // Initially false, so that input does not get dispatched until boot is finished at
48    // which point the ActivityManager will enable dispatching.
49    private boolean mInputDispatchEnabled;
50
51    // When true, need to call updateInputWindowsLw().
52    private boolean mUpdateInputWindowsNeeded = true;
53
54    // Array of window handles to provide to the input dispatcher.
55    private InputWindowHandle[] mInputWindowHandles;
56    private int mInputWindowHandleCount;
57
58    // Set to true when the first input device configuration change notification
59    // is received to indicate that the input devices are ready.
60    private final Object mInputDevicesReadyMonitor = new Object();
61    private boolean mInputDevicesReady;
62
63    public InputMonitor(WindowManagerService service) {
64        mService = service;
65    }
66
67    /* Notifies the window manager about a broken input channel.
68     *
69     * Called by the InputManager.
70     */
71    public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
72        if (inputWindowHandle == null) {
73            return;
74        }
75
76        synchronized (mService.mWindowMap) {
77            WindowState windowState = (WindowState) inputWindowHandle.windowState;
78            if (windowState != null) {
79                Slog.i(WindowManagerService.TAG, "WINDOW DIED " + windowState);
80                mService.removeWindowLocked(windowState.mSession, windowState);
81            }
82        }
83    }
84
85    /* Notifies the window manager about an application that is not responding.
86     * Returns a new timeout to continue waiting in nanoseconds, or 0 to abort dispatch.
87     *
88     * Called by the InputManager.
89     */
90    public long notifyANR(InputApplicationHandle inputApplicationHandle,
91            InputWindowHandle inputWindowHandle) {
92        AppWindowToken appWindowToken = null;
93        WindowState windowState = null;
94        boolean aboveSystem = false;
95        synchronized (mService.mWindowMap) {
96            if (inputWindowHandle != null) {
97                windowState = (WindowState) inputWindowHandle.windowState;
98                if (windowState != null) {
99                    appWindowToken = windowState.mAppToken;
100                }
101            }
102            if (appWindowToken == null && inputApplicationHandle != null) {
103                appWindowToken = (AppWindowToken)inputApplicationHandle.appWindowToken;
104            }
105
106            if (windowState != null) {
107                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out "
108                        + "sending to " + windowState.mAttrs.getTitle());
109                // Figure out whether this window is layered above system windows.
110                // We need to do this here to help the activity manager know how to
111                // layer its ANR dialog.
112                int systemAlertLayer = mService.mPolicy.windowTypeToLayerLw(
113                        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
114                aboveSystem = windowState.mBaseLayer > systemAlertLayer;
115            } else if (appWindowToken != null) {
116                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out "
117                        + "sending to application " + appWindowToken.stringName);
118            } else {
119                Slog.i(WindowManagerService.TAG, "Input event dispatching timed out.");
120            }
121
122            mService.saveANRStateLocked(appWindowToken, windowState);
123        }
124
125        if (appWindowToken != null && appWindowToken.appToken != null) {
126            try {
127                // Notify the activity manager about the timeout and let it decide whether
128                // to abort dispatching or keep waiting.
129                boolean abort = appWindowToken.appToken.keyDispatchingTimedOut();
130                if (! abort) {
131                    // The activity manager declined to abort dispatching.
132                    // Wait a bit longer and timeout again later.
133                    return appWindowToken.inputDispatchingTimeoutNanos;
134                }
135            } catch (RemoteException ex) {
136            }
137        } else if (windowState != null) {
138            try {
139                // Notify the activity manager about the timeout and let it decide whether
140                // to abort dispatching or keep waiting.
141                long timeout = ActivityManagerNative.getDefault().inputDispatchingTimedOut(
142                        windowState.mSession.mPid, aboveSystem);
143                if (timeout >= 0) {
144                    // The activity manager declined to abort dispatching.
145                    // Wait a bit longer and timeout again later.
146                    return timeout;
147                }
148            } catch (RemoteException ex) {
149            }
150        }
151        return 0; // abort dispatching
152    }
153
154    private void addInputWindowHandleLw(final InputWindowHandle windowHandle) {
155        if (mInputWindowHandles == null) {
156            mInputWindowHandles = new InputWindowHandle[16];
157        }
158        if (mInputWindowHandleCount >= mInputWindowHandles.length) {
159            mInputWindowHandles = Arrays.copyOf(mInputWindowHandles,
160                    mInputWindowHandleCount * 2);
161        }
162        mInputWindowHandles[mInputWindowHandleCount++] = windowHandle;
163    }
164
165    private void addInputWindowHandleLw(final InputWindowHandle inputWindowHandle,
166            final WindowState child, final int flags, final int type,
167            final boolean isVisible, final boolean hasFocus, final boolean hasWallpaper) {
168        // Add a window to our list of input windows.
169        inputWindowHandle.name = child.toString();
170        inputWindowHandle.layoutParamsFlags = flags;
171        inputWindowHandle.layoutParamsType = type;
172        inputWindowHandle.dispatchingTimeoutNanos = child.getInputDispatchingTimeoutNanos();
173        inputWindowHandle.visible = isVisible;
174        inputWindowHandle.canReceiveKeys = child.canReceiveKeys();
175        inputWindowHandle.hasFocus = hasFocus;
176        inputWindowHandle.hasWallpaper = hasWallpaper;
177        inputWindowHandle.paused = child.mAppToken != null ? child.mAppToken.paused : false;
178        inputWindowHandle.layer = child.mLayer;
179        inputWindowHandle.ownerPid = child.mSession.mPid;
180        inputWindowHandle.ownerUid = child.mSession.mUid;
181        inputWindowHandle.inputFeatures = child.mAttrs.inputFeatures;
182
183        final Rect frame = child.mFrame;
184        inputWindowHandle.frameLeft = frame.left;
185        inputWindowHandle.frameTop = frame.top;
186        inputWindowHandle.frameRight = frame.right;
187        inputWindowHandle.frameBottom = frame.bottom;
188
189        if (child.mGlobalScale != 1) {
190            // If we are scaling the window, input coordinates need
191            // to be inversely scaled to map from what is on screen
192            // to what is actually being touched in the UI.
193            inputWindowHandle.scaleFactor = 1.0f/child.mGlobalScale;
194        } else {
195            inputWindowHandle.scaleFactor = 1;
196        }
197
198        child.getTouchableRegion(inputWindowHandle.touchableRegion);
199
200        addInputWindowHandleLw(inputWindowHandle);
201    }
202
203    private void clearInputWindowHandlesLw() {
204        while (mInputWindowHandleCount != 0) {
205            mInputWindowHandles[--mInputWindowHandleCount] = null;
206        }
207    }
208
209    public void setUpdateInputWindowsNeededLw() {
210        mUpdateInputWindowsNeeded = true;
211    }
212
213    /* Updates the cached window information provided to the input dispatcher. */
214    public void updateInputWindowsLw(boolean force) {
215        if (!force && !mUpdateInputWindowsNeeded) {
216            return;
217        }
218        mUpdateInputWindowsNeeded = false;
219
220        if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED updateInputWindowsLw");
221
222        // Populate the input window list with information about all of the windows that
223        // could potentially receive input.
224        // As an optimization, we could try to prune the list of windows but this turns
225        // out to be difficult because only the native code knows for sure which window
226        // currently has touch focus.
227        final WindowStateAnimator universeBackground = mService.mAnimator.mUniverseBackground;
228        final int aboveUniverseLayer = mService.mAnimator.mAboveUniverseLayer;
229        boolean addedUniverse = false;
230
231        // If there's a drag in flight, provide a pseudowindow to catch drag input
232        final boolean inDrag = (mService.mDragState != null);
233        if (inDrag) {
234            if (WindowManagerService.DEBUG_DRAG) {
235                Log.d(WindowManagerService.TAG, "Inserting drag window");
236            }
237            final InputWindowHandle dragWindowHandle = mService.mDragState.mDragWindowHandle;
238            if (dragWindowHandle != null) {
239                addInputWindowHandleLw(dragWindowHandle);
240            } else {
241                Slog.w(WindowManagerService.TAG, "Drag is in progress but there is no "
242                        + "drag window handle.");
243            }
244        }
245
246        final int NFW = mService.mFakeWindows.size();
247        for (int i = 0; i < NFW; i++) {
248            addInputWindowHandleLw(mService.mFakeWindows.get(i).mWindowHandle);
249        }
250
251        // Add all windows on the default display.
252        final AllWindowsIterator iterator = mService.new AllWindowsIterator(
253                WindowManagerService.REVERSE_ITERATOR);
254        while (iterator.hasNext()) {
255            final WindowState child = iterator.next();
256            final InputChannel inputChannel = child.mInputChannel;
257            final InputWindowHandle inputWindowHandle = child.mInputWindowHandle;
258            if (inputChannel == null || inputWindowHandle == null || child.mRemoved) {
259                // Skip this window because it cannot possibly receive input.
260                continue;
261            }
262
263            final int flags = child.mAttrs.flags;
264            final int type = child.mAttrs.type;
265
266            final boolean hasFocus = (child == mInputFocus);
267            final boolean isVisible = child.isVisibleLw();
268            final boolean hasWallpaper = (child == mService.mWallpaperTarget)
269                    && (type != WindowManager.LayoutParams.TYPE_KEYGUARD);
270            final boolean onDefaultDisplay = (child.getDisplayId() == Display.DEFAULT_DISPLAY);
271
272            // If there's a drag in progress and 'child' is a potential drop target,
273            // make sure it's been told about the drag
274            if (inDrag && isVisible && onDefaultDisplay) {
275                mService.mDragState.sendDragStartedIfNeededLw(child);
276            }
277
278            if (universeBackground != null && !addedUniverse
279                    && child.mBaseLayer < aboveUniverseLayer && onDefaultDisplay) {
280                final WindowState u = universeBackground.mWin;
281                if (u.mInputChannel != null && u.mInputWindowHandle != null) {
282                    addInputWindowHandleLw(u.mInputWindowHandle, u, u.mAttrs.flags,
283                            u.mAttrs.type, true, u == mInputFocus, false);
284                }
285                addedUniverse = true;
286            }
287
288            if (child.mWinAnimator != universeBackground) {
289                addInputWindowHandleLw(inputWindowHandle, child, flags, type,
290                        isVisible, hasFocus, hasWallpaper);
291            }
292        }
293
294        // Send windows to native code.
295        mService.mInputManager.setInputWindows(mInputWindowHandles);
296
297        // Clear the list in preparation for the next round.
298        clearInputWindowHandlesLw();
299
300        if (false) Slog.d(WindowManagerService.TAG, "<<<<<<< EXITED updateInputWindowsLw");
301    }
302
303    /* Notifies that the input device configuration has changed. */
304    public void notifyConfigurationChanged() {
305        mService.sendNewConfiguration();
306
307        synchronized (mInputDevicesReadyMonitor) {
308            if (!mInputDevicesReady) {
309                mInputDevicesReady = true;
310                mInputDevicesReadyMonitor.notifyAll();
311            }
312        }
313    }
314
315    /* Waits until the built-in input devices have been configured. */
316    public boolean waitForInputDevicesReady(long timeoutMillis) {
317        synchronized (mInputDevicesReadyMonitor) {
318            if (!mInputDevicesReady) {
319                try {
320                    mInputDevicesReadyMonitor.wait(timeoutMillis);
321                } catch (InterruptedException ex) {
322                }
323            }
324            return mInputDevicesReady;
325        }
326    }
327
328    /* Notifies that the lid switch changed state. */
329    public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
330        mService.mPolicy.notifyLidSwitchChanged(whenNanos, lidOpen);
331    }
332
333    /* Provides an opportunity for the window manager policy to intercept early key
334     * processing as soon as the key has been read from the device. */
335    public int interceptKeyBeforeQueueing(
336            KeyEvent event, int policyFlags, boolean isScreenOn) {
337        return mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);
338    }
339
340    /* Provides an opportunity for the window manager policy to intercept early
341     * motion event processing when the screen is off since these events are normally
342     * dropped. */
343    public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
344        return mService.mPolicy.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
345    }
346
347    /* Provides an opportunity for the window manager policy to process a key before
348     * ordinary dispatch. */
349    public long interceptKeyBeforeDispatching(
350            InputWindowHandle focus, KeyEvent event, int policyFlags) {
351        WindowState windowState = focus != null ? (WindowState) focus.windowState : null;
352        return mService.mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);
353    }
354
355    /* Provides an opportunity for the window manager policy to process a key that
356     * the application did not handle. */
357    public KeyEvent dispatchUnhandledKey(
358            InputWindowHandle focus, KeyEvent event, int policyFlags) {
359        WindowState windowState = focus != null ? (WindowState) focus.windowState : null;
360        return mService.mPolicy.dispatchUnhandledKey(windowState, event, policyFlags);
361    }
362
363    /* Callback to get pointer layer. */
364    public int getPointerLayer() {
365        return mService.mPolicy.windowTypeToLayerLw(WindowManager.LayoutParams.TYPE_POINTER)
366                * WindowManagerService.TYPE_LAYER_MULTIPLIER
367                + WindowManagerService.TYPE_LAYER_OFFSET;
368    }
369
370    /* Called when the current input focus changes.
371     * Layer assignment is assumed to be complete by the time this is called.
372     */
373    public void setInputFocusLw(WindowState newWindow, boolean updateInputWindows) {
374        if (WindowManagerService.DEBUG_INPUT) {
375            Slog.d(WindowManagerService.TAG, "Input focus has changed to " + newWindow);
376        }
377
378        if (newWindow != mInputFocus) {
379            if (newWindow != null && newWindow.canReceiveKeys()) {
380                // Displaying a window implicitly causes dispatching to be unpaused.
381                // This is to protect against bugs if someone pauses dispatching but
382                // forgets to resume.
383                newWindow.mToken.paused = false;
384            }
385
386            mInputFocus = newWindow;
387            setUpdateInputWindowsNeededLw();
388
389            if (updateInputWindows) {
390                updateInputWindowsLw(false /*force*/);
391            }
392        }
393    }
394
395    public void setFocusedAppLw(AppWindowToken newApp) {
396        // Focused app has changed.
397        if (newApp == null) {
398            mService.mInputManager.setFocusedApplication(null);
399        } else {
400            final InputApplicationHandle handle = newApp.mInputApplicationHandle;
401            handle.name = newApp.toString();
402            handle.dispatchingTimeoutNanos = newApp.inputDispatchingTimeoutNanos;
403
404            mService.mInputManager.setFocusedApplication(handle);
405        }
406    }
407
408    public void pauseDispatchingLw(WindowToken window) {
409        if (! window.paused) {
410            if (WindowManagerService.DEBUG_INPUT) {
411                Slog.v(WindowManagerService.TAG, "Pausing WindowToken " + window);
412            }
413
414            window.paused = true;
415            updateInputWindowsLw(true /*force*/);
416        }
417    }
418
419    public void resumeDispatchingLw(WindowToken window) {
420        if (window.paused) {
421            if (WindowManagerService.DEBUG_INPUT) {
422                Slog.v(WindowManagerService.TAG, "Resuming WindowToken " + window);
423            }
424
425            window.paused = false;
426            updateInputWindowsLw(true /*force*/);
427        }
428    }
429
430    public void freezeInputDispatchingLw() {
431        if (! mInputDispatchFrozen) {
432            if (WindowManagerService.DEBUG_INPUT) {
433                Slog.v(WindowManagerService.TAG, "Freezing input dispatching");
434            }
435
436            mInputDispatchFrozen = true;
437            updateInputDispatchModeLw();
438        }
439    }
440
441    public void thawInputDispatchingLw() {
442        if (mInputDispatchFrozen) {
443            if (WindowManagerService.DEBUG_INPUT) {
444                Slog.v(WindowManagerService.TAG, "Thawing input dispatching");
445            }
446
447            mInputDispatchFrozen = false;
448            updateInputDispatchModeLw();
449        }
450    }
451
452    public void setEventDispatchingLw(boolean enabled) {
453        if (mInputDispatchEnabled != enabled) {
454            if (WindowManagerService.DEBUG_INPUT) {
455                Slog.v(WindowManagerService.TAG, "Setting event dispatching to " + enabled);
456            }
457
458            mInputDispatchEnabled = enabled;
459            updateInputDispatchModeLw();
460        }
461    }
462
463    private void updateInputDispatchModeLw() {
464        mService.mInputManager.setInputDispatchMode(mInputDispatchEnabled, mInputDispatchFrozen);
465    }
466}
467