blob: 189a9c72674633a1f994b24002e3f388eeab7c56 [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 void nativeGetInputConfiguration(int ptr, Configuration configuration);
Jeff Brown4532e612012-04-05 14:27:12 -0700166 private static native boolean nativeTransferTouchFocus(int ptr,
167 InputChannel fromChannel, InputChannel toChannel);
168 private static native void nativeSetPointerSpeed(int ptr, int speed);
169 private static native void nativeSetShowTouches(int ptr, boolean enabled);
Jeff Browna47425a2012-04-13 04:09:27 -0700170 private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
171 int repeat, int token);
172 private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700173 private static native void nativeReloadKeyboardLayouts(int ptr);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700174 private static native void nativeReloadDeviceAliases(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700175 private static native String nativeDump(int ptr);
176 private static native void nativeMonitor(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700177
Jeff Brownac143512012-04-05 18:57:33 -0700178 // Input event injection constants defined in InputDispatcher.h.
179 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
180 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
181 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
182 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
183
184 // Maximum number of milliseconds to wait for input event injection.
185 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
186
Jeff Brown6d0fec22010-07-23 21:28:06 -0700187 // Key states (may be returned by queries about the current state of a
188 // particular key code, scan code or switch).
189
190 /** The key state is unknown or the requested key itself is not supported. */
191 public static final int KEY_STATE_UNKNOWN = -1;
192
193 /** The key is up. /*/
194 public static final int KEY_STATE_UP = 0;
195
196 /** The key is down. */
197 public static final int KEY_STATE_DOWN = 1;
198
199 /** The key is down but is a virtual key press that is being emulated by the system. */
200 public static final int KEY_STATE_VIRTUAL = 2;
201
Jeff Brown4532e612012-04-05 14:27:12 -0700202 public InputManagerService(Context context, Callbacks callbacks) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700203 this.mContext = context;
Jeff Brown4532e612012-04-05 14:27:12 -0700204 this.mCallbacks = callbacks;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700205 this.mHandler = new InputManagerHandler();
Jeff Brown05dc66a2011-03-02 14:41:58 -0800206
Jeff Brown46b9ac02010-04-22 18:58:52 -0700207 Slog.i(TAG, "Initializing input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700208 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700209 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700210
Jeff Brown46b9ac02010-04-22 18:58:52 -0700211 public void start() {
212 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700213 nativeStart(mPtr);
214
215 // Add ourself to the Watchdog monitors.
216 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700217
218 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700219 registerShowTouchesSettingObserver();
220
Jeff Brown1a84fd12011-06-02 01:26:32 -0700221 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700222 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700223 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700224
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700225 public void systemReady(BluetoothService bluetoothService) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700226 if (DEBUG) {
227 Slog.d(TAG, "System ready.");
228 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700229 mBluetoothService = bluetoothService;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700230 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700231
232 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
233 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
234 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
235 filter.addDataScheme("package");
236 mContext.registerReceiver(new BroadcastReceiver() {
237 @Override
238 public void onReceive(Context context, Intent intent) {
239 if (DEBUG) {
240 Slog.d(TAG, "Packages changed, reloading keyboard layouts.");
241 }
242 reloadKeyboardLayouts();
243 }
244 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700245
246 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
247 mContext.registerReceiver(new BroadcastReceiver() {
248 @Override
249 public void onReceive(Context context, Intent intent) {
250 if (DEBUG) {
251 Slog.d(TAG, "Bluetooth alias changed, reloading device names.");
252 }
253 reloadDeviceAliases();
254 }
255 }, filter, null, mHandler);
256
257 reloadKeyboardLayouts();
258 reloadDeviceAliases();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700259 }
260
261 private void reloadKeyboardLayouts() {
262 nativeReloadKeyboardLayouts(mPtr);
263 }
264
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700265 private void reloadDeviceAliases() {
266 nativeReloadDeviceAliases(mPtr);
267 }
268
Jeff Brownbc68a592011-07-25 12:58:12 -0700269 public void setDisplaySize(int displayId, int width, int height,
270 int externalWidth, int externalHeight) {
271 if (width <= 0 || height <= 0 || externalWidth <= 0 || externalHeight <= 0) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700272 throw new IllegalArgumentException("Invalid display id or dimensions.");
273 }
274
Jeff Brownb6997262010-10-08 22:31:17 -0700275 if (DEBUG) {
Jeff Brownbc68a592011-07-25 12:58:12 -0700276 Slog.d(TAG, "Setting display #" + displayId + " size to " + width + "x" + height
277 + " external size " + externalWidth + "x" + externalHeight);
Jeff Brownb6997262010-10-08 22:31:17 -0700278 }
Jeff Brown4532e612012-04-05 14:27:12 -0700279 nativeSetDisplaySize(mPtr, displayId, width, height, externalWidth, externalHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700280 }
281
282 public void setDisplayOrientation(int displayId, int rotation) {
283 if (rotation < Surface.ROTATION_0 || rotation > Surface.ROTATION_270) {
284 throw new IllegalArgumentException("Invalid rotation.");
285 }
286
Jeff Brownb6997262010-10-08 22:31:17 -0700287 if (DEBUG) {
288 Slog.d(TAG, "Setting display #" + displayId + " orientation to " + rotation);
289 }
Jeff Brown4532e612012-04-05 14:27:12 -0700290 nativeSetDisplayOrientation(mPtr, displayId, rotation);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700291 }
292
293 public void getInputConfiguration(Configuration config) {
294 if (config == null) {
295 throw new IllegalArgumentException("config must not be null.");
296 }
297
Jeff Brown4532e612012-04-05 14:27:12 -0700298 nativeGetInputConfiguration(mPtr, config);
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
516 @Override // Binder call
517 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
518 if (listener == null) {
519 throw new IllegalArgumentException("listener must not be null");
520 }
521
522 synchronized (mInputDevicesLock) {
523 int callingPid = Binder.getCallingPid();
524 if (mInputDevicesChangedListeners.get(callingPid) != null) {
525 throw new SecurityException("The calling process has already "
526 + "registered an InputDevicesChangedListener.");
527 }
528
529 InputDevicesChangedListenerRecord record =
530 new InputDevicesChangedListenerRecord(callingPid, listener);
531 try {
532 IBinder binder = listener.asBinder();
533 binder.linkToDeath(record, 0);
534 } catch (RemoteException ex) {
535 // give up
536 throw new RuntimeException(ex);
537 }
538
539 mInputDevicesChangedListeners.put(callingPid, record);
540 }
541 }
542
543 private void onInputDevicesChangedListenerDied(int pid) {
544 synchronized (mInputDevicesLock) {
545 mInputDevicesChangedListeners.remove(pid);
546 }
547 }
548
549 // Must be called on handler.
550 private void deliverInputDevicesChanged() {
551 mTempInputDevicesChangedListenersToNotify.clear();
552
553 final int numListeners;
554 final int[] deviceIdAndGeneration;
555 synchronized (mInputDevicesLock) {
556 if (!mInputDevicesChangedPending) {
557 return;
558 }
559 mInputDevicesChangedPending = false;
560
561 numListeners = mInputDevicesChangedListeners.size();
562 for (int i = 0; i < numListeners; i++) {
563 mTempInputDevicesChangedListenersToNotify.add(
564 mInputDevicesChangedListeners.valueAt(i));
565 }
566
567 final int numDevices = mInputDevices.length;
568 deviceIdAndGeneration = new int[numDevices * 2];
569 for (int i = 0; i < numDevices; i++) {
570 final InputDevice inputDevice = mInputDevices[i];
571 deviceIdAndGeneration[i * 2] = inputDevice.getId();
572 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
573 }
574 }
575
576 for (int i = 0; i < numListeners; i++) {
577 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
578 deviceIdAndGeneration);
579 }
Jeff Brown8d608662010-08-30 03:02:23 -0700580 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700581
582 @Override // Binder call
583 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700584 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
585 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
586 @Override
587 public void visitKeyboardLayout(Resources resources,
588 String descriptor, String label, int kcmResId) {
589 list.add(new KeyboardLayout(descriptor, label));
590 }
591 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700592 return list.toArray(new KeyboardLayout[list.size()]);
593 }
594
595 @Override // Binder call
596 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
597 if (keyboardLayoutDescriptor == null) {
598 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
599 }
600
Jeff Brown6ec6f792012-04-17 16:52:41 -0700601 final KeyboardLayout[] result = new KeyboardLayout[1];
602 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
603 @Override
604 public void visitKeyboardLayout(Resources resources,
605 String descriptor, String label, int kcmResId) {
606 result[0] = new KeyboardLayout(descriptor, label);
607 }
608 });
609 if (result[0] == null) {
610 Log.w(TAG, "Could not get keyboard layout with descriptor '"
611 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700612 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700613 return result[0];
614 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700615
Jeff Brown6ec6f792012-04-17 16:52:41 -0700616 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700617 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700618 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
619 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
620 PackageManager.GET_META_DATA)) {
621 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700622 }
623 }
624
Jeff Brown6ec6f792012-04-17 16:52:41 -0700625 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
626 KeyboardLayoutVisitor visitor) {
627 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
628 if (d != null) {
629 final PackageManager pm = mContext.getPackageManager();
630 try {
631 ActivityInfo receiver = pm.getReceiverInfo(
632 new ComponentName(d.packageName, d.receiverName),
633 PackageManager.GET_META_DATA);
634 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
635 } catch (NameNotFoundException ex) {
636 }
637 }
638 }
639
640 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
641 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700642 Bundle metaData = receiver.metaData;
643 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700644 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700645 }
646
647 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
648 if (configResId == 0) {
649 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
650 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700651 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700652 }
653
654 try {
655 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
656 XmlResourceParser parser = resources.getXml(configResId);
657 try {
658 XmlUtils.beginDocument(parser, "keyboard-layouts");
659
660 for (;;) {
661 XmlUtils.nextElement(parser);
662 String element = parser.getName();
663 if (element == null) {
664 break;
665 }
666 if (element.equals("keyboard-layout")) {
667 TypedArray a = resources.obtainAttributes(
668 parser, com.android.internal.R.styleable.KeyboardLayout);
669 try {
670 String name = a.getString(
671 com.android.internal.R.styleable.KeyboardLayout_name);
672 String label = a.getString(
673 com.android.internal.R.styleable.KeyboardLayout_label);
674 int kcmResId = a.getResourceId(
675 com.android.internal.R.styleable.KeyboardLayout_kcm, 0);
676 if (name == null || label == null || kcmResId == 0) {
677 Log.w(TAG, "Missing required 'name', 'label' or 'kcm' "
678 + "attributes in keyboard layout "
679 + "resource from receiver "
680 + receiver.packageName + "/" + receiver.name);
681 } else {
682 String descriptor = KeyboardLayoutDescriptor.format(
683 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700684 if (keyboardName == null || name.equals(keyboardName)) {
685 visitor.visitKeyboardLayout(resources, descriptor,
686 label, kcmResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700687 }
688 }
689 } finally {
690 a.recycle();
691 }
692 } else {
693 Log.w(TAG, "Skipping unrecognized element '" + element
694 + "' in keyboard layout resource from receiver "
695 + receiver.packageName + "/" + receiver.name);
696 }
697 }
698 } finally {
699 parser.close();
700 }
701 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700702 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700703 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700704 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700705 }
706
707 @Override // Binder call
708 public String getKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
709 if (inputDeviceDescriptor == null) {
710 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
711 }
712
Jeff Browna3bc5652012-04-17 11:42:25 -0700713 synchronized (mDataStore) {
714 return mDataStore.getKeyboardLayout(inputDeviceDescriptor);
715 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700716 }
717
718 @Override // Binder call
719 public void setKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
720 String keyboardLayoutDescriptor) {
721 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
722 "setKeyboardLayoutForInputDevice()")) {
723 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
724 }
725
726 if (inputDeviceDescriptor == null) {
727 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
728 }
729
Jeff Brown6ec6f792012-04-17 16:52:41 -0700730 final boolean changed;
Jeff Browna3bc5652012-04-17 11:42:25 -0700731 synchronized (mDataStore) {
732 try {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700733 changed = mDataStore.setKeyboardLayout(
734 inputDeviceDescriptor, keyboardLayoutDescriptor);
Jeff Browna3bc5652012-04-17 11:42:25 -0700735 } finally {
736 mDataStore.saveIfNeeded();
737 }
738 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700739
740 if (changed) {
741 if (DEBUG) {
742 Slog.d(TAG, "Keyboard layout changed, reloading keyboard layouts.");
743 }
744 reloadKeyboardLayouts();
745 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700746 }
747
Jeff Brown9302c872011-07-13 22:51:29 -0700748 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -0700749 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -0700750 }
751
Jeff Brown9302c872011-07-13 22:51:29 -0700752 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -0700753 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -0700754 }
755
Jeff Brown349703e2010-06-22 01:27:15 -0700756 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -0700757 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -0700758 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800759
760 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -0700761 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -0800762 }
763
Jeff Browne6504122010-09-27 14:52:15 -0700764 /**
765 * Atomically transfers touch focus from one window to another as identified by
766 * their input channels. It is possible for multiple windows to have
767 * touch focus if they support split touch dispatch
768 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
769 * method only transfers touch focus of the specified window without affecting
770 * other windows that may also have touch focus at the same time.
771 * @param fromChannel The channel of a window that currently has touch focus.
772 * @param toChannel The channel of the window that should receive touch focus in
773 * place of the first.
774 * @return True if the transfer was successful. False if the window with the
775 * specified channel did not actually have touch focus at the time of the request.
776 */
777 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
778 if (fromChannel == null) {
779 throw new IllegalArgumentException("fromChannel must not be null.");
780 }
781 if (toChannel == null) {
782 throw new IllegalArgumentException("toChannel must not be null.");
783 }
Jeff Brown4532e612012-04-05 14:27:12 -0700784 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -0700785 }
Jeff Brown05dc66a2011-03-02 14:41:58 -0800786
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700787 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700788 public void tryPointerSpeed(int speed) {
789 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
790 "tryPointerSpeed()")) {
791 throw new SecurityException("Requires SET_POINTER_SPEED permission");
792 }
793
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700794 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
795 throw new IllegalArgumentException("speed out of range");
796 }
797
Jeff Brownac143512012-04-05 18:57:33 -0700798 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700799 }
800
801 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -0700802 int speed = getPointerSpeedSetting();
803 setPointerSpeedUnchecked(speed);
804 }
805
806 private void setPointerSpeedUnchecked(int speed) {
807 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
808 InputManager.MAX_POINTER_SPEED);
809 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700810 }
811
812 private void registerPointerSpeedSettingObserver() {
813 mContext.getContentResolver().registerContentObserver(
814 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700815 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -0700816 @Override
817 public void onChange(boolean selfChange) {
818 updatePointerSpeedFromSettings();
819 }
820 });
821 }
822
Jeff Brownac143512012-04-05 18:57:33 -0700823 private int getPointerSpeedSetting() {
824 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -0700825 try {
826 speed = Settings.System.getInt(mContext.getContentResolver(),
827 Settings.System.POINTER_SPEED);
828 } catch (SettingNotFoundException snfe) {
829 }
830 return speed;
831 }
832
Jeff Browndaf4a122011-08-26 17:14:14 -0700833 public void updateShowTouchesFromSettings() {
834 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -0700835 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -0700836 }
837
838 private void registerShowTouchesSettingObserver() {
839 mContext.getContentResolver().registerContentObserver(
840 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -0700841 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -0700842 @Override
843 public void onChange(boolean selfChange) {
844 updateShowTouchesFromSettings();
845 }
846 });
847 }
848
849 private int getShowTouchesSetting(int defaultValue) {
850 int result = defaultValue;
851 try {
852 result = Settings.System.getInt(mContext.getContentResolver(),
853 Settings.System.SHOW_TOUCHES);
854 } catch (SettingNotFoundException snfe) {
855 }
856 return result;
857 }
858
Jeff Browna47425a2012-04-13 04:09:27 -0700859 // Binder call
860 @Override
861 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
862 if (repeat >= pattern.length) {
863 throw new ArrayIndexOutOfBoundsException();
864 }
865
866 VibratorToken v;
867 synchronized (mVibratorLock) {
868 v = mVibratorTokens.get(token);
869 if (v == null) {
870 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
871 try {
872 token.linkToDeath(v, 0);
873 } catch (RemoteException ex) {
874 // give up
875 throw new RuntimeException(ex);
876 }
877 mVibratorTokens.put(token, v);
878 }
879 }
880
881 synchronized (v) {
882 v.mVibrating = true;
883 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
884 }
885 }
886
887 // Binder call
888 @Override
889 public void cancelVibrate(int deviceId, IBinder token) {
890 VibratorToken v;
891 synchronized (mVibratorLock) {
892 v = mVibratorTokens.get(token);
893 if (v == null || v.mDeviceId != deviceId) {
894 return; // nothing to cancel
895 }
896 }
897
898 cancelVibrateIfNeeded(v);
899 }
900
901 void onVibratorTokenDied(VibratorToken v) {
902 synchronized (mVibratorLock) {
903 mVibratorTokens.remove(v.mToken);
904 }
905
906 cancelVibrateIfNeeded(v);
907 }
908
909 private void cancelVibrateIfNeeded(VibratorToken v) {
910 synchronized (v) {
911 if (v.mVibrating) {
912 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
913 v.mVibrating = false;
914 }
915 }
916 }
917
Jeff Brown4532e612012-04-05 14:27:12 -0700918 @Override
919 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -0700920 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -0700921 != PackageManager.PERMISSION_GRANTED) {
922 pw.println("Permission Denial: can't dump InputManager from from pid="
923 + Binder.getCallingPid()
924 + ", uid=" + Binder.getCallingUid());
925 return;
926 }
927
928 pw.println("INPUT MANAGER (dumpsys input)\n");
929 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -0700930 if (dumpStr != null) {
931 pw.println(dumpStr);
932 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700933 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -0800934
Jeff Brownac143512012-04-05 18:57:33 -0700935 private boolean checkCallingPermission(String permission, String func) {
936 // Quick check: if the calling permission is me, it's all okay.
937 if (Binder.getCallingPid() == Process.myPid()) {
938 return true;
939 }
940
941 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
942 return true;
943 }
944 String msg = "Permission Denial: " + func + " from pid="
945 + Binder.getCallingPid()
946 + ", uid=" + Binder.getCallingUid()
947 + " requires " + permission;
948 Slog.w(TAG, msg);
949 return false;
950 }
951
Jeff Brown4532e612012-04-05 14:27:12 -0700952 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Jeff Brown89ef0722011-08-10 16:25:21 -0700953 public void monitor() {
954 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -0700955 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -0700956 }
957
Jeff Brown4532e612012-04-05 14:27:12 -0700958 // Native callback.
959 private void notifyConfigurationChanged(long whenNanos) {
960 mCallbacks.notifyConfigurationChanged();
961 }
962
963 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700964 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
965 synchronized (mInputDevicesLock) {
966 mInputDevices = inputDevices;
967
968 if (!mInputDevicesChangedPending) {
969 mInputDevicesChangedPending = true;
970 mHandler.sendEmptyMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED);
971 }
972 }
973 }
974
975 // Native callback.
Jeff Brown4532e612012-04-05 14:27:12 -0700976 private void notifyLidSwitchChanged(long whenNanos, boolean lidOpen) {
977 mCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
978 }
979
980 // Native callback.
981 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
982 mCallbacks.notifyInputChannelBroken(inputWindowHandle);
983 }
984
985 // Native callback.
986 private long notifyANR(InputApplicationHandle inputApplicationHandle,
987 InputWindowHandle inputWindowHandle) {
988 return mCallbacks.notifyANR(inputApplicationHandle, inputWindowHandle);
989 }
990
991 // Native callback.
992 final boolean filterInputEvent(InputEvent event, int policyFlags) {
993 synchronized (mInputFilterLock) {
994 if (mInputFilter != null) {
995 mInputFilter.filterInputEvent(event, policyFlags);
996 return false;
997 }
998 }
999 event.recycle();
1000 return true;
1001 }
1002
1003 // Native callback.
1004 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
1005 return mCallbacks.interceptKeyBeforeQueueing(
1006 event, policyFlags, isScreenOn);
1007 }
1008
1009 // Native callback.
1010 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
1011 return mCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
1012 }
1013
1014 // Native callback.
1015 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1016 KeyEvent event, int policyFlags) {
1017 return mCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
1018 }
1019
1020 // Native callback.
1021 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1022 KeyEvent event, int policyFlags) {
1023 return mCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
1024 }
1025
1026 // Native callback.
1027 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1028 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1029 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1030 }
1031
1032 // Native callback.
1033 private int getVirtualKeyQuietTimeMillis() {
1034 return mContext.getResources().getInteger(
1035 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1036 }
1037
1038 // Native callback.
1039 private String[] getExcludedDeviceNames() {
1040 ArrayList<String> names = new ArrayList<String>();
1041
1042 // Read partner-provided list of excluded input devices
1043 XmlPullParser parser = null;
1044 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1045 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1046 FileReader confreader = null;
1047 try {
1048 confreader = new FileReader(confFile);
1049 parser = Xml.newPullParser();
1050 parser.setInput(confreader);
1051 XmlUtils.beginDocument(parser, "devices");
1052
1053 while (true) {
1054 XmlUtils.nextElement(parser);
1055 if (!"device".equals(parser.getName())) {
1056 break;
1057 }
1058 String name = parser.getAttributeValue(null, "name");
1059 if (name != null) {
1060 names.add(name);
1061 }
1062 }
1063 } catch (FileNotFoundException e) {
1064 // It's ok if the file does not exist.
1065 } catch (Exception e) {
1066 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1067 } finally {
1068 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1069 }
1070
1071 return names.toArray(new String[names.size()]);
1072 }
1073
1074 // Native callback.
1075 private int getKeyRepeatTimeout() {
1076 return ViewConfiguration.getKeyRepeatTimeout();
1077 }
1078
1079 // Native callback.
1080 private int getKeyRepeatDelay() {
1081 return ViewConfiguration.getKeyRepeatDelay();
1082 }
1083
1084 // Native callback.
1085 private int getHoverTapTimeout() {
1086 return ViewConfiguration.getHoverTapTimeout();
1087 }
1088
1089 // Native callback.
1090 private int getHoverTapSlop() {
1091 return ViewConfiguration.getHoverTapSlop();
1092 }
1093
1094 // Native callback.
1095 private int getDoubleTapTimeout() {
1096 return ViewConfiguration.getDoubleTapTimeout();
1097 }
1098
1099 // Native callback.
1100 private int getLongPressTimeout() {
1101 return ViewConfiguration.getLongPressTimeout();
1102 }
1103
1104 // Native callback.
1105 private int getPointerLayer() {
1106 return mCallbacks.getPointerLayer();
1107 }
1108
1109 // Native callback.
1110 private PointerIcon getPointerIcon() {
1111 return PointerIcon.getDefaultIcon(mContext);
1112 }
1113
Jeff Brown6ec6f792012-04-17 16:52:41 -07001114 // Native callback.
1115 private String[] getKeyboardLayoutOverlay(String inputDeviceDescriptor) {
1116 if (!mSystemReady) {
1117 return null;
1118 }
1119
1120 String keyboardLayoutDescriptor = getKeyboardLayoutForInputDevice(inputDeviceDescriptor);
1121 if (keyboardLayoutDescriptor == null) {
1122 return null;
1123 }
1124
1125 final String[] result = new String[2];
1126 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1127 @Override
1128 public void visitKeyboardLayout(Resources resources,
1129 String descriptor, String label, int kcmResId) {
1130 try {
1131 result[0] = descriptor;
1132 result[1] = Streams.readFully(new InputStreamReader(
1133 resources.openRawResource(kcmResId)));
1134 } catch (IOException ex) {
1135 } catch (NotFoundException ex) {
1136 }
1137 }
1138 });
1139 if (result[0] == null) {
1140 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1141 + keyboardLayoutDescriptor + "'.");
1142 return null;
1143 }
1144 return result;
1145 }
1146
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001147 // Native callback.
1148 private String getDeviceAlias(String uniqueId) {
1149 if (mBluetoothService != null &&
1150 BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1151 return mBluetoothService.getRemoteAlias(uniqueId);
1152 }
1153 return null;
1154 }
1155
Jeff Brown6ec6f792012-04-17 16:52:41 -07001156
Jeff Brown4532e612012-04-05 14:27:12 -07001157 /**
1158 * Callback interface implemented by the Window Manager.
1159 */
1160 public interface Callbacks {
1161 public void notifyConfigurationChanged();
1162
1163 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1164
1165 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1166
1167 public long notifyANR(InputApplicationHandle inputApplicationHandle,
1168 InputWindowHandle inputWindowHandle);
1169
1170 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1171
1172 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1173
1174 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1175 KeyEvent event, int policyFlags);
1176
1177 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1178 KeyEvent event, int policyFlags);
1179
1180 public int getPointerLayer();
1181 }
1182
1183 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001184 * Private handler for the input manager.
1185 */
1186 private final class InputManagerHandler extends Handler {
1187 @Override
1188 public void handleMessage(Message msg) {
1189 switch (msg.what) {
1190 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
1191 deliverInputDevicesChanged();
1192 break;
1193 }
1194 }
1195 }
1196
1197 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001198 * Hosting interface for input filters to call back into the input manager.
1199 */
Jeff Brown0029c662011-03-30 02:25:18 -07001200 private final class InputFilterHost implements InputFilter.Host {
1201 private boolean mDisconnected;
1202
1203 public void disconnectLocked() {
1204 mDisconnected = true;
1205 }
1206
1207 public void sendInputEvent(InputEvent event, int policyFlags) {
1208 if (event == null) {
1209 throw new IllegalArgumentException("event must not be null");
1210 }
1211
1212 synchronized (mInputFilterLock) {
1213 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001214 nativeInjectInputEvent(mPtr, event, 0, 0,
1215 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001216 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1217 }
1218 }
1219 }
1220 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001221
1222 private static final class KeyboardLayoutDescriptor {
1223 public String packageName;
1224 public String receiverName;
1225 public String keyboardLayoutName;
1226
1227 public static String format(String packageName,
1228 String receiverName, String keyboardName) {
1229 return packageName + "/" + receiverName + "/" + keyboardName;
1230 }
1231
1232 public static KeyboardLayoutDescriptor parse(String descriptor) {
1233 int pos = descriptor.indexOf('/');
1234 if (pos < 0 || pos + 1 == descriptor.length()) {
1235 return null;
1236 }
1237 int pos2 = descriptor.indexOf('/', pos + 1);
1238 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1239 return null;
1240 }
1241
1242 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1243 result.packageName = descriptor.substring(0, pos);
1244 result.receiverName = descriptor.substring(pos + 1, pos2);
1245 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1246 return result;
1247 }
1248 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001249
Jeff Brown6ec6f792012-04-17 16:52:41 -07001250 private interface KeyboardLayoutVisitor {
1251 void visitKeyboardLayout(Resources resources,
1252 String descriptor, String label, int kcmResId);
1253 }
1254
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001255 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1256 private final int mPid;
1257 private final IInputDevicesChangedListener mListener;
1258
1259 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1260 mPid = pid;
1261 mListener = listener;
1262 }
1263
1264 @Override
1265 public void binderDied() {
1266 if (DEBUG) {
1267 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1268 }
1269 onInputDevicesChangedListenerDied(mPid);
1270 }
1271
1272 public void notifyInputDevicesChanged(int[] info) {
1273 try {
1274 mListener.onInputDevicesChanged(info);
1275 } catch (RemoteException ex) {
1276 Slog.w(TAG, "Failed to notify process "
1277 + mPid + " that input devices changed, assuming it died.", ex);
1278 binderDied();
1279 }
1280 }
1281 }
Jeff Browna47425a2012-04-13 04:09:27 -07001282
1283 private final class VibratorToken implements DeathRecipient {
1284 public final int mDeviceId;
1285 public final IBinder mToken;
1286 public final int mTokenValue;
1287
1288 public boolean mVibrating;
1289
1290 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1291 mDeviceId = deviceId;
1292 mToken = token;
1293 mTokenValue = tokenValue;
1294 }
1295
1296 @Override
1297 public void binderDied() {
1298 if (DEBUG) {
1299 Slog.d(TAG, "Vibrator token died.");
1300 }
1301 onVibratorTokenDied(this);
1302 }
1303 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001304
1305 /**
1306 * Manages persistent state recorded by the input manager service as an XML file.
1307 * Caller must acquire lock on the data store before accessing it.
1308 *
1309 * File format:
1310 * <code>
1311 * &lt;input-mananger-state>
1312 * &lt;input-devices>
1313 * &lt;input-device descriptor="xxxxx" keyboard-layout="yyyyy" />
1314 * &gt;input-devices>
1315 * &gt;/input-manager-state>
1316 * </code>
1317 */
1318 private static final class PersistentDataStore {
1319 // Input device state by descriptor.
1320 private final HashMap<String, InputDeviceState> mInputDevices =
1321 new HashMap<String, InputDeviceState>();
1322 private final AtomicFile mAtomicFile;
1323
1324 // True if the data has been loaded.
1325 private boolean mLoaded;
1326
1327 // True if there are changes to be saved.
1328 private boolean mDirty;
1329
1330 public PersistentDataStore() {
1331 mAtomicFile = new AtomicFile(new File("/data/system/input-manager-state.xml"));
1332 }
1333
1334 public void saveIfNeeded() {
1335 if (mDirty) {
1336 save();
1337 mDirty = false;
1338 }
1339 }
1340
1341 public String getKeyboardLayout(String inputDeviceDescriptor) {
1342 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, false);
1343 return state != null ? state.keyboardLayoutDescriptor : null;
1344 }
1345
1346 public boolean setKeyboardLayout(String inputDeviceDescriptor,
1347 String keyboardLayoutDescriptor) {
1348 InputDeviceState state = getInputDeviceState(inputDeviceDescriptor, true);
1349 if (!Objects.equal(state.keyboardLayoutDescriptor, keyboardLayoutDescriptor)) {
1350 state.keyboardLayoutDescriptor = keyboardLayoutDescriptor;
1351 setDirty();
1352 return true;
1353 }
1354 return false;
1355 }
1356
1357 private InputDeviceState getInputDeviceState(String inputDeviceDescriptor,
1358 boolean createIfAbsent) {
1359 loadIfNeeded();
1360 InputDeviceState state = mInputDevices.get(inputDeviceDescriptor);
1361 if (state == null && createIfAbsent) {
1362 state = new InputDeviceState();
1363 mInputDevices.put(inputDeviceDescriptor, state);
1364 setDirty();
1365 }
1366 return state;
1367 }
1368
1369 private void loadIfNeeded() {
1370 if (!mLoaded) {
1371 load();
1372 mLoaded = true;
1373 }
1374 }
1375
1376 private void setDirty() {
1377 mDirty = true;
1378 }
1379
1380 private void clearState() {
1381 mInputDevices.clear();
1382 }
1383
1384 private void load() {
1385 clearState();
1386
1387 final InputStream is;
1388 try {
1389 is = mAtomicFile.openRead();
1390 } catch (FileNotFoundException ex) {
1391 return;
1392 }
1393
1394 XmlPullParser parser;
1395 try {
1396 parser = Xml.newPullParser();
1397 parser.setInput(new BufferedInputStream(is), null);
1398 loadFromXml(parser);
1399 } catch (IOException ex) {
1400 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1401 clearState();
1402 } catch (XmlPullParserException ex) {
1403 Slog.w(TAG, "Failed to load input manager persistent store data.", ex);
1404 clearState();
1405 } finally {
1406 IoUtils.closeQuietly(is);
1407 }
1408 }
1409
1410 private void save() {
1411 final FileOutputStream os;
1412 try {
1413 os = mAtomicFile.startWrite();
1414 boolean success = false;
1415 try {
1416 XmlSerializer serializer = new FastXmlSerializer();
1417 serializer.setOutput(new BufferedOutputStream(os), "utf-8");
1418 saveToXml(serializer);
1419 serializer.flush();
1420 success = true;
1421 } finally {
1422 if (success) {
1423 mAtomicFile.finishWrite(os);
1424 } else {
1425 mAtomicFile.failWrite(os);
1426 }
1427 }
1428 } catch (IOException ex) {
1429 Slog.w(TAG, "Failed to save input manager persistent store data.", ex);
1430 }
1431 }
1432
1433 private void loadFromXml(XmlPullParser parser)
1434 throws IOException, XmlPullParserException {
1435 XmlUtils.beginDocument(parser, "input-manager-state");
1436 final int outerDepth = parser.getDepth();
1437 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1438 if (parser.getName().equals("input-devices")) {
1439 loadInputDevicesFromXml(parser);
1440 }
1441 }
1442 }
1443
1444 private void loadInputDevicesFromXml(XmlPullParser parser)
1445 throws IOException, XmlPullParserException {
1446 final int outerDepth = parser.getDepth();
1447 while (XmlUtils.nextElementWithin(parser, outerDepth)) {
1448 if (parser.getName().equals("input-device")) {
1449 String descriptor = parser.getAttributeValue(null, "descriptor");
1450 if (descriptor == null) {
1451 throw new XmlPullParserException(
1452 "Missing descriptor attribute on input-device");
1453 }
1454 InputDeviceState state = new InputDeviceState();
1455 state.keyboardLayoutDescriptor =
1456 parser.getAttributeValue(null, "keyboard-layout");
1457 mInputDevices.put(descriptor, state);
1458 }
1459 }
1460 }
1461
1462 private void saveToXml(XmlSerializer serializer) throws IOException {
1463 serializer.startDocument(null, true);
1464 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
1465 serializer.startTag(null, "input-manager-state");
1466 serializer.startTag(null, "input-devices");
1467 for (Map.Entry<String, InputDeviceState> entry : mInputDevices.entrySet()) {
1468 final String descriptor = entry.getKey();
1469 final InputDeviceState state = entry.getValue();
1470 serializer.startTag(null, "input-device");
1471 serializer.attribute(null, "descriptor", descriptor);
1472 if (state.keyboardLayoutDescriptor != null) {
1473 serializer.attribute(null, "keyboard-layout", state.keyboardLayoutDescriptor);
1474 }
1475 serializer.endTag(null, "input-device");
1476 }
1477 serializer.endTag(null, "input-devices");
1478 serializer.endTag(null, "input-manager-state");
1479 serializer.endDocument();
1480 }
1481 }
1482
1483 private static final class InputDeviceState {
1484 public String keyboardLayoutDescriptor;
1485 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001486}