blob: c3c22f63c2b5a36aa80fdd8a5b3d7277f1a8061a [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 Browncf39bdf2012-05-18 14:41:19 -070019import com.android.internal.R;
Jeff Brown46b9ac02010-04-22 18:58:52 -070020import com.android.internal.util.XmlUtils;
Jeff Brown89ef0722011-08-10 16:25:21 -070021import com.android.server.Watchdog;
Jeff Brownd728bf52012-09-08 18:05:28 -070022import com.android.server.display.DisplayManagerService;
23import com.android.server.display.DisplayViewport;
Jeff Brown46b9ac02010-04-22 18:58:52 -070024
25import org.xmlpull.v1.XmlPullParser;
26
Jeff Browna3bc5652012-04-17 11:42:25 -070027import android.Manifest;
Jeff Browncf39bdf2012-05-18 14:41:19 -070028import android.app.Notification;
29import android.app.NotificationManager;
30import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070031import android.bluetooth.BluetoothAdapter;
32import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070033import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070035import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070037import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.pm.ActivityInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070039import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070040import android.content.pm.ResolveInfo;
41import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070042import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070043import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070044import android.content.res.TypedArray;
45import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070046import android.database.ContentObserver;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070047import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070048import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080049import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070050import android.hardware.input.InputManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070051import android.hardware.input.KeyboardLayout;
Jeff Brown4532e612012-04-05 14:27:12 -070052import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070053import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070054import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070055import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070056import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070057import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080059import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070063import android.provider.Settings;
64import android.provider.Settings.SettingNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070065import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070066import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070067import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070069import android.view.IInputFilter;
70import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070071import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070072import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070073import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080074import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070075import android.view.PointerIcon;
Jeff Browna4547672011-03-02 21:38:11 -080076import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070077import android.view.WindowManagerPolicy;
Jeff Browncf39bdf2012-05-18 14:41:19 -070078import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070079
Jeff Brown46b9ac02010-04-22 18:58:52 -070080import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070081import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082import java.io.FileNotFoundException;
83import java.io.FileReader;
84import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -070085import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -070086import java.io.PrintWriter;
87import java.util.ArrayList;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070088import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -070089import java.util.HashSet;
Jeff Browna3bc5652012-04-17 11:42:25 -070090
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 Brownd728bf52012-09-08 18:05:28 -070097public class InputManagerService extends IInputManager.Stub
98 implements Watchdog.Monitor, DisplayManagerService.InputManagerFuncs {
Jeff Brown46b9ac02010-04-22 18:58:52 -070099 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700100 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700101
Jeff Brown4532e612012-04-05 14:27:12 -0700102 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
103
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700104 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700105 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
106 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
107 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
108 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700109
Jeff Brown4532e612012-04-05 14:27:12 -0700110 // Pointer to native input manager service object.
111 private final int mPtr;
112
Jeff Brown46b9ac02010-04-22 18:58:52 -0700113 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700114 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700115
116 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700117 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700118 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700119 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700120
Jeff Browna3bc5652012-04-17 11:42:25 -0700121 // Persistent data store. Must be locked each time during use.
122 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700123
124 // List of currently registered input devices changed listeners by process id.
125 private Object mInputDevicesLock = new Object();
126 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
127 private InputDevice[] mInputDevices = new InputDevice[0];
128 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
129 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
130 private final ArrayList<InputDevicesChangedListenerRecord>
131 mTempInputDevicesChangedListenersToNotify =
132 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700133 private final ArrayList<InputDevice>
134 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
135 private boolean mKeyboardLayoutNotificationShown;
136 private PendingIntent mKeyboardLayoutIntent;
137 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700138
Jeff Browna47425a2012-04-13 04:09:27 -0700139 // State for vibrator tokens.
140 private Object mVibratorLock = new Object();
141 private HashMap<IBinder, VibratorToken> mVibratorTokens =
142 new HashMap<IBinder, VibratorToken>();
143 private int mNextVibratorTokenValue;
144
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145 // State for the currently installed input filter.
146 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700147 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700148 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700149
Jeff Brown4532e612012-04-05 14:27:12 -0700150 private static native int nativeInit(InputManagerService service,
151 Context context, MessageQueue messageQueue);
152 private static native void nativeStart(int ptr);
Jeff Brownd728bf52012-09-08 18:05:28 -0700153 private static native void nativeSetDisplayViewport(int ptr, boolean external,
154 int displayId, int rotation,
155 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700156 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
157 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700158
Jeff Brown4532e612012-04-05 14:27:12 -0700159 private static native int nativeGetScanCodeState(int ptr,
160 int deviceId, int sourceMask, int scanCode);
161 private static native int nativeGetKeyCodeState(int ptr,
162 int deviceId, int sourceMask, int keyCode);
163 private static native int nativeGetSwitchState(int ptr,
164 int deviceId, int sourceMask, int sw);
165 private static native boolean nativeHasKeys(int ptr,
166 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
167 private static native void nativeRegisterInputChannel(int ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800168 InputWindowHandle inputWindowHandle, boolean monitor);
Jeff Brown4532e612012-04-05 14:27:12 -0700169 private static native void nativeUnregisterInputChannel(int ptr, InputChannel inputChannel);
170 private static native void nativeSetInputFilterEnabled(int ptr, boolean enable);
171 private static native int nativeInjectInputEvent(int ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700172 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
173 int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -0700174 private static native void nativeSetInputWindows(int ptr, InputWindowHandle[] windowHandles);
175 private static native void nativeSetInputDispatchMode(int ptr, boolean enabled, boolean frozen);
176 private static native void nativeSetSystemUiVisibility(int ptr, int visibility);
177 private static native void nativeSetFocusedApplication(int ptr,
178 InputApplicationHandle application);
Jeff Brown4532e612012-04-05 14:27:12 -0700179 private static native boolean nativeTransferTouchFocus(int ptr,
180 InputChannel fromChannel, InputChannel toChannel);
181 private static native void nativeSetPointerSpeed(int ptr, int speed);
182 private static native void nativeSetShowTouches(int ptr, boolean enabled);
Jeff Browna47425a2012-04-13 04:09:27 -0700183 private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
184 int repeat, int token);
185 private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700186 private static native void nativeReloadKeyboardLayouts(int ptr);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700187 private static native void nativeReloadDeviceAliases(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700188 private static native String nativeDump(int ptr);
189 private static native void nativeMonitor(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700190
Jeff Brownac143512012-04-05 18:57:33 -0700191 // Input event injection constants defined in InputDispatcher.h.
192 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
193 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
194 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
195 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
196
197 // Maximum number of milliseconds to wait for input event injection.
198 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
199
Jeff Brown6d0fec22010-07-23 21:28:06 -0700200 // Key states (may be returned by queries about the current state of a
201 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700202
Jeff Brown6d0fec22010-07-23 21:28:06 -0700203 /** The key state is unknown or the requested key itself is not supported. */
204 public static final int KEY_STATE_UNKNOWN = -1;
205
206 /** The key is up. /*/
207 public static final int KEY_STATE_UP = 0;
208
209 /** The key is down. */
210 public static final int KEY_STATE_DOWN = 1;
211
212 /** The key is down but is a virtual key press that is being emulated by the system. */
213 public static final int KEY_STATE_VIRTUAL = 2;
214
Jeff Brownc458ce92012-04-30 14:58:40 -0700215 /** Scan code: Mouse / trackball button. */
216 public static final int BTN_MOUSE = 0x110;
217
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700218 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700219 /** Switch code: Lid switch. When set, lid is shut. */
220 public static final int SW_LID = 0x00;
221
222 /** Switch code: Keypad slide. When set, keyboard is exposed. */
223 public static final int SW_KEYPAD_SLIDE = 0x0a;
224
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700225 /** Switch code: Headphone. When set, headphone is inserted. */
226 public static final int SW_HEADPHONE_INSERT = 0x02;
227
228 /** Switch code: Microphone. When set, microphone is inserted. */
229 public static final int SW_MICROPHONE_INSERT = 0x04;
230
231 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
232 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
233
234 public static final int SW_LID_BIT = 1 << SW_LID;
235 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
236 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
237 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
238 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
239 public static final int SW_JACK_BITS =
240 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT;
241
242 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
243 final boolean mUseDevInputEventForAudioJack;
244
Jeff Browna9d131c2012-09-20 16:48:17 -0700245 public InputManagerService(Context context, Handler handler) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700246 this.mContext = context;
Jeff Browna9d131c2012-09-20 16:48:17 -0700247 this.mHandler = new InputManagerHandler(handler.getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800248
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700249 mUseDevInputEventForAudioJack =
250 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
251 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
252 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700253 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700254 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700255
Jeff Browna9d131c2012-09-20 16:48:17 -0700256 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
257 mWindowManagerCallbacks = callbacks;
258 }
259
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700260 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
261 mWiredAccessoryCallbacks = callbacks;
262 }
263
Jeff Brown46b9ac02010-04-22 18:58:52 -0700264 public void start() {
265 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700266 nativeStart(mPtr);
267
268 // Add ourself to the Watchdog monitors.
269 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700270
271 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700272 registerShowTouchesSettingObserver();
273
Jeff Brownd4935962012-09-25 13:27:20 -0700274 mContext.registerReceiver(new BroadcastReceiver() {
275 @Override
276 public void onReceive(Context context, Intent intent) {
277 updatePointerSpeedFromSettings();
278 updateShowTouchesFromSettings();
279 }
280 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
281
Jeff Brown1a84fd12011-06-02 01:26:32 -0700282 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700283 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700284 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700285
Matthew Xie96313142012-06-29 16:57:31 -0700286 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700287 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700288 if (DEBUG) {
289 Slog.d(TAG, "System ready.");
290 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700291 mNotificationManager = (NotificationManager)mContext.getSystemService(
292 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700293 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700294
295 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
296 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
297 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800298 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700299 filter.addDataScheme("package");
300 mContext.registerReceiver(new BroadcastReceiver() {
301 @Override
302 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700303 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700304 }
305 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700306
307 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
308 mContext.registerReceiver(new BroadcastReceiver() {
309 @Override
310 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700311 reloadDeviceAliases();
312 }
313 }, filter, null, mHandler);
314
Jeff Browncf39bdf2012-05-18 14:41:19 -0700315 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
316 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700317 }
318
319 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700320 if (DEBUG) {
321 Slog.d(TAG, "Reloading keyboard layouts.");
322 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700323 nativeReloadKeyboardLayouts(mPtr);
324 }
325
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700326 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700327 if (DEBUG) {
328 Slog.d(TAG, "Reloading device names.");
329 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700330 nativeReloadDeviceAliases(mPtr);
331 }
332
Jeff Brownd728bf52012-09-08 18:05:28 -0700333 @Override
334 public void setDisplayViewports(DisplayViewport defaultViewport,
335 DisplayViewport externalTouchViewport) {
336 if (defaultViewport.valid) {
337 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700338 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700339
340 if (externalTouchViewport.valid) {
341 setDisplayViewport(true, externalTouchViewport);
342 } else if (defaultViewport.valid) {
343 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700344 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700345 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700346
Jeff Brownd728bf52012-09-08 18:05:28 -0700347 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
348 nativeSetDisplayViewport(mPtr, external,
349 viewport.displayId, viewport.orientation,
350 viewport.logicalFrame.left, viewport.logicalFrame.top,
351 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
352 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700353 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
354 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700355 }
Jeff Brownac143512012-04-05 18:57:33 -0700356
Jeff Brown6d0fec22010-07-23 21:28:06 -0700357 /**
358 * Gets the current state of a key or button by key code.
359 * @param deviceId The input device id, or -1 to consult all devices.
360 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
361 * consider all input sources. An input device is consulted if at least one of its
362 * non-class input source bits matches the specified source mask.
363 * @param keyCode The key code to check.
364 * @return The key state.
365 */
366 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700367 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700368 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700369
Jeff Brown6d0fec22010-07-23 21:28:06 -0700370 /**
371 * Gets the current state of a key or button by scan code.
372 * @param deviceId The input device id, or -1 to consult all devices.
373 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
374 * consider all input sources. An input device is consulted if at least one of its
375 * non-class input source bits matches the specified source mask.
376 * @param scanCode The scan code to check.
377 * @return The key state.
378 */
379 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700380 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700381 }
RoboErikfb290df2013-12-16 11:27:55 -0800382
Jeff Brown6d0fec22010-07-23 21:28:06 -0700383 /**
384 * Gets the current state of a switch by switch code.
385 * @param deviceId The input device id, or -1 to consult all devices.
386 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
387 * consider all input sources. An input device is consulted if at least one of its
388 * non-class input source bits matches the specified source mask.
389 * @param switchCode The switch code to check.
390 * @return The switch state.
391 */
392 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700393 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700394 }
395
Jeff Brown6d0fec22010-07-23 21:28:06 -0700396 /**
397 * Determines whether the specified key codes are supported by a particular device.
398 * @param deviceId The input device id, or -1 to consult all devices.
399 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
400 * consider all input sources. An input device is consulted if at least one of its
401 * non-class input source bits matches the specified source mask.
402 * @param keyCodes The array of key codes to check.
403 * @param keyExists An array at least as large as keyCodes whose entries will be set
404 * to true or false based on the presence or absence of support for the corresponding
405 * key codes.
406 * @return True if the lookup was successful, false otherwise.
407 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700408 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700409 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700410 if (keyCodes == null) {
411 throw new IllegalArgumentException("keyCodes must not be null.");
412 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700413 if (keyExists == null || keyExists.length < keyCodes.length) {
414 throw new IllegalArgumentException("keyExists must not be null and must be at "
415 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700416 }
RoboErikfb290df2013-12-16 11:27:55 -0800417
Jeff Brown4532e612012-04-05 14:27:12 -0700418 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700419 }
RoboErikfb290df2013-12-16 11:27:55 -0800420
Jeff Browna41ca772010-08-11 14:46:32 -0700421 /**
422 * Creates an input channel that will receive all input from the input dispatcher.
423 * @param inputChannelName The input channel name.
424 * @return The input channel.
425 */
426 public InputChannel monitorInput(String inputChannelName) {
427 if (inputChannelName == null) {
428 throw new IllegalArgumentException("inputChannelName must not be null.");
429 }
RoboErikfb290df2013-12-16 11:27:55 -0800430
Jeff Browna41ca772010-08-11 14:46:32 -0700431 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700432 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700433 inputChannels[0].dispose(); // don't need to retain the Java object reference
434 return inputChannels[1];
435 }
436
437 /**
438 * Registers an input channel so that it can be used as an input event target.
439 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800440 * @param inputWindowHandle The handle of the input window associated with the
441 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700442 */
Jeff Brown928e0542011-01-10 11:17:36 -0800443 public void registerInputChannel(InputChannel inputChannel,
444 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700445 if (inputChannel == null) {
446 throw new IllegalArgumentException("inputChannel must not be null.");
447 }
RoboErikfb290df2013-12-16 11:27:55 -0800448
Jeff Brown4532e612012-04-05 14:27:12 -0700449 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700450 }
RoboErikfb290df2013-12-16 11:27:55 -0800451
Jeff Browna41ca772010-08-11 14:46:32 -0700452 /**
453 * Unregisters an input channel.
454 * @param inputChannel The input channel to unregister.
455 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700456 public void unregisterInputChannel(InputChannel inputChannel) {
457 if (inputChannel == null) {
458 throw new IllegalArgumentException("inputChannel must not be null.");
459 }
RoboErikfb290df2013-12-16 11:27:55 -0800460
Jeff Brown4532e612012-04-05 14:27:12 -0700461 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700462 }
Jeff Brown0029c662011-03-30 02:25:18 -0700463
464 /**
465 * Sets an input filter that will receive all input events before they are dispatched.
466 * The input filter may then reinterpret input events or inject new ones.
467 *
468 * To ensure consistency, the input dispatcher automatically drops all events
469 * in progress whenever an input filter is installed or uninstalled. After an input
470 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
471 * Any events it attempts to send after it has been uninstalled will be dropped.
472 *
473 * @param filter The input filter, or null to remove the current filter.
474 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700475 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700476 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700477 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700478 if (oldFilter == filter) {
479 return; // nothing to do
480 }
481
482 if (oldFilter != null) {
483 mInputFilter = null;
484 mInputFilterHost.disconnectLocked();
485 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700486 try {
487 oldFilter.uninstall();
488 } catch (RemoteException re) {
489 /* ignore */
490 }
Jeff Brown0029c662011-03-30 02:25:18 -0700491 }
492
493 if (filter != null) {
494 mInputFilter = filter;
495 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700496 try {
497 filter.install(mInputFilterHost);
498 } catch (RemoteException re) {
499 /* ignore */
500 }
Jeff Brown0029c662011-03-30 02:25:18 -0700501 }
502
Jeff Brown4532e612012-04-05 14:27:12 -0700503 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700504 }
505 }
506
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700507 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700508 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700509 if (event == null) {
510 throw new IllegalArgumentException("event must not be null");
511 }
Jeff Brownac143512012-04-05 18:57:33 -0700512 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
513 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
514 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
515 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700516 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700517
Jeff Brownac143512012-04-05 18:57:33 -0700518 final int pid = Binder.getCallingPid();
519 final int uid = Binder.getCallingUid();
520 final long ident = Binder.clearCallingIdentity();
521 final int result;
522 try {
523 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
524 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
525 } finally {
526 Binder.restoreCallingIdentity(ident);
527 }
528 switch (result) {
529 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
530 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
531 throw new SecurityException(
532 "Injecting to another application requires INJECT_EVENTS permission");
533 case INPUT_EVENT_INJECTION_SUCCEEDED:
534 return true;
535 case INPUT_EVENT_INJECTION_TIMED_OUT:
536 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
537 return false;
538 case INPUT_EVENT_INJECTION_FAILED:
539 default:
540 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
541 return false;
542 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700543 }
Jeff Brown0029c662011-03-30 02:25:18 -0700544
Jeff Brown8d608662010-08-30 03:02:23 -0700545 /**
546 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700547 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700548 * @return The input device or null if not found.
549 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700550 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700551 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700552 synchronized (mInputDevicesLock) {
553 final int count = mInputDevices.length;
554 for (int i = 0; i < count; i++) {
555 final InputDevice inputDevice = mInputDevices[i];
556 if (inputDevice.getId() == deviceId) {
557 return inputDevice;
558 }
559 }
560 }
561 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700562 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700563
Jeff Brown8d608662010-08-30 03:02:23 -0700564 /**
565 * Gets the ids of all input devices in the system.
566 * @return The input device ids.
567 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700568 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700569 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700570 synchronized (mInputDevicesLock) {
571 final int count = mInputDevices.length;
572 int[] ids = new int[count];
573 for (int i = 0; i < count; i++) {
574 ids[i] = mInputDevices[i].getId();
575 }
576 return ids;
577 }
578 }
579
Jeff Browndaa37532012-05-01 15:54:03 -0700580 /**
581 * Gets all input devices in the system.
582 * @return The array of input devices.
583 */
584 public InputDevice[] getInputDevices() {
585 synchronized (mInputDevicesLock) {
586 return mInputDevices;
587 }
588 }
589
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700590 @Override // Binder call
591 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
592 if (listener == null) {
593 throw new IllegalArgumentException("listener must not be null");
594 }
595
596 synchronized (mInputDevicesLock) {
597 int callingPid = Binder.getCallingPid();
598 if (mInputDevicesChangedListeners.get(callingPid) != null) {
599 throw new SecurityException("The calling process has already "
600 + "registered an InputDevicesChangedListener.");
601 }
602
603 InputDevicesChangedListenerRecord record =
604 new InputDevicesChangedListenerRecord(callingPid, listener);
605 try {
606 IBinder binder = listener.asBinder();
607 binder.linkToDeath(record, 0);
608 } catch (RemoteException ex) {
609 // give up
610 throw new RuntimeException(ex);
611 }
612
613 mInputDevicesChangedListeners.put(callingPid, record);
614 }
615 }
616
617 private void onInputDevicesChangedListenerDied(int pid) {
618 synchronized (mInputDevicesLock) {
619 mInputDevicesChangedListeners.remove(pid);
620 }
621 }
622
623 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700624 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
625 // Scan for changes.
626 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700627 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700628 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700629 final int numListeners;
630 final int[] deviceIdAndGeneration;
631 synchronized (mInputDevicesLock) {
632 if (!mInputDevicesChangedPending) {
633 return;
634 }
635 mInputDevicesChangedPending = false;
636
637 numListeners = mInputDevicesChangedListeners.size();
638 for (int i = 0; i < numListeners; i++) {
639 mTempInputDevicesChangedListenersToNotify.add(
640 mInputDevicesChangedListeners.valueAt(i));
641 }
642
643 final int numDevices = mInputDevices.length;
644 deviceIdAndGeneration = new int[numDevices * 2];
645 for (int i = 0; i < numDevices; i++) {
646 final InputDevice inputDevice = mInputDevices[i];
647 deviceIdAndGeneration[i * 2] = inputDevice.getId();
648 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700649
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700650 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700651 if (!containsInputDeviceWithDescriptor(oldInputDevices,
652 inputDevice.getDescriptor())) {
653 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
654 } else {
655 mTempFullKeyboards.add(inputDevice);
656 }
657 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700658 }
659 }
660
Jeff Browncf39bdf2012-05-18 14:41:19 -0700661 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700662 for (int i = 0; i < numListeners; i++) {
663 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
664 deviceIdAndGeneration);
665 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700666 mTempInputDevicesChangedListenersToNotify.clear();
667
668 // Check for missing keyboard layouts.
669 if (mNotificationManager != null) {
670 final int numFullKeyboards = mTempFullKeyboards.size();
671 boolean missingLayoutForExternalKeyboard = false;
672 boolean missingLayoutForExternalKeyboardAdded = false;
673 synchronized (mDataStore) {
674 for (int i = 0; i < numFullKeyboards; i++) {
675 final InputDevice inputDevice = mTempFullKeyboards.get(i);
676 if (mDataStore.getCurrentKeyboardLayout(inputDevice.getDescriptor()) == null) {
677 missingLayoutForExternalKeyboard = true;
678 if (i < numFullKeyboardsAdded) {
679 missingLayoutForExternalKeyboardAdded = true;
680 }
681 }
682 }
683 }
684 if (missingLayoutForExternalKeyboard) {
685 if (missingLayoutForExternalKeyboardAdded) {
686 showMissingKeyboardLayoutNotification();
687 }
688 } else if (mKeyboardLayoutNotificationShown) {
689 hideMissingKeyboardLayoutNotification();
690 }
691 }
692 mTempFullKeyboards.clear();
693 }
694
695 // Must be called on handler.
696 private void showMissingKeyboardLayoutNotification() {
697 if (!mKeyboardLayoutNotificationShown) {
698 if (mKeyboardLayoutIntent == null) {
699 final Intent intent = new Intent("android.settings.INPUT_METHOD_SETTINGS");
700 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
701 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
702 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700703 mKeyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
704 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700705 }
706
707 Resources r = mContext.getResources();
708 Notification notification = new Notification.Builder(mContext)
709 .setContentTitle(r.getString(
710 R.string.select_keyboard_layout_notification_title))
711 .setContentText(r.getString(
712 R.string.select_keyboard_layout_notification_message))
713 .setContentIntent(mKeyboardLayoutIntent)
714 .setSmallIcon(R.drawable.ic_settings_language)
715 .setPriority(Notification.PRIORITY_LOW)
716 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700717 mNotificationManager.notifyAsUser(null,
718 R.string.select_keyboard_layout_notification_title,
719 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700720 mKeyboardLayoutNotificationShown = true;
721 }
722 }
723
724 // Must be called on handler.
725 private void hideMissingKeyboardLayoutNotification() {
726 if (mKeyboardLayoutNotificationShown) {
727 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700728 mNotificationManager.cancelAsUser(null,
729 R.string.select_keyboard_layout_notification_title,
730 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700731 }
732 }
733
734 // Must be called on handler.
735 private void updateKeyboardLayouts() {
736 // Scan all input devices state for keyboard layouts that have been uninstalled.
737 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
738 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
739 @Override
740 public void visitKeyboardLayout(Resources resources,
741 String descriptor, String label, String collection, int keyboardLayoutResId) {
742 availableKeyboardLayouts.add(descriptor);
743 }
744 });
745 synchronized (mDataStore) {
746 try {
747 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
748 } finally {
749 mDataStore.saveIfNeeded();
750 }
751 }
752
753 // Reload keyboard layouts.
754 reloadKeyboardLayouts();
755 }
756
Jeff Browncf39bdf2012-05-18 14:41:19 -0700757 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
758 String descriptor) {
759 final int numDevices = inputDevices.length;
760 for (int i = 0; i < numDevices; i++) {
761 final InputDevice inputDevice = inputDevices[i];
762 if (inputDevice.getDescriptor().equals(descriptor)) {
763 return true;
764 }
765 }
766 return false;
Jeff Brown8d608662010-08-30 03:02:23 -0700767 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700768
769 @Override // Binder call
770 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700771 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
772 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
773 @Override
774 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700775 String descriptor, String label, String collection, int keyboardLayoutResId) {
776 list.add(new KeyboardLayout(descriptor, label, collection));
Jeff Brown6ec6f792012-04-17 16:52:41 -0700777 }
778 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700779 return list.toArray(new KeyboardLayout[list.size()]);
780 }
781
782 @Override // Binder call
783 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
784 if (keyboardLayoutDescriptor == null) {
785 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
786 }
787
Jeff Brown6ec6f792012-04-17 16:52:41 -0700788 final KeyboardLayout[] result = new KeyboardLayout[1];
789 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
790 @Override
791 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700792 String descriptor, String label, String collection, int keyboardLayoutResId) {
793 result[0] = new KeyboardLayout(descriptor, label, collection);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700794 }
795 });
796 if (result[0] == null) {
797 Log.w(TAG, "Could not get keyboard layout with descriptor '"
798 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700799 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700800 return result[0];
801 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700802
Jeff Brown6ec6f792012-04-17 16:52:41 -0700803 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700804 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700805 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
806 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
807 PackageManager.GET_META_DATA)) {
808 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700809 }
810 }
811
Jeff Brown6ec6f792012-04-17 16:52:41 -0700812 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
813 KeyboardLayoutVisitor visitor) {
814 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
815 if (d != null) {
816 final PackageManager pm = mContext.getPackageManager();
817 try {
818 ActivityInfo receiver = pm.getReceiverInfo(
819 new ComponentName(d.packageName, d.receiverName),
820 PackageManager.GET_META_DATA);
821 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
822 } catch (NameNotFoundException ex) {
823 }
824 }
825 }
826
827 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
828 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700829 Bundle metaData = receiver.metaData;
830 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700831 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700832 }
833
834 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
835 if (configResId == 0) {
836 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
837 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700838 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700839 }
840
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700841 CharSequence receiverLabel = receiver.loadLabel(pm);
842 String collection = receiverLabel != null ? receiverLabel.toString() : "";
843
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700844 try {
845 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
846 XmlResourceParser parser = resources.getXml(configResId);
847 try {
848 XmlUtils.beginDocument(parser, "keyboard-layouts");
849
850 for (;;) {
851 XmlUtils.nextElement(parser);
852 String element = parser.getName();
853 if (element == null) {
854 break;
855 }
856 if (element.equals("keyboard-layout")) {
857 TypedArray a = resources.obtainAttributes(
858 parser, com.android.internal.R.styleable.KeyboardLayout);
859 try {
860 String name = a.getString(
861 com.android.internal.R.styleable.KeyboardLayout_name);
862 String label = a.getString(
863 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -0700864 int keyboardLayoutResId = a.getResourceId(
865 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
866 0);
867 if (name == null || label == null || keyboardLayoutResId == 0) {
868 Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700869 + "attributes in keyboard layout "
870 + "resource from receiver "
871 + receiver.packageName + "/" + receiver.name);
872 } else {
873 String descriptor = KeyboardLayoutDescriptor.format(
874 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700875 if (keyboardName == null || name.equals(keyboardName)) {
876 visitor.visitKeyboardLayout(resources, descriptor,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700877 label, collection, keyboardLayoutResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700878 }
879 }
880 } finally {
881 a.recycle();
882 }
883 } else {
884 Log.w(TAG, "Skipping unrecognized element '" + element
885 + "' in keyboard layout resource from receiver "
886 + receiver.packageName + "/" + receiver.name);
887 }
888 }
889 } finally {
890 parser.close();
891 }
892 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700893 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700894 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700895 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700896 }
897
RoboErikfb290df2013-12-16 11:27:55 -0800898 /**
899 * Builds a layout descriptor for the vendor/product. This returns the
900 * descriptor for ids that aren't useful (such as the default 0, 0).
901 */
902 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
903 if (identifier == null || identifier.getDescriptor() == null) {
904 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700905 }
906
RoboErikfb290df2013-12-16 11:27:55 -0800907 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
908 return identifier.getDescriptor();
909 }
910 StringBuilder bob = new StringBuilder();
911 bob.append("vendor:").append(identifier.getVendorId());
912 bob.append(",product:").append(identifier.getProductId());
913 return bob.toString();
914 }
915
916 @Override // Binder call
917 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
918
919 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -0700920 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -0800921 String layout = null;
922 // try loading it using the layout descriptor if we have it
923 layout = mDataStore.getCurrentKeyboardLayout(key);
924 if (layout == null && !key.equals(identifier.getDescriptor())) {
925 // if it doesn't exist fall back to the device descriptor
926 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
927 }
928 if (DEBUG) {
929 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
930 + layout);
931 }
932 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -0700933 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700934 }
935
936 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800937 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700938 String keyboardLayoutDescriptor) {
939 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700940 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700941 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
942 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700943 if (keyboardLayoutDescriptor == null) {
944 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
945 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700946
RoboErikfb290df2013-12-16 11:27:55 -0800947 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -0700948 synchronized (mDataStore) {
949 try {
RoboErikfb290df2013-12-16 11:27:55 -0800950 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
951 if (DEBUG) {
952 Slog.d(TAG, "Saved keyboard layout using " + key);
953 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700954 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
955 }
Jeff Browna3bc5652012-04-17 11:42:25 -0700956 } finally {
957 mDataStore.saveIfNeeded();
958 }
959 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700960 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700961
Jeff Browncf39bdf2012-05-18 14:41:19 -0700962 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800963 public String[] getKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
964 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700965 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -0800966 String[] layouts = mDataStore.getKeyboardLayouts(key);
967 if ((layouts == null || layouts.length == 0)
968 && !key.equals(identifier.getDescriptor())) {
969 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
970 }
971 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700972 }
973 }
974
975 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800976 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700977 String keyboardLayoutDescriptor) {
978 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
979 "addKeyboardLayoutForInputDevice()")) {
980 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
981 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700982 if (keyboardLayoutDescriptor == null) {
983 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
984 }
985
RoboErikfb290df2013-12-16 11:27:55 -0800986 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700987 synchronized (mDataStore) {
988 try {
RoboErikfb290df2013-12-16 11:27:55 -0800989 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
990 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
991 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
992 }
993 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700994 && !Objects.equal(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -0800995 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700996 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
997 }
998 } finally {
999 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001000 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001001 }
1002 }
1003
1004 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001005 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001006 String keyboardLayoutDescriptor) {
1007 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1008 "removeKeyboardLayoutForInputDevice()")) {
1009 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1010 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001011 if (keyboardLayoutDescriptor == null) {
1012 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1013 }
1014
RoboErikfb290df2013-12-16 11:27:55 -08001015 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001016 synchronized (mDataStore) {
1017 try {
RoboErikfb290df2013-12-16 11:27:55 -08001018 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1019 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1020 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1021 }
1022 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1023 if (!key.equals(identifier.getDescriptor())) {
1024 // We need to remove from both places to ensure it is gone
1025 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1026 keyboardLayoutDescriptor);
1027 }
1028 if (removed && !Objects.equal(oldLayout,
1029 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001030 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1031 }
1032 } finally {
1033 mDataStore.saveIfNeeded();
1034 }
1035 }
1036 }
1037
1038 public void switchKeyboardLayout(int deviceId, int direction) {
1039 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
1040 }
1041
1042 // Must be called on handler.
1043 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1044 final InputDevice device = getInputDevice(deviceId);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001045 if (device != null) {
1046 final boolean changed;
1047 final String keyboardLayoutDescriptor;
RoboErikfb290df2013-12-16 11:27:55 -08001048
1049 String key = getLayoutDescriptor(device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001050 synchronized (mDataStore) {
1051 try {
RoboErikfb290df2013-12-16 11:27:55 -08001052 changed = mDataStore.switchKeyboardLayout(key, direction);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001053 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
RoboErikfb290df2013-12-16 11:27:55 -08001054 key);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001055 } finally {
1056 mDataStore.saveIfNeeded();
1057 }
1058 }
1059
1060 if (changed) {
1061 if (mSwitchedKeyboardLayoutToast != null) {
1062 mSwitchedKeyboardLayoutToast.cancel();
1063 mSwitchedKeyboardLayoutToast = null;
1064 }
1065 if (keyboardLayoutDescriptor != null) {
1066 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1067 if (keyboardLayout != null) {
1068 mSwitchedKeyboardLayoutToast = Toast.makeText(
1069 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1070 mSwitchedKeyboardLayoutToast.show();
1071 }
1072 }
1073
1074 reloadKeyboardLayouts();
1075 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001076 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001077 }
1078
Jeff Brown9302c872011-07-13 22:51:29 -07001079 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001080 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001081 }
RoboErikfb290df2013-12-16 11:27:55 -08001082
Jeff Brown9302c872011-07-13 22:51:29 -07001083 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001084 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001085 }
RoboErikfb290df2013-12-16 11:27:55 -08001086
Jeff Brown349703e2010-06-22 01:27:15 -07001087 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001088 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001089 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001090
1091 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001092 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001093 }
1094
Jeff Browne6504122010-09-27 14:52:15 -07001095 /**
1096 * Atomically transfers touch focus from one window to another as identified by
1097 * their input channels. It is possible for multiple windows to have
1098 * touch focus if they support split touch dispatch
1099 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1100 * method only transfers touch focus of the specified window without affecting
1101 * other windows that may also have touch focus at the same time.
1102 * @param fromChannel The channel of a window that currently has touch focus.
1103 * @param toChannel The channel of the window that should receive touch focus in
1104 * place of the first.
1105 * @return True if the transfer was successful. False if the window with the
1106 * specified channel did not actually have touch focus at the time of the request.
1107 */
1108 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1109 if (fromChannel == null) {
1110 throw new IllegalArgumentException("fromChannel must not be null.");
1111 }
1112 if (toChannel == null) {
1113 throw new IllegalArgumentException("toChannel must not be null.");
1114 }
Jeff Brown4532e612012-04-05 14:27:12 -07001115 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001116 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001117
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001118 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001119 public void tryPointerSpeed(int speed) {
1120 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1121 "tryPointerSpeed()")) {
1122 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1123 }
1124
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001125 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1126 throw new IllegalArgumentException("speed out of range");
1127 }
1128
Jeff Brownac143512012-04-05 18:57:33 -07001129 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001130 }
1131
1132 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001133 int speed = getPointerSpeedSetting();
1134 setPointerSpeedUnchecked(speed);
1135 }
1136
1137 private void setPointerSpeedUnchecked(int speed) {
1138 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1139 InputManager.MAX_POINTER_SPEED);
1140 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001141 }
1142
1143 private void registerPointerSpeedSettingObserver() {
1144 mContext.getContentResolver().registerContentObserver(
1145 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001146 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001147 @Override
1148 public void onChange(boolean selfChange) {
1149 updatePointerSpeedFromSettings();
1150 }
Jeff Brownd4935962012-09-25 13:27:20 -07001151 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001152 }
1153
Jeff Brownac143512012-04-05 18:57:33 -07001154 private int getPointerSpeedSetting() {
1155 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001156 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001157 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1158 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001159 } catch (SettingNotFoundException snfe) {
1160 }
1161 return speed;
1162 }
1163
Jeff Browndaf4a122011-08-26 17:14:14 -07001164 public void updateShowTouchesFromSettings() {
1165 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001166 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001167 }
1168
1169 private void registerShowTouchesSettingObserver() {
1170 mContext.getContentResolver().registerContentObserver(
1171 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001172 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001173 @Override
1174 public void onChange(boolean selfChange) {
1175 updateShowTouchesFromSettings();
1176 }
Jeff Brownd4935962012-09-25 13:27:20 -07001177 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001178 }
1179
1180 private int getShowTouchesSetting(int defaultValue) {
1181 int result = defaultValue;
1182 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001183 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1184 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001185 } catch (SettingNotFoundException snfe) {
1186 }
1187 return result;
1188 }
1189
Jeff Browna47425a2012-04-13 04:09:27 -07001190 // Binder call
1191 @Override
1192 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1193 if (repeat >= pattern.length) {
1194 throw new ArrayIndexOutOfBoundsException();
1195 }
1196
1197 VibratorToken v;
1198 synchronized (mVibratorLock) {
1199 v = mVibratorTokens.get(token);
1200 if (v == null) {
1201 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1202 try {
1203 token.linkToDeath(v, 0);
1204 } catch (RemoteException ex) {
1205 // give up
1206 throw new RuntimeException(ex);
1207 }
1208 mVibratorTokens.put(token, v);
1209 }
1210 }
1211
1212 synchronized (v) {
1213 v.mVibrating = true;
1214 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1215 }
1216 }
1217
1218 // Binder call
1219 @Override
1220 public void cancelVibrate(int deviceId, IBinder token) {
1221 VibratorToken v;
1222 synchronized (mVibratorLock) {
1223 v = mVibratorTokens.get(token);
1224 if (v == null || v.mDeviceId != deviceId) {
1225 return; // nothing to cancel
1226 }
1227 }
1228
1229 cancelVibrateIfNeeded(v);
1230 }
1231
1232 void onVibratorTokenDied(VibratorToken v) {
1233 synchronized (mVibratorLock) {
1234 mVibratorTokens.remove(v.mToken);
1235 }
1236
1237 cancelVibrateIfNeeded(v);
1238 }
1239
1240 private void cancelVibrateIfNeeded(VibratorToken v) {
1241 synchronized (v) {
1242 if (v.mVibrating) {
1243 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1244 v.mVibrating = false;
1245 }
1246 }
1247 }
1248
Jeff Brown4532e612012-04-05 14:27:12 -07001249 @Override
1250 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001251 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001252 != PackageManager.PERMISSION_GRANTED) {
1253 pw.println("Permission Denial: can't dump InputManager from from pid="
1254 + Binder.getCallingPid()
1255 + ", uid=" + Binder.getCallingUid());
1256 return;
1257 }
1258
1259 pw.println("INPUT MANAGER (dumpsys input)\n");
1260 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001261 if (dumpStr != null) {
1262 pw.println(dumpStr);
1263 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001264 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001265
Jeff Brownac143512012-04-05 18:57:33 -07001266 private boolean checkCallingPermission(String permission, String func) {
1267 // Quick check: if the calling permission is me, it's all okay.
1268 if (Binder.getCallingPid() == Process.myPid()) {
1269 return true;
1270 }
1271
1272 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1273 return true;
1274 }
1275 String msg = "Permission Denial: " + func + " from pid="
1276 + Binder.getCallingPid()
1277 + ", uid=" + Binder.getCallingUid()
1278 + " requires " + permission;
1279 Slog.w(TAG, msg);
1280 return false;
1281 }
1282
Jeff Brown4532e612012-04-05 14:27:12 -07001283 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001284 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001285 public void monitor() {
1286 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001287 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001288 }
1289
Jeff Brown4532e612012-04-05 14:27:12 -07001290 // Native callback.
1291 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001292 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001293 }
1294
1295 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001296 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1297 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001298 if (!mInputDevicesChangedPending) {
1299 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001300 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1301 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001302 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001303
1304 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001305 }
1306 }
1307
1308 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001309 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1310 if (DEBUG) {
1311 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1312 + ", mask=" + Integer.toHexString(switchMask));
1313 }
1314
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001315 if ((switchMask & SW_LID_BIT) != 0) {
1316 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001317 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001318 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001319
1320 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1321 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1322 switchMask);
1323 }
Jeff Brown4532e612012-04-05 14:27:12 -07001324 }
1325
1326 // Native callback.
1327 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001328 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001329 }
1330
1331 // Native callback.
1332 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001333 InputWindowHandle inputWindowHandle, String reason) {
1334 return mWindowManagerCallbacks.notifyANR(
1335 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001336 }
1337
1338 // Native callback.
1339 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1340 synchronized (mInputFilterLock) {
1341 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001342 try {
1343 mInputFilter.filterInputEvent(event, policyFlags);
1344 } catch (RemoteException e) {
1345 /* ignore */
1346 }
Jeff Brown4532e612012-04-05 14:27:12 -07001347 return false;
1348 }
1349 }
1350 event.recycle();
1351 return true;
1352 }
1353
1354 // Native callback.
1355 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001356 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(
Jeff Brown4532e612012-04-05 14:27:12 -07001357 event, policyFlags, isScreenOn);
1358 }
1359
1360 // Native callback.
1361 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001362 return mWindowManagerCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001363 }
1364
1365 // Native callback.
1366 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1367 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001368 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001369 }
1370
1371 // Native callback.
1372 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1373 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001374 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001375 }
1376
1377 // Native callback.
1378 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1379 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1380 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1381 }
1382
1383 // Native callback.
1384 private int getVirtualKeyQuietTimeMillis() {
1385 return mContext.getResources().getInteger(
1386 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1387 }
1388
1389 // Native callback.
1390 private String[] getExcludedDeviceNames() {
1391 ArrayList<String> names = new ArrayList<String>();
1392
1393 // Read partner-provided list of excluded input devices
1394 XmlPullParser parser = null;
1395 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1396 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1397 FileReader confreader = null;
1398 try {
1399 confreader = new FileReader(confFile);
1400 parser = Xml.newPullParser();
1401 parser.setInput(confreader);
1402 XmlUtils.beginDocument(parser, "devices");
1403
1404 while (true) {
1405 XmlUtils.nextElement(parser);
1406 if (!"device".equals(parser.getName())) {
1407 break;
1408 }
1409 String name = parser.getAttributeValue(null, "name");
1410 if (name != null) {
1411 names.add(name);
1412 }
1413 }
1414 } catch (FileNotFoundException e) {
1415 // It's ok if the file does not exist.
1416 } catch (Exception e) {
1417 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1418 } finally {
1419 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1420 }
1421
1422 return names.toArray(new String[names.size()]);
1423 }
1424
1425 // Native callback.
1426 private int getKeyRepeatTimeout() {
1427 return ViewConfiguration.getKeyRepeatTimeout();
1428 }
1429
1430 // Native callback.
1431 private int getKeyRepeatDelay() {
1432 return ViewConfiguration.getKeyRepeatDelay();
1433 }
1434
1435 // Native callback.
1436 private int getHoverTapTimeout() {
1437 return ViewConfiguration.getHoverTapTimeout();
1438 }
1439
1440 // Native callback.
1441 private int getHoverTapSlop() {
1442 return ViewConfiguration.getHoverTapSlop();
1443 }
1444
1445 // Native callback.
1446 private int getDoubleTapTimeout() {
1447 return ViewConfiguration.getDoubleTapTimeout();
1448 }
1449
1450 // Native callback.
1451 private int getLongPressTimeout() {
1452 return ViewConfiguration.getLongPressTimeout();
1453 }
1454
1455 // Native callback.
1456 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001457 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001458 }
1459
1460 // Native callback.
1461 private PointerIcon getPointerIcon() {
1462 return PointerIcon.getDefaultIcon(mContext);
1463 }
1464
Jeff Brown6ec6f792012-04-17 16:52:41 -07001465 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001466 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001467 if (!mSystemReady) {
1468 return null;
1469 }
1470
RoboErikfb290df2013-12-16 11:27:55 -08001471 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001472 if (keyboardLayoutDescriptor == null) {
1473 return null;
1474 }
1475
1476 final String[] result = new String[2];
1477 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1478 @Override
1479 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001480 String descriptor, String label, String collection, int keyboardLayoutResId) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001481 try {
1482 result[0] = descriptor;
1483 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001484 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001485 } catch (IOException ex) {
1486 } catch (NotFoundException ex) {
1487 }
1488 }
1489 });
1490 if (result[0] == null) {
1491 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1492 + keyboardLayoutDescriptor + "'.");
1493 return null;
1494 }
1495 return result;
1496 }
1497
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001498 // Native callback.
1499 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001500 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1501 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1502 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001503 }
1504 return null;
1505 }
1506
Jeff Brown4532e612012-04-05 14:27:12 -07001507 /**
1508 * Callback interface implemented by the Window Manager.
1509 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001510 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001511 public void notifyConfigurationChanged();
1512
1513 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1514
1515 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1516
1517 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001518 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001519
1520 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1521
1522 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1523
1524 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1525 KeyEvent event, int policyFlags);
1526
1527 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1528 KeyEvent event, int policyFlags);
1529
1530 public int getPointerLayer();
1531 }
1532
1533 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001534 * Callback interface implemented by WiredAccessoryObserver.
1535 */
1536 public interface WiredAccessoryCallbacks {
1537 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
1538 }
1539
1540 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001541 * Private handler for the input manager.
1542 */
1543 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07001544 public InputManagerHandler(Looper looper) {
1545 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07001546 }
1547
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001548 @Override
1549 public void handleMessage(Message msg) {
1550 switch (msg.what) {
1551 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07001552 deliverInputDevicesChanged((InputDevice[])msg.obj);
1553 break;
1554 case MSG_SWITCH_KEYBOARD_LAYOUT:
1555 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
1556 break;
1557 case MSG_RELOAD_KEYBOARD_LAYOUTS:
1558 reloadKeyboardLayouts();
1559 break;
1560 case MSG_UPDATE_KEYBOARD_LAYOUTS:
1561 updateKeyboardLayouts();
1562 break;
1563 case MSG_RELOAD_DEVICE_ALIASES:
1564 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001565 break;
1566 }
1567 }
1568 }
1569
1570 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001571 * Hosting interface for input filters to call back into the input manager.
1572 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001573 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07001574 private boolean mDisconnected;
1575
1576 public void disconnectLocked() {
1577 mDisconnected = true;
1578 }
1579
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001580 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07001581 public void sendInputEvent(InputEvent event, int policyFlags) {
1582 if (event == null) {
1583 throw new IllegalArgumentException("event must not be null");
1584 }
1585
1586 synchronized (mInputFilterLock) {
1587 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001588 nativeInjectInputEvent(mPtr, event, 0, 0,
1589 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001590 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1591 }
1592 }
1593 }
1594 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001595
1596 private static final class KeyboardLayoutDescriptor {
1597 public String packageName;
1598 public String receiverName;
1599 public String keyboardLayoutName;
1600
1601 public static String format(String packageName,
1602 String receiverName, String keyboardName) {
1603 return packageName + "/" + receiverName + "/" + keyboardName;
1604 }
1605
1606 public static KeyboardLayoutDescriptor parse(String descriptor) {
1607 int pos = descriptor.indexOf('/');
1608 if (pos < 0 || pos + 1 == descriptor.length()) {
1609 return null;
1610 }
1611 int pos2 = descriptor.indexOf('/', pos + 1);
1612 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1613 return null;
1614 }
1615
1616 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1617 result.packageName = descriptor.substring(0, pos);
1618 result.receiverName = descriptor.substring(pos + 1, pos2);
1619 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1620 return result;
1621 }
1622 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001623
Jeff Brown6ec6f792012-04-17 16:52:41 -07001624 private interface KeyboardLayoutVisitor {
1625 void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001626 String descriptor, String label, String collection, int keyboardLayoutResId);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001627 }
1628
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001629 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1630 private final int mPid;
1631 private final IInputDevicesChangedListener mListener;
1632
1633 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1634 mPid = pid;
1635 mListener = listener;
1636 }
1637
1638 @Override
1639 public void binderDied() {
1640 if (DEBUG) {
1641 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1642 }
1643 onInputDevicesChangedListenerDied(mPid);
1644 }
1645
1646 public void notifyInputDevicesChanged(int[] info) {
1647 try {
1648 mListener.onInputDevicesChanged(info);
1649 } catch (RemoteException ex) {
1650 Slog.w(TAG, "Failed to notify process "
1651 + mPid + " that input devices changed, assuming it died.", ex);
1652 binderDied();
1653 }
1654 }
1655 }
Jeff Browna47425a2012-04-13 04:09:27 -07001656
1657 private final class VibratorToken implements DeathRecipient {
1658 public final int mDeviceId;
1659 public final IBinder mToken;
1660 public final int mTokenValue;
1661
1662 public boolean mVibrating;
1663
1664 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1665 mDeviceId = deviceId;
1666 mToken = token;
1667 mTokenValue = tokenValue;
1668 }
1669
1670 @Override
1671 public void binderDied() {
1672 if (DEBUG) {
1673 Slog.d(TAG, "Vibrator token died.");
1674 }
1675 onVibratorTokenDied(this);
1676 }
1677 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001678}