blob: a4ed31c040aff02bc7183b9c55cb529ed3580922 [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
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
Jeff Brown4532e612012-04-05 14:27:12 -070017package com.android.server.input;
Jeff Brown46b9ac02010-04-22 18:58:52 -070018
Jeff Browna3bc5652012-04-17 11:42:25 -070019import com.android.internal.os.AtomicFile;
20import com.android.internal.util.FastXmlSerializer;
Jeff Brown46b9ac02010-04-22 18:58:52 -070021import com.android.internal.util.XmlUtils;
Jeff Brown89ef0722011-08-10 16:25:21 -070022import com.android.server.Watchdog;
Jeff Brown46b9ac02010-04-22 18:58:52 -070023
24import org.xmlpull.v1.XmlPullParser;
Jeff Browna3bc5652012-04-17 11:42:25 -070025import org.xmlpull.v1.XmlPullParserException;
26import org.xmlpull.v1.XmlSerializer;
Jeff Brown46b9ac02010-04-22 18:58:52 -070027
Jeff Browna3bc5652012-04-17 11:42:25 -070028import android.Manifest;
Jeff Brown6ec6f792012-04-17 16:52:41 -070029import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070030import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070031import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070032import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070033import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.pm.ActivityInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070035import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.pm.ResolveInfo;
37import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown46b9ac02010-04-22 18:58:52 -070038import android.content.res.Configuration;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070039import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070040import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070041import android.content.res.TypedArray;
42import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070043import android.database.ContentObserver;
Jeff Brown4532e612012-04-05 14:27:12 -070044import android.hardware.input.IInputManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070045import android.hardware.input.IInputDevicesChangedListener;
Jeff Brownac143512012-04-05 18:57:33 -070046import android.hardware.input.InputManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070047import android.hardware.input.KeyboardLayout;
Jeff Brown4532e612012-04-05 14:27:12 -070048import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070050import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070052import android.os.IBinder;
53import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080054import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070055import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070056import android.os.RemoteException;
Jeff Brown1a84fd12011-06-02 01:26:32 -070057import android.provider.Settings;
58import android.provider.Settings.SettingNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070059import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070060import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070062import android.util.Xml;
63import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070064import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070065import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080066import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070067import android.view.PointerIcon;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080069import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070070import android.view.WindowManagerPolicy;
Jeff Brown46b9ac02010-04-22 18:58:52 -070071
Jeff Browna3bc5652012-04-17 11:42:25 -070072import java.io.BufferedInputStream;
73import java.io.BufferedOutputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070075import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070076import java.io.FileNotFoundException;
Jeff Browna3bc5652012-04-17 11:42:25 -070077import java.io.FileOutputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -070078import java.io.FileReader;
79import java.io.IOException;
Jeff Browna3bc5652012-04-17 11:42:25 -070080import java.io.InputStream;
Jeff Brown6ec6f792012-04-17 16:52:41 -070081import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082import java.io.PrintWriter;
83import java.util.ArrayList;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070084import java.util.HashMap;
Jeff Browna3bc5652012-04-17 11:42:25 -070085import java.util.Map;
86
87import libcore.io.IoUtils;
Jeff Brown6ec6f792012-04-17 16:52:41 -070088import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -070089import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -070090
91/*
92 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -070093 */
Jeff Brown4532e612012-04-05 14:27:12 -070094public class InputManagerService extends IInputManager.Stub implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -070095 static final String TAG = "InputManager";
Jeff Brown6ec6f792012-04-17 16:52:41 -070096 static final boolean DEBUG = true;
Jeff Brownb6997262010-10-08 22:31:17 -070097
Jeff Brown4532e612012-04-05 14:27:12 -070098 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
99
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700100 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
101
Jeff Brown4532e612012-04-05 14:27:12 -0700102 // Pointer to native input manager service object.
103 private final int mPtr;
104
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105 private final Context mContext;
Jeff Brown4532e612012-04-05 14:27:12 -0700106 private final Callbacks mCallbacks;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700107 private final InputManagerHandler mHandler;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700108 private boolean mSystemReady;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700109
Jeff Browna3bc5652012-04-17 11:42:25 -0700110 // Persistent data store. Must be locked each time during use.
111 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700112
113 // List of currently registered input devices changed listeners by process id.
114 private Object mInputDevicesLock = new Object();
115 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
116 private InputDevice[] mInputDevices = new InputDevice[0];
117 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
118 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
119 private final ArrayList<InputDevicesChangedListenerRecord>
120 mTempInputDevicesChangedListenersToNotify =
121 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
122
Jeff Browna47425a2012-04-13 04:09:27 -0700123 // State for vibrator tokens.
124 private Object mVibratorLock = new Object();
125 private HashMap<IBinder, VibratorToken> mVibratorTokens =
126 new HashMap<IBinder, VibratorToken>();
127 private int mNextVibratorTokenValue;
128
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700129 // State for the currently installed input filter.
130 final Object mInputFilterLock = new Object();
131 InputFilter mInputFilter; // guarded by mInputFilterLock
132 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700133
Jeff Brown4532e612012-04-05 14:27:12 -0700134 private static native int nativeInit(InputManagerService service,
135 Context context, MessageQueue messageQueue);
136 private static native void nativeStart(int ptr);
137 private static native void nativeSetDisplaySize(int ptr, int displayId,
138 int width, int height, int externalWidth, int externalHeight);
139 private static native void nativeSetDisplayOrientation(int ptr, int displayId, int rotation);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700140
Jeff Brown4532e612012-04-05 14:27:12 -0700141 private static native int nativeGetScanCodeState(int ptr,
142 int deviceId, int sourceMask, int scanCode);
143 private static native int nativeGetKeyCodeState(int ptr,
144 int deviceId, int sourceMask, int keyCode);
145 private static native int nativeGetSwitchState(int ptr,
146 int deviceId, int sourceMask, int sw);
147 private static native boolean nativeHasKeys(int ptr,
148 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
149 private static native void nativeRegisterInputChannel(int ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800150 InputWindowHandle inputWindowHandle, boolean monitor);
Jeff Brown4532e612012-04-05 14:27:12 -0700151 private static native void nativeUnregisterInputChannel(int ptr, InputChannel inputChannel);
152 private static native void nativeSetInputFilterEnabled(int ptr, boolean enable);
153 private static native int nativeInjectInputEvent(int ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700154 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
155 int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -0700156 private static native void nativeSetInputWindows(int ptr, InputWindowHandle[] windowHandles);
157 private static native void nativeSetInputDispatchMode(int ptr, boolean enabled, boolean frozen);
158 private static native void nativeSetSystemUiVisibility(int ptr, int visibility);
159 private static native void nativeSetFocusedApplication(int ptr,
160 InputApplicationHandle application);
Jeff Brown4532e612012-04-05 14:27:12 -0700161 private static native void nativeGetInputConfiguration(int ptr, Configuration configuration);
Jeff Brown4532e612012-04-05 14:27:12 -0700162 private static native boolean nativeTransferTouchFocus(int ptr,
163 InputChannel fromChannel, InputChannel toChannel);
164 private static native void nativeSetPointerSpeed(int ptr, int speed);
165 private static native void nativeSetShowTouches(int ptr, boolean enabled);
Jeff Browna47425a2012-04-13 04:09:27 -0700166 private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
167 int repeat, int token);
168 private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700169 private static native void nativeReloadKeyboardLayouts(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700170 private static native String nativeDump(int ptr);
171 private static native void nativeMonitor(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700172
Jeff Brownac143512012-04-05 18:57:33 -0700173 // Input event injection constants defined in InputDispatcher.h.
174 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
175 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
176 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
177 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
178
179 // Maximum number of milliseconds to wait for input event injection.
180 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
181
Jeff Brown6d0fec22010-07-23 21:28:06 -0700182 // Key states (may be returned by queries about the current state of a
183 // particular key code, scan code or switch).
184
185 /** The key state is unknown or the requested key itself is not supported. */
186 public static final int KEY_STATE_UNKNOWN = -1;
187
188 /** The key is up. /*/
189 public static final int KEY_STATE_UP = 0;
190
191 /** The key is down. */
192 public static final int KEY_STATE_DOWN = 1;
193
194 /** The key is down but is a virtual key press that is being emulated by the system. */
195 public static final int KEY_STATE_VIRTUAL = 2;
196
Jeff Brown4532e612012-04-05 14:27:12 -0700197 public InputManagerService(Context context, Callbacks callbacks) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700198 this.mContext = context;
Jeff Brown4532e612012-04-05 14:27:12 -0700199 this.mCallbacks = callbacks;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700200 this.mHandler = new InputManagerHandler();
Jeff Brown05dc66a2011-03-02 14:41:58 -0800201
Jeff Brown46b9ac02010-04-22 18:58:52 -0700202 Slog.i(TAG, "Initializing input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700203 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700204 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700205
Jeff Brown46b9ac02010-04-22 18:58:52 -0700206 public void start() {
207 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700208 nativeStart(mPtr);
209
210 // Add ourself to the Watchdog monitors.
211 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700212
213 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700214 registerShowTouchesSettingObserver();
215
Jeff Brown1a84fd12011-06-02 01:26:32 -0700216 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700217 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700218 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700219
220 public void systemReady() {
221 if (DEBUG) {
222 Slog.d(TAG, "System ready.");
223 }
224 mSystemReady = true;
225 reloadKeyboardLayouts();
226
227 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
228 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
229 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
230 filter.addDataScheme("package");
231 mContext.registerReceiver(new BroadcastReceiver() {
232 @Override
233 public void onReceive(Context context, Intent intent) {
234 if (DEBUG) {
235 Slog.d(TAG, "Packages changed, reloading keyboard layouts.");
236 }
237 reloadKeyboardLayouts();
238 }
239 }, filter, null, mHandler);
240 }
241
242 private void reloadKeyboardLayouts() {
243 nativeReloadKeyboardLayouts(mPtr);
244 }
245
Jeff Brownbc68a592011-07-25 12:58:12 -0700246 public void setDisplaySize(int displayId, int width, int height,
247 int externalWidth, int externalHeight) {
248 if (width <= 0 || height <= 0 || externalWidth <= 0 || externalHeight <= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700249 throw new IllegalArgumentException("Invalid display id or dimensions.");
250 }
251
Jeff Brownb6997262010-10-08 22:31:17 -0700252 if (DEBUG) {
Jeff Brownbc68a592011-07-25 12:58:12 -0700253 Slog.d(TAG, "Setting display #" + displayId + " size to " + width + "x" + height
254 + " external size " + externalWidth + "x" + externalHeight);
Jeff Brownb6997262010-10-08 22:31:17 -0700255 }
Jeff Brown4532e612012-04-05 14:27:12 -0700256 nativeSetDisplaySize(mPtr, displayId, width, height, externalWidth, externalHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700257 }
258
259 public void setDisplayOrientation(int displayId, int rotation) {
260 if (rotation < Surface.ROTATION_0 || rotation > Surface.ROTATION_270) {
261 throw new IllegalArgumentException("Invalid rotation.");
262 }
263
Jeff Brownb6997262010-10-08 22:31:17 -0700264 if (DEBUG) {
265 Slog.d(TAG, "Setting display #" + displayId + " orientation to " + rotation);
266 }
Jeff Brown4532e612012-04-05 14:27:12 -0700267 nativeSetDisplayOrientation(mPtr, displayId, rotation);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700268 }
269
270 public void getInputConfiguration(Configuration config) {
271 if (config == null) {
272 throw new IllegalArgumentException("config must not be null.");
273 }
274
Jeff Brown4532e612012-04-05 14:27:12 -0700275 nativeGetInputConfiguration(mPtr, config);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700276 }
Jeff Brownac143512012-04-05 18:57:33 -0700277
Jeff Brown6d0fec22010-07-23 21:28:06 -0700278 /**
279 * Gets the current state of a key or button by key code.
280 * @param deviceId The input device id, or -1 to consult all devices.
281 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
282 * consider all input sources. An input device is consulted if at least one of its
283 * non-class input source bits matches the specified source mask.
284 * @param keyCode The key code to check.
285 * @return The key state.
286 */
287 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700288 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700289 }
290
Jeff Brown6d0fec22010-07-23 21:28:06 -0700291 /**
292 * Gets the current state of a key or button by scan code.
293 * @param deviceId The input device id, or -1 to consult all devices.
294 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
295 * consider all input sources. An input device is consulted if at least one of its
296 * non-class input source bits matches the specified source mask.
297 * @param scanCode The scan code to check.
298 * @return The key state.
299 */
300 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700301 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700302 }
303
Jeff Brown6d0fec22010-07-23 21:28:06 -0700304 /**
305 * Gets the current state of a switch by switch code.
306 * @param deviceId The input device id, or -1 to consult all devices.
307 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
308 * consider all input sources. An input device is consulted if at least one of its
309 * non-class input source bits matches the specified source mask.
310 * @param switchCode The switch code to check.
311 * @return The switch state.
312 */
313 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700314 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700315 }
316
Jeff Brown6d0fec22010-07-23 21:28:06 -0700317 /**
318 * Determines whether the specified key codes are supported by a particular device.
319 * @param deviceId The input device id, or -1 to consult all devices.
320 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
321 * consider all input sources. An input device is consulted if at least one of its
322 * non-class input source bits matches the specified source mask.
323 * @param keyCodes The array of key codes to check.
324 * @param keyExists An array at least as large as keyCodes whose entries will be set
325 * to true or false based on the presence or absence of support for the corresponding
326 * key codes.
327 * @return True if the lookup was successful, false otherwise.
328 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700329 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700330 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700331 if (keyCodes == null) {
332 throw new IllegalArgumentException("keyCodes must not be null.");
333 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700334 if (keyExists == null || keyExists.length < keyCodes.length) {
335 throw new IllegalArgumentException("keyExists must not be null and must be at "
336 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700337 }
338
Jeff Brown4532e612012-04-05 14:27:12 -0700339 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700340 }
341
Jeff Browna41ca772010-08-11 14:46:32 -0700342 /**
343 * Creates an input channel that will receive all input from the input dispatcher.
344 * @param inputChannelName The input channel name.
345 * @return The input channel.
346 */
347 public InputChannel monitorInput(String inputChannelName) {
348 if (inputChannelName == null) {
349 throw new IllegalArgumentException("inputChannelName must not be null.");
350 }
351
352 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700353 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700354 inputChannels[0].dispose(); // don't need to retain the Java object reference
355 return inputChannels[1];
356 }
357
358 /**
359 * Registers an input channel so that it can be used as an input event target.
360 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800361 * @param inputWindowHandle The handle of the input window associated with the
362 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700363 */
Jeff Brown928e0542011-01-10 11:17:36 -0800364 public void registerInputChannel(InputChannel inputChannel,
365 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700366 if (inputChannel == null) {
367 throw new IllegalArgumentException("inputChannel must not be null.");
368 }
369
Jeff Brown4532e612012-04-05 14:27:12 -0700370 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700371 }
372
Jeff Browna41ca772010-08-11 14:46:32 -0700373 /**
374 * Unregisters an input channel.
375 * @param inputChannel The input channel to unregister.
376 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700377 public void unregisterInputChannel(InputChannel inputChannel) {
378 if (inputChannel == null) {
379 throw new IllegalArgumentException("inputChannel must not be null.");
380 }
381
Jeff Brown4532e612012-04-05 14:27:12 -0700382 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700383 }
Jeff Brown0029c662011-03-30 02:25:18 -0700384
385 /**
386 * Sets an input filter that will receive all input events before they are dispatched.
387 * The input filter may then reinterpret input events or inject new ones.
388 *
389 * To ensure consistency, the input dispatcher automatically drops all events
390 * in progress whenever an input filter is installed or uninstalled. After an input
391 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
392 * Any events it attempts to send after it has been uninstalled will be dropped.
393 *
394 * @param filter The input filter, or null to remove the current filter.
395 */
396 public void setInputFilter(InputFilter filter) {
397 synchronized (mInputFilterLock) {
398 final InputFilter oldFilter = mInputFilter;
399 if (oldFilter == filter) {
400 return; // nothing to do
401 }
402
403 if (oldFilter != null) {
404 mInputFilter = null;
405 mInputFilterHost.disconnectLocked();
406 mInputFilterHost = null;
407 oldFilter.uninstall();
408 }
409
410 if (filter != null) {
411 mInputFilter = filter;
412 mInputFilterHost = new InputFilterHost();
413 filter.install(mInputFilterHost);
414 }
415
Jeff Brown4532e612012-04-05 14:27:12 -0700416 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700417 }
418 }
419
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700420 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700421 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700422 if (event == null) {
423 throw new IllegalArgumentException("event must not be null");
424 }
Jeff Brownac143512012-04-05 18:57:33 -0700425 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
426 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
427 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
428 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700429 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700430
Jeff Brownac143512012-04-05 18:57:33 -0700431 final int pid = Binder.getCallingPid();
432 final int uid = Binder.getCallingUid();
433 final long ident = Binder.clearCallingIdentity();
434 final int result;
435 try {
436 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
437 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
438 } finally {
439 Binder.restoreCallingIdentity(ident);
440 }
441 switch (result) {
442 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
443 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
444 throw new SecurityException(
445 "Injecting to another application requires INJECT_EVENTS permission");
446 case INPUT_EVENT_INJECTION_SUCCEEDED:
447 return true;
448 case INPUT_EVENT_INJECTION_TIMED_OUT:
449 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
450 return false;
451 case INPUT_EVENT_INJECTION_FAILED:
452 default:
453 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
454 return false;
455 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700456 }
Jeff Brown0029c662011-03-30 02:25:18 -0700457
Jeff Brown8d608662010-08-30 03:02:23 -0700458 /**
459 * Gets information about the input device with the specified id.
460 * @param id The device id.
461 * @return The input device or null if not found.
462 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700463 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700464 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700465 synchronized (mInputDevicesLock) {
466 final int count = mInputDevices.length;
467 for (int i = 0; i < count; i++) {
468 final InputDevice inputDevice = mInputDevices[i];
469 if (inputDevice.getId() == deviceId) {
470 return inputDevice;
471 }
472 }
473 }
474 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700475 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700476
Jeff Brown8d608662010-08-30 03:02:23 -0700477 /**
478 * Gets the ids of all input devices in the system.
479 * @return The input device ids.
480 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700481 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700482 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700483 synchronized (mInputDevicesLock) {
484 final int count = mInputDevices.length;
485 int[] ids = new int[count];
486 for (int i = 0; i < count; i++) {
487 ids[i] = mInputDevices[i].getId();
488 }
489 return ids;
490 }
491 }
492
493 @Override // Binder call
494 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
495 if (listener == null) {
496 throw new IllegalArgumentException("listener must not be null");
497 }
498
499 synchronized (mInputDevicesLock) {
500 int callingPid = Binder.getCallingPid();
501 if (mInputDevicesChangedListeners.get(callingPid) != null) {
502 throw new SecurityException("The calling process has already "
503 + "registered an InputDevicesChangedListener.");
504 }
505
506 InputDevicesChangedListenerRecord record =
507 new InputDevicesChangedListenerRecord(callingPid, listener);
508 try {
509 IBinder binder = listener.asBinder();
510 binder.linkToDeath(record, 0);
511 } catch (RemoteException ex) {
512 // give up
513 throw new RuntimeException(ex);
514 }
515
516 mInputDevicesChangedListeners.put(callingPid, record);
517 }
518 }
519
520 private void onInputDevicesChangedListenerDied(int pid) {
521 synchronized (mInputDevicesLock) {
522 mInputDevicesChangedListeners.remove(pid);
523 }
524 }
525
526 // Must be called on handler.
527 private void deliverInputDevicesChanged() {
528 mTempInputDevicesChangedListenersToNotify.clear();
529
530 final int numListeners;
531 final int[] deviceIdAndGeneration;
532 synchronized (mInputDevicesLock) {
533 if (!mInputDevicesChangedPending) {
534 return;
535 }
536 mInputDevicesChangedPending = false;
537
538 numListeners = mInputDevicesChangedListeners.size();
539 for (int i = 0; i < numListeners; i++) {
540 mTempInputDevicesChangedListenersToNotify.add(
541 mInputDevicesChangedListeners.valueAt(i));
542 }
543
544 final int numDevices = mInputDevices.length;
545 deviceIdAndGeneration = new int[numDevices * 2];
546 for (int i = 0; i < numDevices; i++) {
547 final InputDevice inputDevice = mInputDevices[i];
548 deviceIdAndGeneration[i * 2] = inputDevice.getId();
549 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
550 }
551 }
552
553 for (int i = 0; i < numListeners; i++) {
554 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
555 deviceIdAndGeneration);
556 }
Jeff Brown8d608662010-08-30 03:02:23 -0700557 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700558
559 @Override // Binder call
560 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700561 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
562 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
563 @Override
564 public void visitKeyboardLayout(Resources resources,
565 String descriptor, String label, int kcmResId) {
566 list.add(new KeyboardLayout(descriptor, label));
567 }
568 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700569 return list.toArray(new KeyboardLayout[list.size()]);
570 }
571
572 @Override // Binder call
573 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
574 if (keyboardLayoutDescriptor == null) {
575 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
576 }
577
Jeff Brown6ec6f792012-04-17 16:52:41 -0700578 final KeyboardLayout[] result = new KeyboardLayout[1];
579 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
580 @Override
581 public void visitKeyboardLayout(Resources resources,
582 String descriptor, String label, int kcmResId) {
583 result[0] = new KeyboardLayout(descriptor, label);
584 }
585 });
586 if (result[0] == null) {
587 Log.w(TAG, "Could not get keyboard layout with descriptor '"
588 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700589 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700590 return result[0];
591 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700592
Jeff Brown6ec6f792012-04-17 16:52:41 -0700593 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700594 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700595 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
596 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
597 PackageManager.GET_META_DATA)) {
598 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700599 }
600 }
601
Jeff Brown6ec6f792012-04-17 16:52:41 -0700602 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
603 KeyboardLayoutVisitor visitor) {
604 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
605 if (d != null) {
606 final PackageManager pm = mContext.getPackageManager();
607 try {
608 ActivityInfo receiver = pm.getReceiverInfo(
609 new ComponentName(d.packageName, d.receiverName),
610 PackageManager.GET_META_DATA);
611 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
612 } catch (NameNotFoundException ex) {
613 }
614 }
615 }
616
617 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
618 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700619 Bundle metaData = receiver.metaData;
620 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700621 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700622 }
623
624 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
625 if (configResId == 0) {
626 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
627 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700628 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700629 }
630
631 try {
632 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
633 XmlResourceParser parser = resources.getXml(configResId);
634 try {
635 XmlUtils.beginDocument(parser, "keyboard-layouts");
636
637 for (;;) {
638 XmlUtils.nextElement(parser);
639 String element = parser.getName();
640 if (element == null) {
641 break;
642 }
643 if (element.equals("keyboard-layout")) {
644 TypedArray a = resources.obtainAttributes(
645 parser, com.android.internal.R.styleable.KeyboardLayout);
646 try {
647 String name = a.getString(
648 com.android.internal.R.styleable.KeyboardLayout_name);
649 String label = a.getString(
650 com.android.internal.R.styleable.KeyboardLayout_label);
651 int kcmResId = a.getResourceId(
652 com.android.internal.R.styleable.KeyboardLayout_kcm, 0);
653 if (name == null || label == null || kcmResId == 0) {
654 Log.w(TAG, "Missing required 'name', 'label' or 'kcm' "
655 + "attributes in keyboard layout "
656 + "resource from receiver "
657 + receiver.packageName + "/" + receiver.name);
658 } else {
659 String descriptor = KeyboardLayoutDescriptor.format(
660 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700661 if (keyboardName == null || name.equals(keyboardName)) {
662 visitor.visitKeyboardLayout(resources, descriptor,
663 label, kcmResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700664 }
665 }
666 } finally {
667 a.recycle();
668 }
669 } else {
670 Log.w(TAG, "Skipping unrecognized element '" + element
671 + "' in keyboard layout resource from receiver "
672 + receiver.packageName + "/" + receiver.name);
673 }
674 }
675 } finally {
676 parser.close();
677 }
678 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700679 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700680 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700681 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700682 }
683
684 @Override // Binder call
685 public String getKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
686 if (inputDeviceDescriptor == null) {
687 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
688 }
689
Jeff Browna3bc5652012-04-17 11:42:25 -0700690 synchronized (mDataStore) {
691 return mDataStore.getKeyboardLayout(inputDeviceDescriptor);
692 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700693 }
694
695 @Override // Binder call
696 public void setKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
697 String keyboardLayoutDescriptor) {
698 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
699 "setKeyboardLayoutForInputDevice()")) {
700 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
701 }
702
703 if (inputDeviceDescriptor == null) {
704 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
705 }
706
Jeff Brown6ec6f792012-04-17 16:52:41 -0700707 final boolean changed;
Jeff Browna3bc5652012-04-17 11:42:25 -0700708 synchronized (mDataStore) {
709 try {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700710 changed = mDataStore.setKeyboardLayout(
711 inputDeviceDescriptor, keyboardLayoutDescriptor);
Jeff Browna3bc5652012-04-17 11:42:25 -0700712 } finally {
713 mDataStore.saveIfNeeded();
714 }
715 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700716
717 if (changed) {
718 if (DEBUG) {
719 Slog.d(TAG, "Keyboard layout changed, reloading keyboard layouts.");
720 }
721 reloadKeyboardLayouts();
722 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700723 }
724
Jeff Brown9302c872011-07-13 22:51:29 -0700725 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -0700726 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -0700727 }
728
Jeff Brown9302c872011-07-13 22:51:29 -0700729 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -0700730 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -0700731 }
732
Jeff Brown349703e2010-06-22 01:27:15 -0700733 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -0700734 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -0700735 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800736
737 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -0700738 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -0800739 }
740
Jeff Browne6504122010-09-27 14:52:15 -0700741 /**
742 * Atomically transfers touch focus from one window to another as identified by
743 * their input channels. It is possible for multiple windows to have
744 * touch focus if they support split touch dispatch
745 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
746 * method only transfers touch focus of the specified window without affecting
747 * other windows that may also have touch focus at the same time.
748 * @param fromChannel The channel of a window that currently has touch focus.
749 * @param toChannel The channel of the window that should receive touch focus in
750 * place of the first.
751 * @return True if the transfer was successful. False if the window with the
752 * specified channel did not actually have touch focus at the time of the request.
753 */
754 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
755 if (fromChannel == null) {
756 throw new IllegalArgumentException("fromChannel must not be null.");
757 }
758 if (toChannel == null) {
759 throw new IllegalArgumentException("toChannel must not be null.");
760 }
Jeff Brown4532e612012-04-05 14:27:12 -0700761 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -0700762 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800763
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700764 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700765 public void tryPointerSpeed(int speed) {
766 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
767 "tryPointerSpeed()")) {
768 throw new SecurityException("Requires SET_POINTER_SPEED permission");
769 }
770
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700771 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
772 throw new IllegalArgumentException("speed out of range");
773 }
774
Jeff Brownac143512012-04-05 18:57:33 -0700775 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700776 }
777
778 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -0700779 int speed = getPointerSpeedSetting();
780 setPointerSpeedUnchecked(speed);
781 }
782
783 private void setPointerSpeedUnchecked(int speed) {
784 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
785 InputManager.MAX_POINTER_SPEED);
786 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700787 }
788
789 private void registerPointerSpeedSettingObserver() {
790 mContext.getContentResolver().registerContentObserver(
791 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700792 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -0700793 @Override
794 public void onChange(boolean selfChange) {
795 updatePointerSpeedFromSettings();
796 }
797 });
798 }
799
Jeff Brownac143512012-04-05 18:57:33 -0700800 private int getPointerSpeedSetting() {
801 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -0700802 try {
803 speed = Settings.System.getInt(mContext.getContentResolver(),
804 Settings.System.POINTER_SPEED);
805 } catch (SettingNotFoundException snfe) {
806 }
807 return speed;
808 }
809
Jeff Browndaf4a122011-08-26 17:14:14 -0700810 public void updateShowTouchesFromSettings() {
811 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -0700812 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -0700813 }
814
815 private void registerShowTouchesSettingObserver() {
816 mContext.getContentResolver().registerContentObserver(
817 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700818 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -0700819 @Override
820 public void onChange(boolean selfChange) {
821 updateShowTouchesFromSettings();
822 }
823 });
824 }
825
826 private int getShowTouchesSetting(int defaultValue) {
827 int result = defaultValue;
828 try {
829 result = Settings.System.getInt(mContext.getContentResolver(),
830 Settings.System.SHOW_TOUCHES);
831 } catch (SettingNotFoundException snfe) {
832 }
833 return result;
834 }
835
Jeff Browna47425a2012-04-13 04:09:27 -0700836 // Binder call
837 @Override
838 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
839 if (repeat >= pattern.length) {
840 throw new ArrayIndexOutOfBoundsException();
841 }
842
843 VibratorToken v;
844 synchronized (mVibratorLock) {
845 v = mVibratorTokens.get(token);
846 if (v == null) {
847 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
848 try {
849 token.linkToDeath(v, 0);
850 } catch (RemoteException ex) {
851 // give up
852 throw new RuntimeException(ex);
853 }
854 mVibratorTokens.put(token, v);
855 }
856 }
857
858 synchronized (v) {
859 v.mVibrating = true;
860 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
861 }
862 }
863
864 // Binder call
865 @Override
866 public void cancelVibrate(int deviceId, IBinder token) {
867 VibratorToken v;
868 synchronized (mVibratorLock) {
869 v = mVibratorTokens.get(token);
870 if (v == null || v.mDeviceId != deviceId) {
871 return; // nothing to cancel
872 }
873 }
874
875 cancelVibrateIfNeeded(v);
876 }
877
878 void onVibratorTokenDied(VibratorToken v) {
879 synchronized (mVibratorLock) {
880 mVibratorTokens.remove(v.mToken);
881 }
882
883 cancelVibrateIfNeeded(v);
884 }
885
886 private void cancelVibrateIfNeeded(VibratorToken v) {
887 synchronized (v) {
888 if (v.mVibrating) {
889 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
890 v.mVibrating = false;
891 }
892 }
893 }
894
Jeff Brown4532e612012-04-05 14:27:12 -0700895 @Override
896 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -0700897 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -0700898 != PackageManager.PERMISSION_GRANTED) {
899 pw.println("Permission Denial: can't dump InputManager from from pid="
900 + Binder.getCallingPid()
901 + ", uid=" + Binder.getCallingUid());
902 return;
903 }
904
905 pw.println("INPUT MANAGER (dumpsys input)\n");
906 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -0700907 if (dumpStr != null) {
908 pw.println(dumpStr);
909 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700910 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -0800911
Jeff Brownac143512012-04-05 18:57:33 -0700912 private boolean checkCallingPermission(String permission, String func) {
913 // Quick check: if the calling permission is me, it's all okay.
914 if (Binder.getCallingPid() == Process.myPid()) {
915 return true;
916 }
917
918 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
919 return true;
920 }
921 String msg = "Permission Denial: " + func + " from pid="
922 + Binder.getCallingPid()
923 + ", uid=" + Binder.getCallingUid()
924 + " requires " + permission;
925 Slog.w(TAG, msg);
926 return false;
927 }
928
Jeff Brown4532e612012-04-05 14:27:12 -0700929 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Jeff Brown89ef0722011-08-10 16:25:21 -0700930 public void monitor() {
931 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -0700932 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -0700933 }
934
Jeff Brown4532e612012-04-05 14:27:12 -0700935 // Native callback.
936 private void notifyConfigurationChanged(long whenNanos) {
937 mCallbacks.notifyConfigurationChanged();
938 }
939
940 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700941 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
942 synchronized (mInputDevicesLock) {
943 mInputDevices = inputDevices;
944
945 if (!mInputDevicesChangedPending) {
946 mInputDevicesChangedPending = true;
947 mHandler.sendEmptyMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED);
948 }
949 }
950 }
951
952 // Native callback.
Jeff Brown4532e612012-04-05 14:27:12 -0700953 private void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
954 mCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
955 }
956
957 // Native callback.
958 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
959 mCallbacks.notifyInputChannelBroken(inputWindowHandle);
960 }
961
962 // Native callback.
963 private long notifyANR(InputApplicationHandle inputApplicationHandle,
964 InputWindowHandle inputWindowHandle) {
965 return mCallbacks.notifyANR(inputApplicationHandle, inputWindowHandle);
966 }
967
968 // Native callback.
969 final boolean filterInputEvent(InputEvent event, int policyFlags) {
970 synchronized (mInputFilterLock) {
971 if (mInputFilter != null) {
972 mInputFilter.filterInputEvent(event, policyFlags);
973 return false;
974 }
975 }
976 event.recycle();
977 return true;
978 }
979
980 // Native callback.
981 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
982 return mCallbacks.interceptKeyBeforeQueueing(
983 event, policyFlags, isScreenOn);
984 }
985
986 // Native callback.
987 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
988 return mCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
989 }
990
991 // Native callback.
992 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
993 KeyEvent event, int policyFlags) {
994 return mCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
995 }
996
997 // Native callback.
998 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
999 KeyEvent event, int policyFlags) {
1000 return mCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
1001 }
1002
1003 // Native callback.
1004 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1005 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1006 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1007 }
1008
1009 // Native callback.
1010 private int getVirtualKeyQuietTimeMillis() {
1011 return mContext.getResources().getInteger(
1012 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1013 }
1014
1015 // Native callback.
1016 private String[] getExcludedDeviceNames() {
1017 ArrayList<String> names = new ArrayList<String>();
1018
1019 // Read partner-provided list of excluded input devices
1020 XmlPullParser parser = null;
1021 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1022 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1023 FileReader confreader = null;
1024 try {
1025 confreader = new FileReader(confFile);
1026 parser = Xml.newPullParser();
1027 parser.setInput(confreader);
1028 XmlUtils.beginDocument(parser, "devices");
1029
1030 while (true) {
1031 XmlUtils.nextElement(parser);
1032 if (!"device".equals(parser.getName())) {
1033 break;
1034 }
1035 String name = parser.getAttributeValue(null, "name");
1036 if (name != null) {
1037 names.add(name);
1038 }
1039 }
1040 } catch (FileNotFoundException e) {
1041 // It's ok if the file does not exist.
1042 } catch (Exception e) {
1043 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1044 } finally {
1045 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1046 }
1047
1048 return names.toArray(new String[names.size()]);
1049 }
1050
1051 // Native callback.
1052 private int getKeyRepeatTimeout() {
1053 return ViewConfiguration.getKeyRepeatTimeout();
1054 }
1055
1056 // Native callback.
1057 private int getKeyRepeatDelay() {
1058 return ViewConfiguration.getKeyRepeatDelay();
1059 }
1060
1061 // Native callback.
1062 private int getHoverTapTimeout() {
1063 return ViewConfiguration.getHoverTapTimeout();
1064 }
1065
1066 // Native callback.
1067 private int getHoverTapSlop() {
1068 return ViewConfiguration.getHoverTapSlop();
1069 }
1070
1071 // Native callback.
1072 private int getDoubleTapTimeout() {
1073 return ViewConfiguration.getDoubleTapTimeout();
1074 }
1075
1076 // Native callback.
1077 private int getLongPressTimeout() {
1078 return ViewConfiguration.getLongPressTimeout();
1079 }
1080
1081 // Native callback.
1082 private int getPointerLayer() {
1083 return mCallbacks.getPointerLayer();
1084 }
1085
1086 // Native callback.
1087 private PointerIcon getPointerIcon() {
1088 return PointerIcon.getDefaultIcon(mContext);
1089 }
1090
Jeff Brown6ec6f792012-04-17 16:52:41 -07001091 // Native callback.
1092 private String[] getKeyboardLayoutOverlay(String inputDeviceDescriptor) {
1093 if (!mSystemReady) {
1094 return null;
1095 }
1096
1097 String keyboardLayoutDescriptor = getKeyboardLayoutForInputDevice(inputDeviceDescriptor);
1098 if (keyboardLayoutDescriptor == null) {
1099 return null;
1100 }
1101
1102 final String[] result = new String[2];
1103 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1104 @Override
1105 public void visitKeyboardLayout(Resources resources,
1106 String descriptor, String label, int kcmResId) {
1107 try {
1108 result[0] = descriptor;
1109 result[1] = Streams.readFully(new InputStreamReader(
1110 resources.openRawResource(kcmResId)));
1111 } catch (IOException ex) {
1112 } catch (NotFoundException ex) {
1113 }
1114 }
1115 });
1116 if (result[0] == null) {
1117 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1118 + keyboardLayoutDescriptor + "'.");
1119 return null;
1120 }
1121 return result;
1122 }
1123
1124
Jeff Brown4532e612012-04-05 14:27:12 -07001125 /**
1126 * Callback interface implemented by the Window Manager.
1127 */
1128 public interface Callbacks {
1129 public void notifyConfigurationChanged();
1130
1131 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1132
1133 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1134
1135 public long notifyANR(InputApplicationHandle inputApplicationHandle,
1136 InputWindowHandle inputWindowHandle);
1137
1138 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1139
1140 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1141
1142 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1143 KeyEvent event, int policyFlags);
1144
1145 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1146 KeyEvent event, int policyFlags);
1147
1148 public int getPointerLayer();
1149 }
1150
1151 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001152 * Private handler for the input manager.
1153 */
1154 private final class InputManagerHandler extends Handler {
1155 @Override
1156 public void handleMessage(Message msg) {
1157 switch (msg.what) {
1158 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
1159 deliverInputDevicesChanged();
1160 break;
1161 }
1162 }
1163 }
1164
1165 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001166 * Hosting interface for input filters to call back into the input manager.
1167 */
Jeff Brown0029c662011-03-30 02:25:18 -07001168 private final class InputFilterHost implements InputFilter.Host {
1169 private boolean mDisconnected;
1170
1171 public void disconnectLocked() {
1172 mDisconnected = true;
1173 }
1174
1175 public void sendInputEvent(InputEvent event, int policyFlags) {
1176 if (event == null) {
1177 throw new IllegalArgumentException("event must not be null");
1178 }
1179
1180 synchronized (mInputFilterLock) {
1181 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001182 nativeInjectInputEvent(mPtr, event, 0, 0,
1183 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001184 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1185 }
1186 }
1187 }
1188 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001189
1190 private static final class KeyboardLayoutDescriptor {
1191 public String packageName;
1192 public String receiverName;
1193 public String keyboardLayoutName;
1194
1195 public static String format(String packageName,
1196 String receiverName, String keyboardName) {
1197 return packageName + "/" + receiverName + "/" + keyboardName;
1198 }
1199
1200 public static KeyboardLayoutDescriptor parse(String descriptor) {
1201 int pos = descriptor.indexOf('/');
1202 if (pos < 0 || pos + 1 == descriptor.length()) {
1203 return null;
1204 }
1205 int pos2 = descriptor.indexOf('/', pos + 1);
1206 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1207 return null;
1208 }
1209
1210 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1211 result.packageName = descriptor.substring(0, pos);
1212 result.receiverName = descriptor.substring(pos + 1, pos2);
1213 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1214 return result;
1215 }
1216 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001217
Jeff Brown6ec6f792012-04-17 16:52:41 -07001218 private interface KeyboardLayoutVisitor {
1219 void visitKeyboardLayout(Resources resources,
1220 String descriptor, String label, int kcmResId);
1221 }
1222
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001223 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1224 private final int mPid;
1225 private final IInputDevicesChangedListener mListener;
1226
1227 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1228 mPid = pid;
1229 mListener = listener;
1230 }
1231
1232 @Override
1233 public void binderDied() {
1234 if (DEBUG) {
1235 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1236 }
1237 onInputDevicesChangedListenerDied(mPid);
1238 }
1239
1240 public void notifyInputDevicesChanged(int[] info) {
1241 try {
1242 mListener.onInputDevicesChanged(info);
1243 } catch (RemoteException ex) {
1244 Slog.w(TAG, "Failed to notify process "
1245 + mPid + " that input devices changed, assuming it died.", ex);
1246 binderDied();
1247 }
1248 }
1249 }
Jeff Browna47425a2012-04-13 04:09:27 -07001250
1251 private final class VibratorToken implements DeathRecipient {
1252 public final int mDeviceId;
1253 public final IBinder mToken;
1254 public final int mTokenValue;
1255
1256 public boolean mVibrating;
1257
1258 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1259 mDeviceId = deviceId;
1260 mToken = token;
1261 mTokenValue = tokenValue;
1262 }
1263
1264 @Override
1265 public void binderDied() {
1266 if (DEBUG) {
1267 Slog.d(TAG, "Vibrator token died.");
1268 }
1269 onVibratorTokenDied(this);
1270 }
1271 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001272
1273 /**
1274 * Manages persistent state recorded by the input manager service as an XML file.
1275 * Caller must acquire lock on the data store before accessing it.
1276 *
1277 * File format:
1278 * <code>
1279 * &lt;input-mananger-state>
1280 * &lt;input-devices>
1281 * &lt;input-device descriptor="xxxxx" keyboard-layout="yyyyy" />
1282 * &gt;input-devices>
1283 * &gt;/input-manager-state>
1284 * </code>
1285 */
1286 private static final class PersistentDataStore {
1287 // Input device state by descriptor.
1288 private final HashMap<String, InputDeviceState> mInputDevices =
1289 new HashMap<String, InputDeviceState>();
1290 private final AtomicFile mAtomicFile;
1291
1292 // True if the data has been loaded.
1293 private boolean mLoaded;
1294
1295 // True if there are changes to be saved.
1296 private boolean mDirty;
1297
1298 public PersistentDataStore() {
1299 mAtomicFile = new AtomicFile(new File("/data/system/input-manager-state.xml"));
1300 }
1301
1302 public void saveIfNeeded() {
1303 if (mDirty) {
1304 save();
1305 mDirty = false;
1306 }
1307 }
1308
1309 public String getKeyboardLayout(String inputDeviceDescriptor) {
1310 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, false);
1311 return state != null ? state.keyboardLayoutDescriptor : null;
1312 }
1313
1314 public boolean setKeyboardLayout(String inputDeviceDescriptor,
1315 String keyboardLayoutDescriptor) {
1316 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, true);
1317 if (!Objects.equal(state.keyboardLayoutDescriptor, keyboardLayoutDescriptor)) {
1318 state.keyboardLayoutDescriptor = keyboardLayoutDescriptor;
1319 setDirty();
1320 return true;
1321 }
1322 return false;
1323 }
1324
1325 private InputDeviceState getInputDeviceState(String inputDeviceDescriptor,
1326 boolean createIfAbsent) {
1327 loadIfNeeded();
1328 InputDeviceState state = mInputDevices.get(inputDeviceDescriptor);
1329 if (state == null && createIfAbsent) {
1330 state = new InputDeviceState();
1331 mInputDevices.put(inputDeviceDescriptor, state);
1332 setDirty();
1333 }
1334 return state;
1335 }
1336
1337 private void loadIfNeeded() {
1338 if (!mLoaded) {
1339 load();
1340 mLoaded = true;
1341 }
1342 }
1343
1344 private void setDirty() {
1345 mDirty = true;
1346 }
1347
1348 private void clearState() {
1349 mInputDevices.clear();
1350 }
1351
1352 private void load() {
1353 clearState();
1354
1355 final InputStream is;
1356 try {
1357 is = mAtomicFile.openRead();
1358 } catch (FileNotFoundException ex) {
1359 return;
1360 }
1361
1362 XmlPullParser parser;
1363 try {
1364 parser = Xml.newPullParser();
1365 parser.setInput(new BufferedInputStream(is), null);
1366 loadFromXml(parser);
1367 } catch (IOException ex) {
1368 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1369 clearState();
1370 } catch (XmlPullParserException ex) {
1371 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1372 clearState();
1373 } finally {
1374 IoUtils.closeQuietly(is);
1375 }
1376 }
1377
1378 private void save() {
1379 final FileOutputStream os;
1380 try {
1381 os = mAtomicFile.startWrite();
1382 boolean success = false;
1383 try {
1384 XmlSerializer serializer = new FastXmlSerializer();
1385 serializer.setOutput(new BufferedOutputStream(os), "utf-8");
1386 saveToXml(serializer);
1387 serializer.flush();
1388 success = true;
1389 } finally {
1390 if (success) {
1391 mAtomicFile.finishWrite(os);
1392 } else {
1393 mAtomicFile.failWrite(os);
1394 }
1395 }
1396 } catch (IOException ex) {
1397 Slog.w(TAG, "Failed to save input manager persistent store data.", ex);
1398 }
1399 }
1400
1401 private void loadFromXml(XmlPullParser parser)
1402 throws IOException, XmlPullParserException {
1403 XmlUtils.beginDocument(parser, "input-manager-state");
1404 final int outerDepth = parser.getDepth();
1405 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1406 if (parser.getName().equals("input-devices")) {
1407 loadInputDevicesFromXml(parser);
1408 }
1409 }
1410 }
1411
1412 private void loadInputDevicesFromXml(XmlPullParser parser)
1413 throws IOException, XmlPullParserException {
1414 final int outerDepth = parser.getDepth();
1415 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1416 if (parser.getName().equals("input-device")) {
1417 String descriptor = parser.getAttributeValue(null, "descriptor");
1418 if (descriptor == null) {
1419 throw new XmlPullParserException(
1420 "Missing descriptor attribute on input-device");
1421 }
1422 InputDeviceState state = new InputDeviceState();
1423 state.keyboardLayoutDescriptor =
1424 parser.getAttributeValue(null, "keyboard-layout");
1425 mInputDevices.put(descriptor, state);
1426 }
1427 }
1428 }
1429
1430 private void saveToXml(XmlSerializer serializer) throws IOException {
1431 serializer.startDocument(null, true);
1432 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1433 serializer.startTag(null, "input-manager-state");
1434 serializer.startTag(null, "input-devices");
1435 for (Map.Entry<String, InputDeviceState> entry : mInputDevices.entrySet()) {
1436 final String descriptor = entry.getKey();
1437 final InputDeviceState state = entry.getValue();
1438 serializer.startTag(null, "input-device");
1439 serializer.attribute(null, "descriptor", descriptor);
1440 if (state.keyboardLayoutDescriptor != null) {
1441 serializer.attribute(null, "keyboard-layout", state.keyboardLayoutDescriptor);
1442 }
1443 serializer.endTag(null, "input-device");
1444 }
1445 serializer.endTag(null, "input-devices");
1446 serializer.endTag(null, "input-manager-state");
1447 serializer.endDocument();
1448 }
1449 }
1450
1451 private static final class InputDeviceState {
1452 public String keyboardLayoutDescriptor;
1453 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001454}