blob: 117e0649d62e9d0fb8f011125135c7ce5993ba14 [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 Brown5bbd4b42012-04-20 19:28:00 -070029import android.bluetooth.BluetoothAdapter;
30import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070031import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070032import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070033import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070035import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.pm.ActivityInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070037import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.pm.ResolveInfo;
39import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown46b9ac02010-04-22 18:58:52 -070040import android.content.res.Configuration;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070041import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070042import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070043import android.content.res.TypedArray;
44import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070045import android.database.ContentObserver;
Jeff Brown4532e612012-04-05 14:27:12 -070046import android.hardware.input.IInputManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070047import android.hardware.input.IInputDevicesChangedListener;
Jeff Brownac143512012-04-05 18:57:33 -070048import android.hardware.input.InputManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.hardware.input.KeyboardLayout;
Jeff Brown4532e612012-04-05 14:27:12 -070050import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070051import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070052import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070053import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070054import android.os.IBinder;
55import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080056import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070057import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.RemoteException;
Jeff Brown1a84fd12011-06-02 01:26:32 -070059import android.provider.Settings;
60import android.provider.Settings.SettingNotFoundException;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070061import android.server.BluetoothService;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070062import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070063import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070064import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070065import android.util.Xml;
66import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070067import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070068import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080069import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070070import android.view.PointerIcon;
Jeff Brown46b9ac02010-04-22 18:58:52 -070071import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080072import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070073import android.view.WindowManagerPolicy;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074
Jeff Browna3bc5652012-04-17 11:42:25 -070075import java.io.BufferedInputStream;
76import java.io.BufferedOutputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -070077import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070078import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070079import java.io.FileNotFoundException;
Jeff Browna3bc5652012-04-17 11:42:25 -070080import java.io.FileOutputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -070081import java.io.FileReader;
82import java.io.IOException;
Jeff Browna3bc5652012-04-17 11:42:25 -070083import java.io.InputStream;
Jeff Brown6ec6f792012-04-17 16:52:41 -070084import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -070085import java.io.PrintWriter;
86import java.util.ArrayList;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070087import java.util.HashMap;
Jeff Browna3bc5652012-04-17 11:42:25 -070088import java.util.Map;
89
90import libcore.io.IoUtils;
Jeff Brown6ec6f792012-04-17 16:52:41 -070091import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -070092import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -070093
94/*
95 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -070096 */
Jeff Brown4532e612012-04-05 14:27:12 -070097public class InputManagerService extends IInputManager.Stub implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -070098 static final String TAG = "InputManager";
Jeff Brown6ec6f792012-04-17 16:52:41 -070099 static final boolean DEBUG = true;
Jeff Brownb6997262010-10-08 22:31:17 -0700100
Jeff Brown4532e612012-04-05 14:27:12 -0700101 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
102
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700103 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
104
Jeff Brown4532e612012-04-05 14:27:12 -0700105 // Pointer to native input manager service object.
106 private final int mPtr;
107
Jeff Brown46b9ac02010-04-22 18:58:52 -0700108 private final Context mContext;
Jeff Brown4532e612012-04-05 14:27:12 -0700109 private final Callbacks mCallbacks;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700110 private final InputManagerHandler mHandler;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700111 private boolean mSystemReady;
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700112 private BluetoothService mBluetoothService;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700113
Jeff Browna3bc5652012-04-17 11:42:25 -0700114 // Persistent data store. Must be locked each time during use.
115 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700116
117 // List of currently registered input devices changed listeners by process id.
118 private Object mInputDevicesLock = new Object();
119 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
120 private InputDevice[] mInputDevices = new InputDevice[0];
121 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
122 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
123 private final ArrayList<InputDevicesChangedListenerRecord>
124 mTempInputDevicesChangedListenersToNotify =
125 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
126
Jeff Browna47425a2012-04-13 04:09:27 -0700127 // State for vibrator tokens.
128 private Object mVibratorLock = new Object();
129 private HashMap<IBinder, VibratorToken> mVibratorTokens =
130 new HashMap<IBinder, VibratorToken>();
131 private int mNextVibratorTokenValue;
132
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700133 // State for the currently installed input filter.
134 final Object mInputFilterLock = new Object();
135 InputFilter mInputFilter; // guarded by mInputFilterLock
136 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700137
Jeff Brown4532e612012-04-05 14:27:12 -0700138 private static native int nativeInit(InputManagerService service,
139 Context context, MessageQueue messageQueue);
140 private static native void nativeStart(int ptr);
141 private static native void nativeSetDisplaySize(int ptr, int displayId,
142 int width, int height, int externalWidth, int externalHeight);
143 private static native void nativeSetDisplayOrientation(int ptr, int displayId, int rotation);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700144
Jeff Brown4532e612012-04-05 14:27:12 -0700145 private static native int nativeGetScanCodeState(int ptr,
146 int deviceId, int sourceMask, int scanCode);
147 private static native int nativeGetKeyCodeState(int ptr,
148 int deviceId, int sourceMask, int keyCode);
149 private static native int nativeGetSwitchState(int ptr,
150 int deviceId, int sourceMask, int sw);
151 private static native boolean nativeHasKeys(int ptr,
152 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
153 private static native void nativeRegisterInputChannel(int ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800154 InputWindowHandle inputWindowHandle, boolean monitor);
Jeff Brown4532e612012-04-05 14:27:12 -0700155 private static native void nativeUnregisterInputChannel(int ptr, InputChannel inputChannel);
156 private static native void nativeSetInputFilterEnabled(int ptr, boolean enable);
157 private static native int nativeInjectInputEvent(int ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700158 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
159 int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -0700160 private static native void nativeSetInputWindows(int ptr, InputWindowHandle[] windowHandles);
161 private static native void nativeSetInputDispatchMode(int ptr, boolean enabled, boolean frozen);
162 private static native void nativeSetSystemUiVisibility(int ptr, int visibility);
163 private static native void nativeSetFocusedApplication(int ptr,
164 InputApplicationHandle application);
Jeff Brown4532e612012-04-05 14:27:12 -0700165 private static native boolean nativeTransferTouchFocus(int ptr,
166 InputChannel fromChannel, InputChannel toChannel);
167 private static native void nativeSetPointerSpeed(int ptr, int speed);
168 private static native void nativeSetShowTouches(int ptr, boolean enabled);
Jeff Browna47425a2012-04-13 04:09:27 -0700169 private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
170 int repeat, int token);
171 private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700172 private static native void nativeReloadKeyboardLayouts(int ptr);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700173 private static native void nativeReloadDeviceAliases(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700174 private static native String nativeDump(int ptr);
175 private static native void nativeMonitor(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700176
Jeff Brownac143512012-04-05 18:57:33 -0700177 // Input event injection constants defined in InputDispatcher.h.
178 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
179 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
180 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
181 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
182
183 // Maximum number of milliseconds to wait for input event injection.
184 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
185
Jeff Brown6d0fec22010-07-23 21:28:06 -0700186 // Key states (may be returned by queries about the current state of a
187 // particular key code, scan code or switch).
188
189 /** The key state is unknown or the requested key itself is not supported. */
190 public static final int KEY_STATE_UNKNOWN = -1;
191
192 /** The key is up. /*/
193 public static final int KEY_STATE_UP = 0;
194
195 /** The key is down. */
196 public static final int KEY_STATE_DOWN = 1;
197
198 /** The key is down but is a virtual key press that is being emulated by the system. */
199 public static final int KEY_STATE_VIRTUAL = 2;
200
Jeff Brownc458ce92012-04-30 14:58:40 -0700201 /** Scan code: Mouse / trackball button. */
202 public static final int BTN_MOUSE = 0x110;
203
204 /** Switch code: Lid switch. When set, lid is shut. */
205 public static final int SW_LID = 0x00;
206
207 /** Switch code: Keypad slide. When set, keyboard is exposed. */
208 public static final int SW_KEYPAD_SLIDE = 0x0a;
209
Jeff Brown4532e612012-04-05 14:27:12 -0700210 public InputManagerService(Context context, Callbacks callbacks) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700211 this.mContext = context;
Jeff Brown4532e612012-04-05 14:27:12 -0700212 this.mCallbacks = callbacks;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700213 this.mHandler = new InputManagerHandler();
Jeff Brown05dc66a2011-03-02 14:41:58 -0800214
Jeff Brown46b9ac02010-04-22 18:58:52 -0700215 Slog.i(TAG, "Initializing input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700216 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700217 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700218
Jeff Brown46b9ac02010-04-22 18:58:52 -0700219 public void start() {
220 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700221 nativeStart(mPtr);
222
223 // Add ourself to the Watchdog monitors.
224 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700225
226 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700227 registerShowTouchesSettingObserver();
228
Jeff Brown1a84fd12011-06-02 01:26:32 -0700229 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700230 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700231 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700232
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700233 public void systemReady(BluetoothService bluetoothService) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700234 if (DEBUG) {
235 Slog.d(TAG, "System ready.");
236 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700237 mBluetoothService = bluetoothService;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700238 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700239
240 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
241 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
242 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
243 filter.addDataScheme("package");
244 mContext.registerReceiver(new BroadcastReceiver() {
245 @Override
246 public void onReceive(Context context, Intent intent) {
247 if (DEBUG) {
248 Slog.d(TAG, "Packages changed, reloading keyboard layouts.");
249 }
250 reloadKeyboardLayouts();
251 }
252 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700253
254 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
255 mContext.registerReceiver(new BroadcastReceiver() {
256 @Override
257 public void onReceive(Context context, Intent intent) {
258 if (DEBUG) {
259 Slog.d(TAG, "Bluetooth alias changed, reloading device names.");
260 }
261 reloadDeviceAliases();
262 }
263 }, filter, null, mHandler);
264
265 reloadKeyboardLayouts();
266 reloadDeviceAliases();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700267 }
268
269 private void reloadKeyboardLayouts() {
270 nativeReloadKeyboardLayouts(mPtr);
271 }
272
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700273 private void reloadDeviceAliases() {
274 nativeReloadDeviceAliases(mPtr);
275 }
276
Jeff Brownbc68a592011-07-25 12:58:12 -0700277 public void setDisplaySize(int displayId, int width, int height,
278 int externalWidth, int externalHeight) {
279 if (width <= 0 || height <= 0 || externalWidth <= 0 || externalHeight <= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700280 throw new IllegalArgumentException("Invalid display id or dimensions.");
281 }
282
Jeff Brownb6997262010-10-08 22:31:17 -0700283 if (DEBUG) {
Jeff Brownbc68a592011-07-25 12:58:12 -0700284 Slog.d(TAG, "Setting display #" + displayId + " size to " + width + "x" + height
285 + " external size " + externalWidth + "x" + externalHeight);
Jeff Brownb6997262010-10-08 22:31:17 -0700286 }
Jeff Brown4532e612012-04-05 14:27:12 -0700287 nativeSetDisplaySize(mPtr, displayId, width, height, externalWidth, externalHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700288 }
289
290 public void setDisplayOrientation(int displayId, int rotation) {
291 if (rotation < Surface.ROTATION_0 || rotation > Surface.ROTATION_270) {
292 throw new IllegalArgumentException("Invalid rotation.");
293 }
294
Jeff Brownb6997262010-10-08 22:31:17 -0700295 if (DEBUG) {
296 Slog.d(TAG, "Setting display #" + displayId + " orientation to " + rotation);
297 }
Jeff Brown4532e612012-04-05 14:27:12 -0700298 nativeSetDisplayOrientation(mPtr, displayId, rotation);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700299 }
Jeff Brownac143512012-04-05 18:57:33 -0700300
Jeff Brown6d0fec22010-07-23 21:28:06 -0700301 /**
302 * Gets the current state of a key or button by key code.
303 * @param deviceId The input device id, or -1 to consult all devices.
304 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
305 * consider all input sources. An input device is consulted if at least one of its
306 * non-class input source bits matches the specified source mask.
307 * @param keyCode The key code to check.
308 * @return The key state.
309 */
310 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700311 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700312 }
313
Jeff Brown6d0fec22010-07-23 21:28:06 -0700314 /**
315 * Gets the current state of a key or button by scan code.
316 * @param deviceId The input device id, or -1 to consult all devices.
317 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
318 * consider all input sources. An input device is consulted if at least one of its
319 * non-class input source bits matches the specified source mask.
320 * @param scanCode The scan code to check.
321 * @return The key state.
322 */
323 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700324 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700325 }
326
Jeff Brown6d0fec22010-07-23 21:28:06 -0700327 /**
328 * Gets the current state of a switch by switch code.
329 * @param deviceId The input device id, or -1 to consult all devices.
330 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
331 * consider all input sources. An input device is consulted if at least one of its
332 * non-class input source bits matches the specified source mask.
333 * @param switchCode The switch code to check.
334 * @return The switch state.
335 */
336 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700337 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700338 }
339
Jeff Brown6d0fec22010-07-23 21:28:06 -0700340 /**
341 * Determines whether the specified key codes are supported by a particular device.
342 * @param deviceId The input device id, or -1 to consult all devices.
343 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
344 * consider all input sources. An input device is consulted if at least one of its
345 * non-class input source bits matches the specified source mask.
346 * @param keyCodes The array of key codes to check.
347 * @param keyExists An array at least as large as keyCodes whose entries will be set
348 * to true or false based on the presence or absence of support for the corresponding
349 * key codes.
350 * @return True if the lookup was successful, false otherwise.
351 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700352 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700353 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700354 if (keyCodes == null) {
355 throw new IllegalArgumentException("keyCodes must not be null.");
356 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700357 if (keyExists == null || keyExists.length < keyCodes.length) {
358 throw new IllegalArgumentException("keyExists must not be null and must be at "
359 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700360 }
361
Jeff Brown4532e612012-04-05 14:27:12 -0700362 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700363 }
364
Jeff Browna41ca772010-08-11 14:46:32 -0700365 /**
366 * Creates an input channel that will receive all input from the input dispatcher.
367 * @param inputChannelName The input channel name.
368 * @return The input channel.
369 */
370 public InputChannel monitorInput(String inputChannelName) {
371 if (inputChannelName == null) {
372 throw new IllegalArgumentException("inputChannelName must not be null.");
373 }
374
375 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700376 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700377 inputChannels[0].dispose(); // don't need to retain the Java object reference
378 return inputChannels[1];
379 }
380
381 /**
382 * Registers an input channel so that it can be used as an input event target.
383 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800384 * @param inputWindowHandle The handle of the input window associated with the
385 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700386 */
Jeff Brown928e0542011-01-10 11:17:36 -0800387 public void registerInputChannel(InputChannel inputChannel,
388 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700389 if (inputChannel == null) {
390 throw new IllegalArgumentException("inputChannel must not be null.");
391 }
392
Jeff Brown4532e612012-04-05 14:27:12 -0700393 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700394 }
395
Jeff Browna41ca772010-08-11 14:46:32 -0700396 /**
397 * Unregisters an input channel.
398 * @param inputChannel The input channel to unregister.
399 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700400 public void unregisterInputChannel(InputChannel inputChannel) {
401 if (inputChannel == null) {
402 throw new IllegalArgumentException("inputChannel must not be null.");
403 }
404
Jeff Brown4532e612012-04-05 14:27:12 -0700405 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700406 }
Jeff Brown0029c662011-03-30 02:25:18 -0700407
408 /**
409 * Sets an input filter that will receive all input events before they are dispatched.
410 * The input filter may then reinterpret input events or inject new ones.
411 *
412 * To ensure consistency, the input dispatcher automatically drops all events
413 * in progress whenever an input filter is installed or uninstalled. After an input
414 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
415 * Any events it attempts to send after it has been uninstalled will be dropped.
416 *
417 * @param filter The input filter, or null to remove the current filter.
418 */
419 public void setInputFilter(InputFilter filter) {
420 synchronized (mInputFilterLock) {
421 final InputFilter oldFilter = mInputFilter;
422 if (oldFilter == filter) {
423 return; // nothing to do
424 }
425
426 if (oldFilter != null) {
427 mInputFilter = null;
428 mInputFilterHost.disconnectLocked();
429 mInputFilterHost = null;
430 oldFilter.uninstall();
431 }
432
433 if (filter != null) {
434 mInputFilter = filter;
435 mInputFilterHost = new InputFilterHost();
436 filter.install(mInputFilterHost);
437 }
438
Jeff Brown4532e612012-04-05 14:27:12 -0700439 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700440 }
441 }
442
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700443 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700444 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700445 if (event == null) {
446 throw new IllegalArgumentException("event must not be null");
447 }
Jeff Brownac143512012-04-05 18:57:33 -0700448 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
449 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
450 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
451 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700452 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700453
Jeff Brownac143512012-04-05 18:57:33 -0700454 final int pid = Binder.getCallingPid();
455 final int uid = Binder.getCallingUid();
456 final long ident = Binder.clearCallingIdentity();
457 final int result;
458 try {
459 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
460 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
461 } finally {
462 Binder.restoreCallingIdentity(ident);
463 }
464 switch (result) {
465 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
466 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
467 throw new SecurityException(
468 "Injecting to another application requires INJECT_EVENTS permission");
469 case INPUT_EVENT_INJECTION_SUCCEEDED:
470 return true;
471 case INPUT_EVENT_INJECTION_TIMED_OUT:
472 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
473 return false;
474 case INPUT_EVENT_INJECTION_FAILED:
475 default:
476 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
477 return false;
478 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700479 }
Jeff Brown0029c662011-03-30 02:25:18 -0700480
Jeff Brown8d608662010-08-30 03:02:23 -0700481 /**
482 * Gets information about the input device with the specified id.
483 * @param id The device id.
484 * @return The input device or null if not found.
485 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700486 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700487 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700488 synchronized (mInputDevicesLock) {
489 final int count = mInputDevices.length;
490 for (int i = 0; i < count; i++) {
491 final InputDevice inputDevice = mInputDevices[i];
492 if (inputDevice.getId() == deviceId) {
493 return inputDevice;
494 }
495 }
496 }
497 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700498 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700499
Jeff Brown8d608662010-08-30 03:02:23 -0700500 /**
501 * Gets the ids of all input devices in the system.
502 * @return The input device ids.
503 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700504 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700505 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700506 synchronized (mInputDevicesLock) {
507 final int count = mInputDevices.length;
508 int[] ids = new int[count];
509 for (int i = 0; i < count; i++) {
510 ids[i] = mInputDevices[i].getId();
511 }
512 return ids;
513 }
514 }
515
Jeff Browndaa37532012-05-01 15:54:03 -0700516 /**
517 * Gets all input devices in the system.
518 * @return The array of input devices.
519 */
520 public InputDevice[] getInputDevices() {
521 synchronized (mInputDevicesLock) {
522 return mInputDevices;
523 }
524 }
525
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700526 @Override // Binder call
527 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
528 if (listener == null) {
529 throw new IllegalArgumentException("listener must not be null");
530 }
531
532 synchronized (mInputDevicesLock) {
533 int callingPid = Binder.getCallingPid();
534 if (mInputDevicesChangedListeners.get(callingPid) != null) {
535 throw new SecurityException("The calling process has already "
536 + "registered an InputDevicesChangedListener.");
537 }
538
539 InputDevicesChangedListenerRecord record =
540 new InputDevicesChangedListenerRecord(callingPid, listener);
541 try {
542 IBinder binder = listener.asBinder();
543 binder.linkToDeath(record, 0);
544 } catch (RemoteException ex) {
545 // give up
546 throw new RuntimeException(ex);
547 }
548
549 mInputDevicesChangedListeners.put(callingPid, record);
550 }
551 }
552
553 private void onInputDevicesChangedListenerDied(int pid) {
554 synchronized (mInputDevicesLock) {
555 mInputDevicesChangedListeners.remove(pid);
556 }
557 }
558
559 // Must be called on handler.
560 private void deliverInputDevicesChanged() {
561 mTempInputDevicesChangedListenersToNotify.clear();
562
563 final int numListeners;
564 final int[] deviceIdAndGeneration;
565 synchronized (mInputDevicesLock) {
566 if (!mInputDevicesChangedPending) {
567 return;
568 }
569 mInputDevicesChangedPending = false;
570
571 numListeners = mInputDevicesChangedListeners.size();
572 for (int i = 0; i < numListeners; i++) {
573 mTempInputDevicesChangedListenersToNotify.add(
574 mInputDevicesChangedListeners.valueAt(i));
575 }
576
577 final int numDevices = mInputDevices.length;
578 deviceIdAndGeneration = new int[numDevices * 2];
579 for (int i = 0; i < numDevices; i++) {
580 final InputDevice inputDevice = mInputDevices[i];
581 deviceIdAndGeneration[i * 2] = inputDevice.getId();
582 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
583 }
584 }
585
586 for (int i = 0; i < numListeners; i++) {
587 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
588 deviceIdAndGeneration);
589 }
Jeff Brown8d608662010-08-30 03:02:23 -0700590 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700591
592 @Override // Binder call
593 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700594 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
595 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
596 @Override
597 public void visitKeyboardLayout(Resources resources,
598 String descriptor, String label, int kcmResId) {
599 list.add(new KeyboardLayout(descriptor, label));
600 }
601 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700602 return list.toArray(new KeyboardLayout[list.size()]);
603 }
604
605 @Override // Binder call
606 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
607 if (keyboardLayoutDescriptor == null) {
608 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
609 }
610
Jeff Brown6ec6f792012-04-17 16:52:41 -0700611 final KeyboardLayout[] result = new KeyboardLayout[1];
612 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
613 @Override
614 public void visitKeyboardLayout(Resources resources,
615 String descriptor, String label, int kcmResId) {
616 result[0] = new KeyboardLayout(descriptor, label);
617 }
618 });
619 if (result[0] == null) {
620 Log.w(TAG, "Could not get keyboard layout with descriptor '"
621 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700622 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700623 return result[0];
624 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700625
Jeff Brown6ec6f792012-04-17 16:52:41 -0700626 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700627 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700628 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
629 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
630 PackageManager.GET_META_DATA)) {
631 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700632 }
633 }
634
Jeff Brown6ec6f792012-04-17 16:52:41 -0700635 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
636 KeyboardLayoutVisitor visitor) {
637 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
638 if (d != null) {
639 final PackageManager pm = mContext.getPackageManager();
640 try {
641 ActivityInfo receiver = pm.getReceiverInfo(
642 new ComponentName(d.packageName, d.receiverName),
643 PackageManager.GET_META_DATA);
644 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
645 } catch (NameNotFoundException ex) {
646 }
647 }
648 }
649
650 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
651 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700652 Bundle metaData = receiver.metaData;
653 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700654 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700655 }
656
657 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
658 if (configResId == 0) {
659 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
660 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700661 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700662 }
663
664 try {
665 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
666 XmlResourceParser parser = resources.getXml(configResId);
667 try {
668 XmlUtils.beginDocument(parser, "keyboard-layouts");
669
670 for (;;) {
671 XmlUtils.nextElement(parser);
672 String element = parser.getName();
673 if (element == null) {
674 break;
675 }
676 if (element.equals("keyboard-layout")) {
677 TypedArray a = resources.obtainAttributes(
678 parser, com.android.internal.R.styleable.KeyboardLayout);
679 try {
680 String name = a.getString(
681 com.android.internal.R.styleable.KeyboardLayout_name);
682 String label = a.getString(
683 com.android.internal.R.styleable.KeyboardLayout_label);
684 int kcmResId = a.getResourceId(
685 com.android.internal.R.styleable.KeyboardLayout_kcm, 0);
686 if (name == null || label == null || kcmResId == 0) {
687 Log.w(TAG, "Missing required 'name', 'label' or 'kcm' "
688 + "attributes in keyboard layout "
689 + "resource from receiver "
690 + receiver.packageName + "/" + receiver.name);
691 } else {
692 String descriptor = KeyboardLayoutDescriptor.format(
693 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700694 if (keyboardName == null || name.equals(keyboardName)) {
695 visitor.visitKeyboardLayout(resources, descriptor,
696 label, kcmResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700697 }
698 }
699 } finally {
700 a.recycle();
701 }
702 } else {
703 Log.w(TAG, "Skipping unrecognized element '" + element
704 + "' in keyboard layout resource from receiver "
705 + receiver.packageName + "/" + receiver.name);
706 }
707 }
708 } finally {
709 parser.close();
710 }
711 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700712 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700713 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700714 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700715 }
716
717 @Override // Binder call
718 public String getKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
719 if (inputDeviceDescriptor == null) {
720 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
721 }
722
Jeff Browna3bc5652012-04-17 11:42:25 -0700723 synchronized (mDataStore) {
724 return mDataStore.getKeyboardLayout(inputDeviceDescriptor);
725 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700726 }
727
728 @Override // Binder call
729 public void setKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
730 String keyboardLayoutDescriptor) {
731 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
732 "setKeyboardLayoutForInputDevice()")) {
733 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
734 }
735
736 if (inputDeviceDescriptor == null) {
737 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
738 }
739
Jeff Brown6ec6f792012-04-17 16:52:41 -0700740 final boolean changed;
Jeff Browna3bc5652012-04-17 11:42:25 -0700741 synchronized (mDataStore) {
742 try {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700743 changed = mDataStore.setKeyboardLayout(
744 inputDeviceDescriptor, keyboardLayoutDescriptor);
Jeff Browna3bc5652012-04-17 11:42:25 -0700745 } finally {
746 mDataStore.saveIfNeeded();
747 }
748 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700749
750 if (changed) {
751 if (DEBUG) {
752 Slog.d(TAG, "Keyboard layout changed, reloading keyboard layouts.");
753 }
754 reloadKeyboardLayouts();
755 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700756 }
757
Jeff Brown9302c872011-07-13 22:51:29 -0700758 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -0700759 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -0700760 }
761
Jeff Brown9302c872011-07-13 22:51:29 -0700762 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -0700763 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -0700764 }
765
Jeff Brown349703e2010-06-22 01:27:15 -0700766 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -0700767 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -0700768 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800769
770 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -0700771 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -0800772 }
773
Jeff Browne6504122010-09-27 14:52:15 -0700774 /**
775 * Atomically transfers touch focus from one window to another as identified by
776 * their input channels. It is possible for multiple windows to have
777 * touch focus if they support split touch dispatch
778 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
779 * method only transfers touch focus of the specified window without affecting
780 * other windows that may also have touch focus at the same time.
781 * @param fromChannel The channel of a window that currently has touch focus.
782 * @param toChannel The channel of the window that should receive touch focus in
783 * place of the first.
784 * @return True if the transfer was successful. False if the window with the
785 * specified channel did not actually have touch focus at the time of the request.
786 */
787 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
788 if (fromChannel == null) {
789 throw new IllegalArgumentException("fromChannel must not be null.");
790 }
791 if (toChannel == null) {
792 throw new IllegalArgumentException("toChannel must not be null.");
793 }
Jeff Brown4532e612012-04-05 14:27:12 -0700794 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -0700795 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800796
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700797 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700798 public void tryPointerSpeed(int speed) {
799 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
800 "tryPointerSpeed()")) {
801 throw new SecurityException("Requires SET_POINTER_SPEED permission");
802 }
803
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700804 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
805 throw new IllegalArgumentException("speed out of range");
806 }
807
Jeff Brownac143512012-04-05 18:57:33 -0700808 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700809 }
810
811 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -0700812 int speed = getPointerSpeedSetting();
813 setPointerSpeedUnchecked(speed);
814 }
815
816 private void setPointerSpeedUnchecked(int speed) {
817 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
818 InputManager.MAX_POINTER_SPEED);
819 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700820 }
821
822 private void registerPointerSpeedSettingObserver() {
823 mContext.getContentResolver().registerContentObserver(
824 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700825 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -0700826 @Override
827 public void onChange(boolean selfChange) {
828 updatePointerSpeedFromSettings();
829 }
830 });
831 }
832
Jeff Brownac143512012-04-05 18:57:33 -0700833 private int getPointerSpeedSetting() {
834 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -0700835 try {
836 speed = Settings.System.getInt(mContext.getContentResolver(),
837 Settings.System.POINTER_SPEED);
838 } catch (SettingNotFoundException snfe) {
839 }
840 return speed;
841 }
842
Jeff Browndaf4a122011-08-26 17:14:14 -0700843 public void updateShowTouchesFromSettings() {
844 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -0700845 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -0700846 }
847
848 private void registerShowTouchesSettingObserver() {
849 mContext.getContentResolver().registerContentObserver(
850 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700851 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -0700852 @Override
853 public void onChange(boolean selfChange) {
854 updateShowTouchesFromSettings();
855 }
856 });
857 }
858
859 private int getShowTouchesSetting(int defaultValue) {
860 int result = defaultValue;
861 try {
862 result = Settings.System.getInt(mContext.getContentResolver(),
863 Settings.System.SHOW_TOUCHES);
864 } catch (SettingNotFoundException snfe) {
865 }
866 return result;
867 }
868
Jeff Browna47425a2012-04-13 04:09:27 -0700869 // Binder call
870 @Override
871 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
872 if (repeat >= pattern.length) {
873 throw new ArrayIndexOutOfBoundsException();
874 }
875
876 VibratorToken v;
877 synchronized (mVibratorLock) {
878 v = mVibratorTokens.get(token);
879 if (v == null) {
880 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
881 try {
882 token.linkToDeath(v, 0);
883 } catch (RemoteException ex) {
884 // give up
885 throw new RuntimeException(ex);
886 }
887 mVibratorTokens.put(token, v);
888 }
889 }
890
891 synchronized (v) {
892 v.mVibrating = true;
893 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
894 }
895 }
896
897 // Binder call
898 @Override
899 public void cancelVibrate(int deviceId, IBinder token) {
900 VibratorToken v;
901 synchronized (mVibratorLock) {
902 v = mVibratorTokens.get(token);
903 if (v == null || v.mDeviceId != deviceId) {
904 return; // nothing to cancel
905 }
906 }
907
908 cancelVibrateIfNeeded(v);
909 }
910
911 void onVibratorTokenDied(VibratorToken v) {
912 synchronized (mVibratorLock) {
913 mVibratorTokens.remove(v.mToken);
914 }
915
916 cancelVibrateIfNeeded(v);
917 }
918
919 private void cancelVibrateIfNeeded(VibratorToken v) {
920 synchronized (v) {
921 if (v.mVibrating) {
922 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
923 v.mVibrating = false;
924 }
925 }
926 }
927
Jeff Brown4532e612012-04-05 14:27:12 -0700928 @Override
929 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -0700930 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -0700931 != PackageManager.PERMISSION_GRANTED) {
932 pw.println("Permission Denial: can't dump InputManager from from pid="
933 + Binder.getCallingPid()
934 + ", uid=" + Binder.getCallingUid());
935 return;
936 }
937
938 pw.println("INPUT MANAGER (dumpsys input)\n");
939 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -0700940 if (dumpStr != null) {
941 pw.println(dumpStr);
942 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700943 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -0800944
Jeff Brownac143512012-04-05 18:57:33 -0700945 private boolean checkCallingPermission(String permission, String func) {
946 // Quick check: if the calling permission is me, it's all okay.
947 if (Binder.getCallingPid() == Process.myPid()) {
948 return true;
949 }
950
951 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
952 return true;
953 }
954 String msg = "Permission Denial: " + func + " from pid="
955 + Binder.getCallingPid()
956 + ", uid=" + Binder.getCallingUid()
957 + " requires " + permission;
958 Slog.w(TAG, msg);
959 return false;
960 }
961
Jeff Brown4532e612012-04-05 14:27:12 -0700962 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Jeff Brown89ef0722011-08-10 16:25:21 -0700963 public void monitor() {
964 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -0700965 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -0700966 }
967
Jeff Brown4532e612012-04-05 14:27:12 -0700968 // Native callback.
969 private void notifyConfigurationChanged(long whenNanos) {
970 mCallbacks.notifyConfigurationChanged();
971 }
972
973 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700974 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
975 synchronized (mInputDevicesLock) {
976 mInputDevices = inputDevices;
977
978 if (!mInputDevicesChangedPending) {
979 mInputDevicesChangedPending = true;
980 mHandler.sendEmptyMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED);
981 }
982 }
983 }
984
985 // Native callback.
Jeff Brown4532e612012-04-05 14:27:12 -0700986 private void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
987 mCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
988 }
989
990 // Native callback.
991 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
992 mCallbacks.notifyInputChannelBroken(inputWindowHandle);
993 }
994
995 // Native callback.
996 private long notifyANR(InputApplicationHandle inputApplicationHandle,
997 InputWindowHandle inputWindowHandle) {
998 return mCallbacks.notifyANR(inputApplicationHandle, inputWindowHandle);
999 }
1000
1001 // Native callback.
1002 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1003 synchronized (mInputFilterLock) {
1004 if (mInputFilter != null) {
1005 mInputFilter.filterInputEvent(event, policyFlags);
1006 return false;
1007 }
1008 }
1009 event.recycle();
1010 return true;
1011 }
1012
1013 // Native callback.
1014 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
1015 return mCallbacks.interceptKeyBeforeQueueing(
1016 event, policyFlags, isScreenOn);
1017 }
1018
1019 // Native callback.
1020 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
1021 return mCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
1022 }
1023
1024 // Native callback.
1025 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1026 KeyEvent event, int policyFlags) {
1027 return mCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
1028 }
1029
1030 // Native callback.
1031 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1032 KeyEvent event, int policyFlags) {
1033 return mCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
1034 }
1035
1036 // Native callback.
1037 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1038 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1039 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1040 }
1041
1042 // Native callback.
1043 private int getVirtualKeyQuietTimeMillis() {
1044 return mContext.getResources().getInteger(
1045 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1046 }
1047
1048 // Native callback.
1049 private String[] getExcludedDeviceNames() {
1050 ArrayList<String> names = new ArrayList<String>();
1051
1052 // Read partner-provided list of excluded input devices
1053 XmlPullParser parser = null;
1054 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1055 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1056 FileReader confreader = null;
1057 try {
1058 confreader = new FileReader(confFile);
1059 parser = Xml.newPullParser();
1060 parser.setInput(confreader);
1061 XmlUtils.beginDocument(parser, "devices");
1062
1063 while (true) {
1064 XmlUtils.nextElement(parser);
1065 if (!"device".equals(parser.getName())) {
1066 break;
1067 }
1068 String name = parser.getAttributeValue(null, "name");
1069 if (name != null) {
1070 names.add(name);
1071 }
1072 }
1073 } catch (FileNotFoundException e) {
1074 // It's ok if the file does not exist.
1075 } catch (Exception e) {
1076 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1077 } finally {
1078 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1079 }
1080
1081 return names.toArray(new String[names.size()]);
1082 }
1083
1084 // Native callback.
1085 private int getKeyRepeatTimeout() {
1086 return ViewConfiguration.getKeyRepeatTimeout();
1087 }
1088
1089 // Native callback.
1090 private int getKeyRepeatDelay() {
1091 return ViewConfiguration.getKeyRepeatDelay();
1092 }
1093
1094 // Native callback.
1095 private int getHoverTapTimeout() {
1096 return ViewConfiguration.getHoverTapTimeout();
1097 }
1098
1099 // Native callback.
1100 private int getHoverTapSlop() {
1101 return ViewConfiguration.getHoverTapSlop();
1102 }
1103
1104 // Native callback.
1105 private int getDoubleTapTimeout() {
1106 return ViewConfiguration.getDoubleTapTimeout();
1107 }
1108
1109 // Native callback.
1110 private int getLongPressTimeout() {
1111 return ViewConfiguration.getLongPressTimeout();
1112 }
1113
1114 // Native callback.
1115 private int getPointerLayer() {
1116 return mCallbacks.getPointerLayer();
1117 }
1118
1119 // Native callback.
1120 private PointerIcon getPointerIcon() {
1121 return PointerIcon.getDefaultIcon(mContext);
1122 }
1123
Jeff Brown6ec6f792012-04-17 16:52:41 -07001124 // Native callback.
1125 private String[] getKeyboardLayoutOverlay(String inputDeviceDescriptor) {
1126 if (!mSystemReady) {
1127 return null;
1128 }
1129
1130 String keyboardLayoutDescriptor = getKeyboardLayoutForInputDevice(inputDeviceDescriptor);
1131 if (keyboardLayoutDescriptor == null) {
1132 return null;
1133 }
1134
1135 final String[] result = new String[2];
1136 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1137 @Override
1138 public void visitKeyboardLayout(Resources resources,
1139 String descriptor, String label, int kcmResId) {
1140 try {
1141 result[0] = descriptor;
1142 result[1] = Streams.readFully(new InputStreamReader(
1143 resources.openRawResource(kcmResId)));
1144 } catch (IOException ex) {
1145 } catch (NotFoundException ex) {
1146 }
1147 }
1148 });
1149 if (result[0] == null) {
1150 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1151 + keyboardLayoutDescriptor + "'.");
1152 return null;
1153 }
1154 return result;
1155 }
1156
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001157 // Native callback.
1158 private String getDeviceAlias(String uniqueId) {
1159 if (mBluetoothService != null &&
1160 BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1161 return mBluetoothService.getRemoteAlias(uniqueId);
1162 }
1163 return null;
1164 }
1165
Jeff Brown6ec6f792012-04-17 16:52:41 -07001166
Jeff Brown4532e612012-04-05 14:27:12 -07001167 /**
1168 * Callback interface implemented by the Window Manager.
1169 */
1170 public interface Callbacks {
1171 public void notifyConfigurationChanged();
1172
1173 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1174
1175 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1176
1177 public long notifyANR(InputApplicationHandle inputApplicationHandle,
1178 InputWindowHandle inputWindowHandle);
1179
1180 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1181
1182 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1183
1184 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1185 KeyEvent event, int policyFlags);
1186
1187 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1188 KeyEvent event, int policyFlags);
1189
1190 public int getPointerLayer();
1191 }
1192
1193 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001194 * Private handler for the input manager.
1195 */
1196 private final class InputManagerHandler extends Handler {
1197 @Override
1198 public void handleMessage(Message msg) {
1199 switch (msg.what) {
1200 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
1201 deliverInputDevicesChanged();
1202 break;
1203 }
1204 }
1205 }
1206
1207 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001208 * Hosting interface for input filters to call back into the input manager.
1209 */
Jeff Brown0029c662011-03-30 02:25:18 -07001210 private final class InputFilterHost implements InputFilter.Host {
1211 private boolean mDisconnected;
1212
1213 public void disconnectLocked() {
1214 mDisconnected = true;
1215 }
1216
1217 public void sendInputEvent(InputEvent event, int policyFlags) {
1218 if (event == null) {
1219 throw new IllegalArgumentException("event must not be null");
1220 }
1221
1222 synchronized (mInputFilterLock) {
1223 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001224 nativeInjectInputEvent(mPtr, event, 0, 0,
1225 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001226 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1227 }
1228 }
1229 }
1230 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001231
1232 private static final class KeyboardLayoutDescriptor {
1233 public String packageName;
1234 public String receiverName;
1235 public String keyboardLayoutName;
1236
1237 public static String format(String packageName,
1238 String receiverName, String keyboardName) {
1239 return packageName + "/" + receiverName + "/" + keyboardName;
1240 }
1241
1242 public static KeyboardLayoutDescriptor parse(String descriptor) {
1243 int pos = descriptor.indexOf('/');
1244 if (pos < 0 || pos + 1 == descriptor.length()) {
1245 return null;
1246 }
1247 int pos2 = descriptor.indexOf('/', pos + 1);
1248 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1249 return null;
1250 }
1251
1252 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1253 result.packageName = descriptor.substring(0, pos);
1254 result.receiverName = descriptor.substring(pos + 1, pos2);
1255 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1256 return result;
1257 }
1258 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001259
Jeff Brown6ec6f792012-04-17 16:52:41 -07001260 private interface KeyboardLayoutVisitor {
1261 void visitKeyboardLayout(Resources resources,
1262 String descriptor, String label, int kcmResId);
1263 }
1264
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001265 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1266 private final int mPid;
1267 private final IInputDevicesChangedListener mListener;
1268
1269 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1270 mPid = pid;
1271 mListener = listener;
1272 }
1273
1274 @Override
1275 public void binderDied() {
1276 if (DEBUG) {
1277 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1278 }
1279 onInputDevicesChangedListenerDied(mPid);
1280 }
1281
1282 public void notifyInputDevicesChanged(int[] info) {
1283 try {
1284 mListener.onInputDevicesChanged(info);
1285 } catch (RemoteException ex) {
1286 Slog.w(TAG, "Failed to notify process "
1287 + mPid + " that input devices changed, assuming it died.", ex);
1288 binderDied();
1289 }
1290 }
1291 }
Jeff Browna47425a2012-04-13 04:09:27 -07001292
1293 private final class VibratorToken implements DeathRecipient {
1294 public final int mDeviceId;
1295 public final IBinder mToken;
1296 public final int mTokenValue;
1297
1298 public boolean mVibrating;
1299
1300 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1301 mDeviceId = deviceId;
1302 mToken = token;
1303 mTokenValue = tokenValue;
1304 }
1305
1306 @Override
1307 public void binderDied() {
1308 if (DEBUG) {
1309 Slog.d(TAG, "Vibrator token died.");
1310 }
1311 onVibratorTokenDied(this);
1312 }
1313 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001314
1315 /**
1316 * Manages persistent state recorded by the input manager service as an XML file.
1317 * Caller must acquire lock on the data store before accessing it.
1318 *
1319 * File format:
1320 * <code>
1321 * &lt;input-mananger-state>
1322 * &lt;input-devices>
1323 * &lt;input-device descriptor="xxxxx" keyboard-layout="yyyyy" />
1324 * &gt;input-devices>
1325 * &gt;/input-manager-state>
1326 * </code>
1327 */
1328 private static final class PersistentDataStore {
1329 // Input device state by descriptor.
1330 private final HashMap<String, InputDeviceState> mInputDevices =
1331 new HashMap<String, InputDeviceState>();
1332 private final AtomicFile mAtomicFile;
1333
1334 // True if the data has been loaded.
1335 private boolean mLoaded;
1336
1337 // True if there are changes to be saved.
1338 private boolean mDirty;
1339
1340 public PersistentDataStore() {
1341 mAtomicFile = new AtomicFile(new File("/data/system/input-manager-state.xml"));
1342 }
1343
1344 public void saveIfNeeded() {
1345 if (mDirty) {
1346 save();
1347 mDirty = false;
1348 }
1349 }
1350
1351 public String getKeyboardLayout(String inputDeviceDescriptor) {
1352 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, false);
1353 return state != null ? state.keyboardLayoutDescriptor : null;
1354 }
1355
1356 public boolean setKeyboardLayout(String inputDeviceDescriptor,
1357 String keyboardLayoutDescriptor) {
1358 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, true);
1359 if (!Objects.equal(state.keyboardLayoutDescriptor, keyboardLayoutDescriptor)) {
1360 state.keyboardLayoutDescriptor = keyboardLayoutDescriptor;
1361 setDirty();
1362 return true;
1363 }
1364 return false;
1365 }
1366
1367 private InputDeviceState getInputDeviceState(String inputDeviceDescriptor,
1368 boolean createIfAbsent) {
1369 loadIfNeeded();
1370 InputDeviceState state = mInputDevices.get(inputDeviceDescriptor);
1371 if (state == null && createIfAbsent) {
1372 state = new InputDeviceState();
1373 mInputDevices.put(inputDeviceDescriptor, state);
1374 setDirty();
1375 }
1376 return state;
1377 }
1378
1379 private void loadIfNeeded() {
1380 if (!mLoaded) {
1381 load();
1382 mLoaded = true;
1383 }
1384 }
1385
1386 private void setDirty() {
1387 mDirty = true;
1388 }
1389
1390 private void clearState() {
1391 mInputDevices.clear();
1392 }
1393
1394 private void load() {
1395 clearState();
1396
1397 final InputStream is;
1398 try {
1399 is = mAtomicFile.openRead();
1400 } catch (FileNotFoundException ex) {
1401 return;
1402 }
1403
1404 XmlPullParser parser;
1405 try {
1406 parser = Xml.newPullParser();
1407 parser.setInput(new BufferedInputStream(is), null);
1408 loadFromXml(parser);
1409 } catch (IOException ex) {
1410 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1411 clearState();
1412 } catch (XmlPullParserException ex) {
1413 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1414 clearState();
1415 } finally {
1416 IoUtils.closeQuietly(is);
1417 }
1418 }
1419
1420 private void save() {
1421 final FileOutputStream os;
1422 try {
1423 os = mAtomicFile.startWrite();
1424 boolean success = false;
1425 try {
1426 XmlSerializer serializer = new FastXmlSerializer();
1427 serializer.setOutput(new BufferedOutputStream(os), "utf-8");
1428 saveToXml(serializer);
1429 serializer.flush();
1430 success = true;
1431 } finally {
1432 if (success) {
1433 mAtomicFile.finishWrite(os);
1434 } else {
1435 mAtomicFile.failWrite(os);
1436 }
1437 }
1438 } catch (IOException ex) {
1439 Slog.w(TAG, "Failed to save input manager persistent store data.", ex);
1440 }
1441 }
1442
1443 private void loadFromXml(XmlPullParser parser)
1444 throws IOException, XmlPullParserException {
1445 XmlUtils.beginDocument(parser, "input-manager-state");
1446 final int outerDepth = parser.getDepth();
1447 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1448 if (parser.getName().equals("input-devices")) {
1449 loadInputDevicesFromXml(parser);
1450 }
1451 }
1452 }
1453
1454 private void loadInputDevicesFromXml(XmlPullParser parser)
1455 throws IOException, XmlPullParserException {
1456 final int outerDepth = parser.getDepth();
1457 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1458 if (parser.getName().equals("input-device")) {
1459 String descriptor = parser.getAttributeValue(null, "descriptor");
1460 if (descriptor == null) {
1461 throw new XmlPullParserException(
1462 "Missing descriptor attribute on input-device");
1463 }
1464 InputDeviceState state = new InputDeviceState();
1465 state.keyboardLayoutDescriptor =
1466 parser.getAttributeValue(null, "keyboard-layout");
1467 mInputDevices.put(descriptor, state);
1468 }
1469 }
1470 }
1471
1472 private void saveToXml(XmlSerializer serializer) throws IOException {
1473 serializer.startDocument(null, true);
1474 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1475 serializer.startTag(null, "input-manager-state");
1476 serializer.startTag(null, "input-devices");
1477 for (Map.Entry<String, InputDeviceState> entry : mInputDevices.entrySet()) {
1478 final String descriptor = entry.getKey();
1479 final InputDeviceState state = entry.getValue();
1480 serializer.startTag(null, "input-device");
1481 serializer.attribute(null, "descriptor", descriptor);
1482 if (state.keyboardLayoutDescriptor != null) {
1483 serializer.attribute(null, "keyboard-layout", state.keyboardLayoutDescriptor);
1484 }
1485 serializer.endTag(null, "input-device");
1486 }
1487 serializer.endTag(null, "input-devices");
1488 serializer.endTag(null, "input-manager-state");
1489 serializer.endDocument();
1490 }
1491 }
1492
1493 private static final class InputDeviceState {
1494 public String keyboardLayoutDescriptor;
1495 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001496}