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