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