blob: 91786643f7cc7cad7fdfb495d8e98654f69cfb57 [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;
Jeff Brownac143512012-04-05 18:57:33 -070049import android.hardware.input.InputManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070050import android.hardware.input.KeyboardLayout;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070053import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070056import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070057import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080058import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070059import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070060import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070061import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070062import android.provider.Settings;
63import android.provider.Settings.SettingNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070064import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070065import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070066import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070068import android.view.IInputFilter;
69import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070070import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070071import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070072import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080073import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070074import android.view.PointerIcon;
Jeff Browna4547672011-03-02 21:38:11 -080075import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070076import android.view.WindowManagerPolicy;
Jeff Browncf39bdf2012-05-18 14:41:19 -070077import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070078
Jeff Brown46b9ac02010-04-22 18:58:52 -070079import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070080import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070081import java.io.FileNotFoundException;
82import java.io.FileReader;
83import java.io.IOException;
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 Browncf39bdf2012-05-18 14:41:19 -070088import java.util.HashSet;
Jeff Browna3bc5652012-04-17 11:42:25 -070089
Jeff Brown6ec6f792012-04-17 16:52:41 -070090import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -070091import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -070092
93/*
94 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -070095 */
Jeff Brownd728bf52012-09-08 18:05:28 -070096public class InputManagerService extends IInputManager.Stub
97 implements Watchdog.Monitor, DisplayManagerService.InputManagerFuncs {
Jeff Brown46b9ac02010-04-22 18:58:52 -070098 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -070099 static final boolean DEBUG = false;
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;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700104 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
105 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
106 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
107 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700108
Jeff Brown4532e612012-04-05 14:27:12 -0700109 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000110 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700111
Jeff Brown46b9ac02010-04-22 18:58:52 -0700112 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700113 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700114
115 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700116 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700117 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700118 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700119
Jeff Browna3bc5652012-04-17 11:42:25 -0700120 // Persistent data store. Must be locked each time during use.
121 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700122
123 // List of currently registered input devices changed listeners by process id.
124 private Object mInputDevicesLock = new Object();
125 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
126 private InputDevice[] mInputDevices = new InputDevice[0];
127 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
128 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
129 private final ArrayList<InputDevicesChangedListenerRecord>
130 mTempInputDevicesChangedListenersToNotify =
131 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700132 private final ArrayList<InputDevice>
133 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
134 private boolean mKeyboardLayoutNotificationShown;
135 private PendingIntent mKeyboardLayoutIntent;
136 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137
Jeff Browna47425a2012-04-13 04:09:27 -0700138 // State for vibrator tokens.
139 private Object mVibratorLock = new Object();
140 private HashMap<IBinder, VibratorToken> mVibratorTokens =
141 new HashMap<IBinder, VibratorToken>();
142 private int mNextVibratorTokenValue;
143
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700144 // State for the currently installed input filter.
145 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700146 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700147 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700148
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000149 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700150 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000151 private static native void nativeStart(long ptr);
152 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700153 int displayId, int rotation,
154 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700155 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
156 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700157
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000158 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700159 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000160 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700161 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000162 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700163 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000164 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700165 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000166 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800167 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000168 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
169 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
170 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700171 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
172 int policyFlags);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000173 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
174 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
175 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
176 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700177 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000178 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700179 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000180 private static native void nativeSetPointerSpeed(long ptr, int speed);
181 private static native void nativeSetShowTouches(long ptr, boolean enabled);
182 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700183 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000184 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
185 private static native void nativeReloadKeyboardLayouts(long ptr);
186 private static native void nativeReloadDeviceAliases(long ptr);
187 private static native String nativeDump(long ptr);
188 private static native void nativeMonitor(long ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700189
Jeff Brownac143512012-04-05 18:57:33 -0700190 // Input event injection constants defined in InputDispatcher.h.
191 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
192 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
193 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
194 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
195
196 // Maximum number of milliseconds to wait for input event injection.
197 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
198
Jeff Brown6d0fec22010-07-23 21:28:06 -0700199 // Key states (may be returned by queries about the current state of a
200 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700201
Jeff Brown6d0fec22010-07-23 21:28:06 -0700202 /** The key state is unknown or the requested key itself is not supported. */
203 public static final int KEY_STATE_UNKNOWN = -1;
204
205 /** The key is up. /*/
206 public static final int KEY_STATE_UP = 0;
207
208 /** The key is down. */
209 public static final int KEY_STATE_DOWN = 1;
210
211 /** The key is down but is a virtual key press that is being emulated by the system. */
212 public static final int KEY_STATE_VIRTUAL = 2;
213
Jeff Brownc458ce92012-04-30 14:58:40 -0700214 /** Scan code: Mouse / trackball button. */
215 public static final int BTN_MOUSE = 0x110;
216
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700217 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700218 /** Switch code: Lid switch. When set, lid is shut. */
219 public static final int SW_LID = 0x00;
220
221 /** Switch code: Keypad slide. When set, keyboard is exposed. */
222 public static final int SW_KEYPAD_SLIDE = 0x0a;
223
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700224 /** Switch code: Headphone. When set, headphone is inserted. */
225 public static final int SW_HEADPHONE_INSERT = 0x02;
226
227 /** Switch code: Microphone. When set, microphone is inserted. */
228 public static final int SW_MICROPHONE_INSERT = 0x04;
229
230 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
231 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
232
233 public static final int SW_LID_BIT = 1 << SW_LID;
234 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
235 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
236 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
237 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
238 public static final int SW_JACK_BITS =
239 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT;
240
241 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
242 final boolean mUseDevInputEventForAudioJack;
243
Jeff Browna9d131c2012-09-20 16:48:17 -0700244 public InputManagerService(Context context, Handler handler) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700245 this.mContext = context;
Jeff Browna9d131c2012-09-20 16:48:17 -0700246 this.mHandler = new InputManagerHandler(handler.getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800247
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700248 mUseDevInputEventForAudioJack =
249 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
250 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
251 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700252 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700253 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700254
Jeff Browna9d131c2012-09-20 16:48:17 -0700255 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
256 mWindowManagerCallbacks = callbacks;
257 }
258
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700259 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
260 mWiredAccessoryCallbacks = callbacks;
261 }
262
Jeff Brown46b9ac02010-04-22 18:58:52 -0700263 public void start() {
264 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700265 nativeStart(mPtr);
266
267 // Add ourself to the Watchdog monitors.
268 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700269
270 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700271 registerShowTouchesSettingObserver();
272
Jeff Brownd4935962012-09-25 13:27:20 -0700273 mContext.registerReceiver(new BroadcastReceiver() {
274 @Override
275 public void onReceive(Context context, Intent intent) {
276 updatePointerSpeedFromSettings();
277 updateShowTouchesFromSettings();
278 }
279 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
280
Jeff Brown1a84fd12011-06-02 01:26:32 -0700281 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700282 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700283 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700284
Matthew Xie96313142012-06-29 16:57:31 -0700285 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700286 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700287 if (DEBUG) {
288 Slog.d(TAG, "System ready.");
289 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700290 mNotificationManager = (NotificationManager)mContext.getSystemService(
291 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700292 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700293
294 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
295 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
296 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800297 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700298 filter.addDataScheme("package");
299 mContext.registerReceiver(new BroadcastReceiver() {
300 @Override
301 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700302 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700303 }
304 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700305
306 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
307 mContext.registerReceiver(new BroadcastReceiver() {
308 @Override
309 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700310 reloadDeviceAliases();
311 }
312 }, filter, null, mHandler);
313
Jeff Browncf39bdf2012-05-18 14:41:19 -0700314 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
315 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700316 }
317
318 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700319 if (DEBUG) {
320 Slog.d(TAG, "Reloading keyboard layouts.");
321 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700322 nativeReloadKeyboardLayouts(mPtr);
323 }
324
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700325 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700326 if (DEBUG) {
327 Slog.d(TAG, "Reloading device names.");
328 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700329 nativeReloadDeviceAliases(mPtr);
330 }
331
Jeff Brownd728bf52012-09-08 18:05:28 -0700332 @Override
333 public void setDisplayViewports(DisplayViewport defaultViewport,
334 DisplayViewport externalTouchViewport) {
335 if (defaultViewport.valid) {
336 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700337 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700338
339 if (externalTouchViewport.valid) {
340 setDisplayViewport(true, externalTouchViewport);
341 } else if (defaultViewport.valid) {
342 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700343 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700344 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700345
Jeff Brownd728bf52012-09-08 18:05:28 -0700346 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
347 nativeSetDisplayViewport(mPtr, external,
348 viewport.displayId, viewport.orientation,
349 viewport.logicalFrame.left, viewport.logicalFrame.top,
350 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
351 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700352 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
353 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700354 }
Jeff Brownac143512012-04-05 18:57:33 -0700355
Jeff Brown6d0fec22010-07-23 21:28:06 -0700356 /**
357 * Gets the current state of a key or button by key code.
358 * @param deviceId The input device id, or -1 to consult all devices.
359 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
360 * consider all input sources. An input device is consulted if at least one of its
361 * non-class input source bits matches the specified source mask.
362 * @param keyCode The key code to check.
363 * @return The key state.
364 */
365 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700366 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700367 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700368
Jeff Brown6d0fec22010-07-23 21:28:06 -0700369 /**
370 * Gets the current state of a key or button by scan code.
371 * @param deviceId The input device id, or -1 to consult all devices.
372 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
373 * consider all input sources. An input device is consulted if at least one of its
374 * non-class input source bits matches the specified source mask.
375 * @param scanCode The scan code to check.
376 * @return The key state.
377 */
378 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700379 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700380 }
381
Jeff Brown6d0fec22010-07-23 21:28:06 -0700382 /**
383 * Gets the current state of a switch by switch code.
384 * @param deviceId The input device id, or -1 to consult all devices.
385 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
386 * consider all input sources. An input device is consulted if at least one of its
387 * non-class input source bits matches the specified source mask.
388 * @param switchCode The switch code to check.
389 * @return The switch state.
390 */
391 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700392 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700393 }
394
Jeff Brown6d0fec22010-07-23 21:28:06 -0700395 /**
396 * Determines whether the specified key codes are supported by a particular device.
397 * @param deviceId The input device id, or -1 to consult all devices.
398 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
399 * consider all input sources. An input device is consulted if at least one of its
400 * non-class input source bits matches the specified source mask.
401 * @param keyCodes The array of key codes to check.
402 * @param keyExists An array at least as large as keyCodes whose entries will be set
403 * to true or false based on the presence or absence of support for the corresponding
404 * key codes.
405 * @return True if the lookup was successful, false otherwise.
406 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700407 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700408 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700409 if (keyCodes == null) {
410 throw new IllegalArgumentException("keyCodes must not be null.");
411 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700412 if (keyExists == null || keyExists.length < keyCodes.length) {
413 throw new IllegalArgumentException("keyExists must not be null and must be at "
414 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700415 }
416
Jeff Brown4532e612012-04-05 14:27:12 -0700417 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700418 }
419
Jeff Browna41ca772010-08-11 14:46:32 -0700420 /**
421 * Creates an input channel that will receive all input from the input dispatcher.
422 * @param inputChannelName The input channel name.
423 * @return The input channel.
424 */
425 public InputChannel monitorInput(String inputChannelName) {
426 if (inputChannelName == null) {
427 throw new IllegalArgumentException("inputChannelName must not be null.");
428 }
429
430 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700431 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700432 inputChannels[0].dispose(); // don't need to retain the Java object reference
433 return inputChannels[1];
434 }
435
436 /**
437 * Registers an input channel so that it can be used as an input event target.
438 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800439 * @param inputWindowHandle The handle of the input window associated with the
440 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700441 */
Jeff Brown928e0542011-01-10 11:17:36 -0800442 public void registerInputChannel(InputChannel inputChannel,
443 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700444 if (inputChannel == null) {
445 throw new IllegalArgumentException("inputChannel must not be null.");
446 }
447
Jeff Brown4532e612012-04-05 14:27:12 -0700448 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700449 }
450
Jeff Browna41ca772010-08-11 14:46:32 -0700451 /**
452 * Unregisters an input channel.
453 * @param inputChannel The input channel to unregister.
454 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700455 public void unregisterInputChannel(InputChannel inputChannel) {
456 if (inputChannel == null) {
457 throw new IllegalArgumentException("inputChannel must not be null.");
458 }
459
Jeff Brown4532e612012-04-05 14:27:12 -0700460 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700461 }
Jeff Brown0029c662011-03-30 02:25:18 -0700462
463 /**
464 * Sets an input filter that will receive all input events before they are dispatched.
465 * The input filter may then reinterpret input events or inject new ones.
466 *
467 * To ensure consistency, the input dispatcher automatically drops all events
468 * in progress whenever an input filter is installed or uninstalled. After an input
469 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
470 * Any events it attempts to send after it has been uninstalled will be dropped.
471 *
472 * @param filter The input filter, or null to remove the current filter.
473 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700474 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700475 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700476 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700477 if (oldFilter == filter) {
478 return; // nothing to do
479 }
480
481 if (oldFilter != null) {
482 mInputFilter = null;
483 mInputFilterHost.disconnectLocked();
484 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700485 try {
486 oldFilter.uninstall();
487 } catch (RemoteException re) {
488 /* ignore */
489 }
Jeff Brown0029c662011-03-30 02:25:18 -0700490 }
491
492 if (filter != null) {
493 mInputFilter = filter;
494 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700495 try {
496 filter.install(mInputFilterHost);
497 } catch (RemoteException re) {
498 /* ignore */
499 }
Jeff Brown0029c662011-03-30 02:25:18 -0700500 }
501
Jeff Brown4532e612012-04-05 14:27:12 -0700502 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700503 }
504 }
505
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700506 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700507 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700508 if (event == null) {
509 throw new IllegalArgumentException("event must not be null");
510 }
Jeff Brownac143512012-04-05 18:57:33 -0700511 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
512 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
513 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
514 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700515 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700516
Jeff Brownac143512012-04-05 18:57:33 -0700517 final int pid = Binder.getCallingPid();
518 final int uid = Binder.getCallingUid();
519 final long ident = Binder.clearCallingIdentity();
520 final int result;
521 try {
522 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
523 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
524 } finally {
525 Binder.restoreCallingIdentity(ident);
526 }
527 switch (result) {
528 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
529 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
530 throw new SecurityException(
531 "Injecting to another application requires INJECT_EVENTS permission");
532 case INPUT_EVENT_INJECTION_SUCCEEDED:
533 return true;
534 case INPUT_EVENT_INJECTION_TIMED_OUT:
535 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
536 return false;
537 case INPUT_EVENT_INJECTION_FAILED:
538 default:
539 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
540 return false;
541 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700542 }
Jeff Brown0029c662011-03-30 02:25:18 -0700543
Jeff Brown8d608662010-08-30 03:02:23 -0700544 /**
545 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700546 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700547 * @return The input device or null if not found.
548 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700549 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700550 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700551 synchronized (mInputDevicesLock) {
552 final int count = mInputDevices.length;
553 for (int i = 0; i < count; i++) {
554 final InputDevice inputDevice = mInputDevices[i];
555 if (inputDevice.getId() == deviceId) {
556 return inputDevice;
557 }
558 }
559 }
560 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700561 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700562
Jeff Brown8d608662010-08-30 03:02:23 -0700563 /**
564 * Gets the ids of all input devices in the system.
565 * @return The input device ids.
566 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700567 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700568 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700569 synchronized (mInputDevicesLock) {
570 final int count = mInputDevices.length;
571 int[] ids = new int[count];
572 for (int i = 0; i < count; i++) {
573 ids[i] = mInputDevices[i].getId();
574 }
575 return ids;
576 }
577 }
578
Jeff Browndaa37532012-05-01 15:54:03 -0700579 /**
580 * Gets all input devices in the system.
581 * @return The array of input devices.
582 */
583 public InputDevice[] getInputDevices() {
584 synchronized (mInputDevicesLock) {
585 return mInputDevices;
586 }
587 }
588
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700589 @Override // Binder call
590 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
591 if (listener == null) {
592 throw new IllegalArgumentException("listener must not be null");
593 }
594
595 synchronized (mInputDevicesLock) {
596 int callingPid = Binder.getCallingPid();
597 if (mInputDevicesChangedListeners.get(callingPid) != null) {
598 throw new SecurityException("The calling process has already "
599 + "registered an InputDevicesChangedListener.");
600 }
601
602 InputDevicesChangedListenerRecord record =
603 new InputDevicesChangedListenerRecord(callingPid, listener);
604 try {
605 IBinder binder = listener.asBinder();
606 binder.linkToDeath(record, 0);
607 } catch (RemoteException ex) {
608 // give up
609 throw new RuntimeException(ex);
610 }
611
612 mInputDevicesChangedListeners.put(callingPid, record);
613 }
614 }
615
616 private void onInputDevicesChangedListenerDied(int pid) {
617 synchronized (mInputDevicesLock) {
618 mInputDevicesChangedListeners.remove(pid);
619 }
620 }
621
622 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700623 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
624 // Scan for changes.
625 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700626 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700627 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700628 final int numListeners;
629 final int[] deviceIdAndGeneration;
630 synchronized (mInputDevicesLock) {
631 if (!mInputDevicesChangedPending) {
632 return;
633 }
634 mInputDevicesChangedPending = false;
635
636 numListeners = mInputDevicesChangedListeners.size();
637 for (int i = 0; i < numListeners; i++) {
638 mTempInputDevicesChangedListenersToNotify.add(
639 mInputDevicesChangedListeners.valueAt(i));
640 }
641
642 final int numDevices = mInputDevices.length;
643 deviceIdAndGeneration = new int[numDevices * 2];
644 for (int i = 0; i < numDevices; i++) {
645 final InputDevice inputDevice = mInputDevices[i];
646 deviceIdAndGeneration[i * 2] = inputDevice.getId();
647 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700648
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700649 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700650 if (!containsInputDeviceWithDescriptor(oldInputDevices,
651 inputDevice.getDescriptor())) {
652 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
653 } else {
654 mTempFullKeyboards.add(inputDevice);
655 }
656 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700657 }
658 }
659
Jeff Browncf39bdf2012-05-18 14:41:19 -0700660 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700661 for (int i = 0; i < numListeners; i++) {
662 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
663 deviceIdAndGeneration);
664 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700665 mTempInputDevicesChangedListenersToNotify.clear();
666
667 // Check for missing keyboard layouts.
668 if (mNotificationManager != null) {
669 final int numFullKeyboards = mTempFullKeyboards.size();
670 boolean missingLayoutForExternalKeyboard = false;
671 boolean missingLayoutForExternalKeyboardAdded = false;
672 synchronized (mDataStore) {
673 for (int i = 0; i < numFullKeyboards; i++) {
674 final InputDevice inputDevice = mTempFullKeyboards.get(i);
675 if (mDataStore.getCurrentKeyboardLayout(inputDevice.getDescriptor()) == null) {
676 missingLayoutForExternalKeyboard = true;
677 if (i < numFullKeyboardsAdded) {
678 missingLayoutForExternalKeyboardAdded = true;
679 }
680 }
681 }
682 }
683 if (missingLayoutForExternalKeyboard) {
684 if (missingLayoutForExternalKeyboardAdded) {
685 showMissingKeyboardLayoutNotification();
686 }
687 } else if (mKeyboardLayoutNotificationShown) {
688 hideMissingKeyboardLayoutNotification();
689 }
690 }
691 mTempFullKeyboards.clear();
692 }
693
694 // Must be called on handler.
695 private void showMissingKeyboardLayoutNotification() {
696 if (!mKeyboardLayoutNotificationShown) {
697 if (mKeyboardLayoutIntent == null) {
698 final Intent intent = new Intent("android.settings.INPUT_METHOD_SETTINGS");
699 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
700 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
701 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700702 mKeyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
703 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700704 }
705
706 Resources r = mContext.getResources();
707 Notification notification = new Notification.Builder(mContext)
708 .setContentTitle(r.getString(
709 R.string.select_keyboard_layout_notification_title))
710 .setContentText(r.getString(
711 R.string.select_keyboard_layout_notification_message))
712 .setContentIntent(mKeyboardLayoutIntent)
713 .setSmallIcon(R.drawable.ic_settings_language)
714 .setPriority(Notification.PRIORITY_LOW)
715 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700716 mNotificationManager.notifyAsUser(null,
717 R.string.select_keyboard_layout_notification_title,
718 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700719 mKeyboardLayoutNotificationShown = true;
720 }
721 }
722
723 // Must be called on handler.
724 private void hideMissingKeyboardLayoutNotification() {
725 if (mKeyboardLayoutNotificationShown) {
726 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700727 mNotificationManager.cancelAsUser(null,
728 R.string.select_keyboard_layout_notification_title,
729 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700730 }
731 }
732
733 // Must be called on handler.
734 private void updateKeyboardLayouts() {
735 // Scan all input devices state for keyboard layouts that have been uninstalled.
736 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
737 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
738 @Override
739 public void visitKeyboardLayout(Resources resources,
740 String descriptor, String label, String collection, int keyboardLayoutResId) {
741 availableKeyboardLayouts.add(descriptor);
742 }
743 });
744 synchronized (mDataStore) {
745 try {
746 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
747 } finally {
748 mDataStore.saveIfNeeded();
749 }
750 }
751
752 // Reload keyboard layouts.
753 reloadKeyboardLayouts();
754 }
755
Jeff Browncf39bdf2012-05-18 14:41:19 -0700756 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
757 String descriptor) {
758 final int numDevices = inputDevices.length;
759 for (int i = 0; i < numDevices; i++) {
760 final InputDevice inputDevice = inputDevices[i];
761 if (inputDevice.getDescriptor().equals(descriptor)) {
762 return true;
763 }
764 }
765 return false;
Jeff Brown8d608662010-08-30 03:02:23 -0700766 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700767
768 @Override // Binder call
769 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700770 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
771 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
772 @Override
773 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700774 String descriptor, String label, String collection, int keyboardLayoutResId) {
775 list.add(new KeyboardLayout(descriptor, label, collection));
Jeff Brown6ec6f792012-04-17 16:52:41 -0700776 }
777 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700778 return list.toArray(new KeyboardLayout[list.size()]);
779 }
780
781 @Override // Binder call
782 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
783 if (keyboardLayoutDescriptor == null) {
784 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
785 }
786
Jeff Brown6ec6f792012-04-17 16:52:41 -0700787 final KeyboardLayout[] result = new KeyboardLayout[1];
788 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
789 @Override
790 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700791 String descriptor, String label, String collection, int keyboardLayoutResId) {
792 result[0] = new KeyboardLayout(descriptor, label, collection);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700793 }
794 });
795 if (result[0] == null) {
796 Log.w(TAG, "Could not get keyboard layout with descriptor '"
797 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700798 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700799 return result[0];
800 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700801
Jeff Brown6ec6f792012-04-17 16:52:41 -0700802 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700803 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700804 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
805 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
806 PackageManager.GET_META_DATA)) {
807 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700808 }
809 }
810
Jeff Brown6ec6f792012-04-17 16:52:41 -0700811 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
812 KeyboardLayoutVisitor visitor) {
813 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
814 if (d != null) {
815 final PackageManager pm = mContext.getPackageManager();
816 try {
817 ActivityInfo receiver = pm.getReceiverInfo(
818 new ComponentName(d.packageName, d.receiverName),
819 PackageManager.GET_META_DATA);
820 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
821 } catch (NameNotFoundException ex) {
822 }
823 }
824 }
825
826 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
827 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700828 Bundle metaData = receiver.metaData;
829 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700830 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700831 }
832
833 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
834 if (configResId == 0) {
835 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
836 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700837 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700838 }
839
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700840 CharSequence receiverLabel = receiver.loadLabel(pm);
841 String collection = receiverLabel != null ? receiverLabel.toString() : "";
842
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700843 try {
844 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
845 XmlResourceParser parser = resources.getXml(configResId);
846 try {
847 XmlUtils.beginDocument(parser, "keyboard-layouts");
848
849 for (;;) {
850 XmlUtils.nextElement(parser);
851 String element = parser.getName();
852 if (element == null) {
853 break;
854 }
855 if (element.equals("keyboard-layout")) {
856 TypedArray a = resources.obtainAttributes(
857 parser, com.android.internal.R.styleable.KeyboardLayout);
858 try {
859 String name = a.getString(
860 com.android.internal.R.styleable.KeyboardLayout_name);
861 String label = a.getString(
862 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -0700863 int keyboardLayoutResId = a.getResourceId(
864 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
865 0);
866 if (name == null || label == null || keyboardLayoutResId == 0) {
867 Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700868 + "attributes in keyboard layout "
869 + "resource from receiver "
870 + receiver.packageName + "/" + receiver.name);
871 } else {
872 String descriptor = KeyboardLayoutDescriptor.format(
873 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700874 if (keyboardName == null || name.equals(keyboardName)) {
875 visitor.visitKeyboardLayout(resources, descriptor,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700876 label, collection, keyboardLayoutResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700877 }
878 }
879 } finally {
880 a.recycle();
881 }
882 } else {
883 Log.w(TAG, "Skipping unrecognized element '" + element
884 + "' in keyboard layout resource from receiver "
885 + receiver.packageName + "/" + receiver.name);
886 }
887 }
888 } finally {
889 parser.close();
890 }
891 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700892 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700893 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700894 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700895 }
896
897 @Override // Binder call
Jeff Browncf39bdf2012-05-18 14:41:19 -0700898 public String getCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700899 if (inputDeviceDescriptor == null) {
900 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
901 }
902
Jeff Browna3bc5652012-04-17 11:42:25 -0700903 synchronized (mDataStore) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700904 return mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
Jeff Browna3bc5652012-04-17 11:42:25 -0700905 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700906 }
907
908 @Override // Binder call
Jeff Browncf39bdf2012-05-18 14:41:19 -0700909 public void setCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700910 String keyboardLayoutDescriptor) {
911 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700912 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700913 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
914 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700915 if (inputDeviceDescriptor == null) {
916 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
917 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700918 if (keyboardLayoutDescriptor == null) {
919 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
920 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700921
Jeff Browna3bc5652012-04-17 11:42:25 -0700922 synchronized (mDataStore) {
923 try {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700924 if (mDataStore.setCurrentKeyboardLayout(
925 inputDeviceDescriptor, keyboardLayoutDescriptor)) {
926 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
927 }
Jeff Browna3bc5652012-04-17 11:42:25 -0700928 } finally {
929 mDataStore.saveIfNeeded();
930 }
931 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700932 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700933
Jeff Browncf39bdf2012-05-18 14:41:19 -0700934 @Override // Binder call
935 public String[] getKeyboardLayoutsForInputDevice(String inputDeviceDescriptor) {
936 if (inputDeviceDescriptor == null) {
937 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
938 }
939
940 synchronized (mDataStore) {
941 return mDataStore.getKeyboardLayouts(inputDeviceDescriptor);
942 }
943 }
944
945 @Override // Binder call
946 public void addKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
947 String keyboardLayoutDescriptor) {
948 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
949 "addKeyboardLayoutForInputDevice()")) {
950 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
951 }
952 if (inputDeviceDescriptor == null) {
953 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
954 }
955 if (keyboardLayoutDescriptor == null) {
956 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
957 }
958
959 synchronized (mDataStore) {
960 try {
961 String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
962 if (mDataStore.addKeyboardLayout(inputDeviceDescriptor, keyboardLayoutDescriptor)
963 && !Objects.equal(oldLayout,
964 mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
965 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
966 }
967 } finally {
968 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700969 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700970 }
971 }
972
973 @Override // Binder call
974 public void removeKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
975 String keyboardLayoutDescriptor) {
976 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
977 "removeKeyboardLayoutForInputDevice()")) {
978 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
979 }
980 if (inputDeviceDescriptor == null) {
981 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
982 }
983 if (keyboardLayoutDescriptor == null) {
984 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
985 }
986
987 synchronized (mDataStore) {
988 try {
989 String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
990 if (mDataStore.removeKeyboardLayout(inputDeviceDescriptor,
991 keyboardLayoutDescriptor)
992 && !Objects.equal(oldLayout,
993 mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
994 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
995 }
996 } finally {
997 mDataStore.saveIfNeeded();
998 }
999 }
1000 }
1001
1002 public void switchKeyboardLayout(int deviceId, int direction) {
1003 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
1004 }
1005
1006 // Must be called on handler.
1007 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1008 final InputDevice device = getInputDevice(deviceId);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001009 if (device != null) {
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001010 final String inputDeviceDescriptor = device.getDescriptor();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001011 final boolean changed;
1012 final String keyboardLayoutDescriptor;
1013 synchronized (mDataStore) {
1014 try {
1015 changed = mDataStore.switchKeyboardLayout(inputDeviceDescriptor, direction);
1016 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1017 inputDeviceDescriptor);
1018 } finally {
1019 mDataStore.saveIfNeeded();
1020 }
1021 }
1022
1023 if (changed) {
1024 if (mSwitchedKeyboardLayoutToast != null) {
1025 mSwitchedKeyboardLayoutToast.cancel();
1026 mSwitchedKeyboardLayoutToast = null;
1027 }
1028 if (keyboardLayoutDescriptor != null) {
1029 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1030 if (keyboardLayout != null) {
1031 mSwitchedKeyboardLayoutToast = Toast.makeText(
1032 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1033 mSwitchedKeyboardLayoutToast.show();
1034 }
1035 }
1036
1037 reloadKeyboardLayouts();
1038 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001039 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001040 }
1041
Jeff Brown9302c872011-07-13 22:51:29 -07001042 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001043 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001044 }
1045
Jeff Brown9302c872011-07-13 22:51:29 -07001046 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001047 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001048 }
1049
Jeff Brown349703e2010-06-22 01:27:15 -07001050 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001051 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001052 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001053
1054 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001055 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001056 }
1057
Jeff Browne6504122010-09-27 14:52:15 -07001058 /**
1059 * Atomically transfers touch focus from one window to another as identified by
1060 * their input channels. It is possible for multiple windows to have
1061 * touch focus if they support split touch dispatch
1062 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1063 * method only transfers touch focus of the specified window without affecting
1064 * other windows that may also have touch focus at the same time.
1065 * @param fromChannel The channel of a window that currently has touch focus.
1066 * @param toChannel The channel of the window that should receive touch focus in
1067 * place of the first.
1068 * @return True if the transfer was successful. False if the window with the
1069 * specified channel did not actually have touch focus at the time of the request.
1070 */
1071 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1072 if (fromChannel == null) {
1073 throw new IllegalArgumentException("fromChannel must not be null.");
1074 }
1075 if (toChannel == null) {
1076 throw new IllegalArgumentException("toChannel must not be null.");
1077 }
Jeff Brown4532e612012-04-05 14:27:12 -07001078 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001079 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001080
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001081 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001082 public void tryPointerSpeed(int speed) {
1083 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1084 "tryPointerSpeed()")) {
1085 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1086 }
1087
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001088 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1089 throw new IllegalArgumentException("speed out of range");
1090 }
1091
Jeff Brownac143512012-04-05 18:57:33 -07001092 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001093 }
1094
1095 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001096 int speed = getPointerSpeedSetting();
1097 setPointerSpeedUnchecked(speed);
1098 }
1099
1100 private void setPointerSpeedUnchecked(int speed) {
1101 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1102 InputManager.MAX_POINTER_SPEED);
1103 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001104 }
1105
1106 private void registerPointerSpeedSettingObserver() {
1107 mContext.getContentResolver().registerContentObserver(
1108 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001109 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001110 @Override
1111 public void onChange(boolean selfChange) {
1112 updatePointerSpeedFromSettings();
1113 }
Jeff Brownd4935962012-09-25 13:27:20 -07001114 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001115 }
1116
Jeff Brownac143512012-04-05 18:57:33 -07001117 private int getPointerSpeedSetting() {
1118 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001119 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001120 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1121 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001122 } catch (SettingNotFoundException snfe) {
1123 }
1124 return speed;
1125 }
1126
Jeff Browndaf4a122011-08-26 17:14:14 -07001127 public void updateShowTouchesFromSettings() {
1128 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001129 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001130 }
1131
1132 private void registerShowTouchesSettingObserver() {
1133 mContext.getContentResolver().registerContentObserver(
1134 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001135 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001136 @Override
1137 public void onChange(boolean selfChange) {
1138 updateShowTouchesFromSettings();
1139 }
Jeff Brownd4935962012-09-25 13:27:20 -07001140 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001141 }
1142
1143 private int getShowTouchesSetting(int defaultValue) {
1144 int result = defaultValue;
1145 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001146 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1147 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001148 } catch (SettingNotFoundException snfe) {
1149 }
1150 return result;
1151 }
1152
Jeff Browna47425a2012-04-13 04:09:27 -07001153 // Binder call
1154 @Override
1155 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1156 if (repeat >= pattern.length) {
1157 throw new ArrayIndexOutOfBoundsException();
1158 }
1159
1160 VibratorToken v;
1161 synchronized (mVibratorLock) {
1162 v = mVibratorTokens.get(token);
1163 if (v == null) {
1164 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1165 try {
1166 token.linkToDeath(v, 0);
1167 } catch (RemoteException ex) {
1168 // give up
1169 throw new RuntimeException(ex);
1170 }
1171 mVibratorTokens.put(token, v);
1172 }
1173 }
1174
1175 synchronized (v) {
1176 v.mVibrating = true;
1177 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1178 }
1179 }
1180
1181 // Binder call
1182 @Override
1183 public void cancelVibrate(int deviceId, IBinder token) {
1184 VibratorToken v;
1185 synchronized (mVibratorLock) {
1186 v = mVibratorTokens.get(token);
1187 if (v == null || v.mDeviceId != deviceId) {
1188 return; // nothing to cancel
1189 }
1190 }
1191
1192 cancelVibrateIfNeeded(v);
1193 }
1194
1195 void onVibratorTokenDied(VibratorToken v) {
1196 synchronized (mVibratorLock) {
1197 mVibratorTokens.remove(v.mToken);
1198 }
1199
1200 cancelVibrateIfNeeded(v);
1201 }
1202
1203 private void cancelVibrateIfNeeded(VibratorToken v) {
1204 synchronized (v) {
1205 if (v.mVibrating) {
1206 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1207 v.mVibrating = false;
1208 }
1209 }
1210 }
1211
Jeff Brown4532e612012-04-05 14:27:12 -07001212 @Override
1213 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001214 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001215 != PackageManager.PERMISSION_GRANTED) {
1216 pw.println("Permission Denial: can't dump InputManager from from pid="
1217 + Binder.getCallingPid()
1218 + ", uid=" + Binder.getCallingUid());
1219 return;
1220 }
1221
1222 pw.println("INPUT MANAGER (dumpsys input)\n");
1223 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001224 if (dumpStr != null) {
1225 pw.println(dumpStr);
1226 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001227 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001228
Jeff Brownac143512012-04-05 18:57:33 -07001229 private boolean checkCallingPermission(String permission, String func) {
1230 // Quick check: if the calling permission is me, it's all okay.
1231 if (Binder.getCallingPid() == Process.myPid()) {
1232 return true;
1233 }
1234
1235 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1236 return true;
1237 }
1238 String msg = "Permission Denial: " + func + " from pid="
1239 + Binder.getCallingPid()
1240 + ", uid=" + Binder.getCallingUid()
1241 + " requires " + permission;
1242 Slog.w(TAG, msg);
1243 return false;
1244 }
1245
Jeff Brown4532e612012-04-05 14:27:12 -07001246 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001247 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001248 public void monitor() {
1249 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001250 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001251 }
1252
Jeff Brown4532e612012-04-05 14:27:12 -07001253 // Native callback.
1254 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001255 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001256 }
1257
1258 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001259 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1260 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001261 if (!mInputDevicesChangedPending) {
1262 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001263 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1264 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001265 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001266
1267 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001268 }
1269 }
1270
1271 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001272 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1273 if (DEBUG) {
1274 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1275 + ", mask=" + Integer.toHexString(switchMask));
1276 }
1277
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001278 if ((switchMask & SW_LID_BIT) != 0) {
1279 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001280 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001281 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001282
1283 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1284 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1285 switchMask);
1286 }
Jeff Brown4532e612012-04-05 14:27:12 -07001287 }
1288
1289 // Native callback.
1290 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001291 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001292 }
1293
1294 // Native callback.
1295 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001296 InputWindowHandle inputWindowHandle, String reason) {
1297 return mWindowManagerCallbacks.notifyANR(
1298 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001299 }
1300
1301 // Native callback.
1302 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1303 synchronized (mInputFilterLock) {
1304 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001305 try {
1306 mInputFilter.filterInputEvent(event, policyFlags);
1307 } catch (RemoteException e) {
1308 /* ignore */
1309 }
Jeff Brown4532e612012-04-05 14:27:12 -07001310 return false;
1311 }
1312 }
1313 event.recycle();
1314 return true;
1315 }
1316
1317 // Native callback.
1318 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001319 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(
Jeff Brown4532e612012-04-05 14:27:12 -07001320 event, policyFlags, isScreenOn);
1321 }
1322
1323 // Native callback.
1324 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001325 return mWindowManagerCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001326 }
1327
1328 // Native callback.
1329 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1330 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001331 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001332 }
1333
1334 // Native callback.
1335 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1336 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001337 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001338 }
1339
1340 // Native callback.
1341 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1342 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1343 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1344 }
1345
1346 // Native callback.
1347 private int getVirtualKeyQuietTimeMillis() {
1348 return mContext.getResources().getInteger(
1349 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1350 }
1351
1352 // Native callback.
1353 private String[] getExcludedDeviceNames() {
1354 ArrayList<String> names = new ArrayList<String>();
1355
1356 // Read partner-provided list of excluded input devices
1357 XmlPullParser parser = null;
1358 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1359 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1360 FileReader confreader = null;
1361 try {
1362 confreader = new FileReader(confFile);
1363 parser = Xml.newPullParser();
1364 parser.setInput(confreader);
1365 XmlUtils.beginDocument(parser, "devices");
1366
1367 while (true) {
1368 XmlUtils.nextElement(parser);
1369 if (!"device".equals(parser.getName())) {
1370 break;
1371 }
1372 String name = parser.getAttributeValue(null, "name");
1373 if (name != null) {
1374 names.add(name);
1375 }
1376 }
1377 } catch (FileNotFoundException e) {
1378 // It's ok if the file does not exist.
1379 } catch (Exception e) {
1380 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1381 } finally {
1382 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1383 }
1384
1385 return names.toArray(new String[names.size()]);
1386 }
1387
1388 // Native callback.
1389 private int getKeyRepeatTimeout() {
1390 return ViewConfiguration.getKeyRepeatTimeout();
1391 }
1392
1393 // Native callback.
1394 private int getKeyRepeatDelay() {
1395 return ViewConfiguration.getKeyRepeatDelay();
1396 }
1397
1398 // Native callback.
1399 private int getHoverTapTimeout() {
1400 return ViewConfiguration.getHoverTapTimeout();
1401 }
1402
1403 // Native callback.
1404 private int getHoverTapSlop() {
1405 return ViewConfiguration.getHoverTapSlop();
1406 }
1407
1408 // Native callback.
1409 private int getDoubleTapTimeout() {
1410 return ViewConfiguration.getDoubleTapTimeout();
1411 }
1412
1413 // Native callback.
1414 private int getLongPressTimeout() {
1415 return ViewConfiguration.getLongPressTimeout();
1416 }
1417
1418 // Native callback.
1419 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001420 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001421 }
1422
1423 // Native callback.
1424 private PointerIcon getPointerIcon() {
1425 return PointerIcon.getDefaultIcon(mContext);
1426 }
1427
Jeff Brown6ec6f792012-04-17 16:52:41 -07001428 // Native callback.
1429 private String[] getKeyboardLayoutOverlay(String inputDeviceDescriptor) {
1430 if (!mSystemReady) {
1431 return null;
1432 }
1433
Jeff Browncf39bdf2012-05-18 14:41:19 -07001434 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(
1435 inputDeviceDescriptor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001436 if (keyboardLayoutDescriptor == null) {
1437 return null;
1438 }
1439
1440 final String[] result = new String[2];
1441 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1442 @Override
1443 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001444 String descriptor, String label, String collection, int keyboardLayoutResId) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001445 try {
1446 result[0] = descriptor;
1447 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001448 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001449 } catch (IOException ex) {
1450 } catch (NotFoundException ex) {
1451 }
1452 }
1453 });
1454 if (result[0] == null) {
1455 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1456 + keyboardLayoutDescriptor + "'.");
1457 return null;
1458 }
1459 return result;
1460 }
1461
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001462 // Native callback.
1463 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001464 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1465 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1466 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001467 }
1468 return null;
1469 }
1470
Jeff Brown4532e612012-04-05 14:27:12 -07001471 /**
1472 * Callback interface implemented by the Window Manager.
1473 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001474 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001475 public void notifyConfigurationChanged();
1476
1477 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1478
1479 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1480
1481 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001482 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001483
1484 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1485
1486 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1487
1488 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1489 KeyEvent event, int policyFlags);
1490
1491 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1492 KeyEvent event, int policyFlags);
1493
1494 public int getPointerLayer();
1495 }
1496
1497 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001498 * Callback interface implemented by WiredAccessoryObserver.
1499 */
1500 public interface WiredAccessoryCallbacks {
1501 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
1502 }
1503
1504 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001505 * Private handler for the input manager.
1506 */
1507 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07001508 public InputManagerHandler(Looper looper) {
1509 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07001510 }
1511
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001512 @Override
1513 public void handleMessage(Message msg) {
1514 switch (msg.what) {
1515 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07001516 deliverInputDevicesChanged((InputDevice[])msg.obj);
1517 break;
1518 case MSG_SWITCH_KEYBOARD_LAYOUT:
1519 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
1520 break;
1521 case MSG_RELOAD_KEYBOARD_LAYOUTS:
1522 reloadKeyboardLayouts();
1523 break;
1524 case MSG_UPDATE_KEYBOARD_LAYOUTS:
1525 updateKeyboardLayouts();
1526 break;
1527 case MSG_RELOAD_DEVICE_ALIASES:
1528 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001529 break;
1530 }
1531 }
1532 }
1533
1534 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001535 * Hosting interface for input filters to call back into the input manager.
1536 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001537 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07001538 private boolean mDisconnected;
1539
1540 public void disconnectLocked() {
1541 mDisconnected = true;
1542 }
1543
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001544 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07001545 public void sendInputEvent(InputEvent event, int policyFlags) {
1546 if (event == null) {
1547 throw new IllegalArgumentException("event must not be null");
1548 }
1549
1550 synchronized (mInputFilterLock) {
1551 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001552 nativeInjectInputEvent(mPtr, event, 0, 0,
1553 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001554 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1555 }
1556 }
1557 }
1558 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001559
1560 private static final class KeyboardLayoutDescriptor {
1561 public String packageName;
1562 public String receiverName;
1563 public String keyboardLayoutName;
1564
1565 public static String format(String packageName,
1566 String receiverName, String keyboardName) {
1567 return packageName + "/" + receiverName + "/" + keyboardName;
1568 }
1569
1570 public static KeyboardLayoutDescriptor parse(String descriptor) {
1571 int pos = descriptor.indexOf('/');
1572 if (pos < 0 || pos + 1 == descriptor.length()) {
1573 return null;
1574 }
1575 int pos2 = descriptor.indexOf('/', pos + 1);
1576 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1577 return null;
1578 }
1579
1580 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1581 result.packageName = descriptor.substring(0, pos);
1582 result.receiverName = descriptor.substring(pos + 1, pos2);
1583 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1584 return result;
1585 }
1586 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001587
Jeff Brown6ec6f792012-04-17 16:52:41 -07001588 private interface KeyboardLayoutVisitor {
1589 void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001590 String descriptor, String label, String collection, int keyboardLayoutResId);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001591 }
1592
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001593 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1594 private final int mPid;
1595 private final IInputDevicesChangedListener mListener;
1596
1597 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1598 mPid = pid;
1599 mListener = listener;
1600 }
1601
1602 @Override
1603 public void binderDied() {
1604 if (DEBUG) {
1605 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1606 }
1607 onInputDevicesChangedListenerDied(mPid);
1608 }
1609
1610 public void notifyInputDevicesChanged(int[] info) {
1611 try {
1612 mListener.onInputDevicesChanged(info);
1613 } catch (RemoteException ex) {
1614 Slog.w(TAG, "Failed to notify process "
1615 + mPid + " that input devices changed, assuming it died.", ex);
1616 binderDied();
1617 }
1618 }
1619 }
Jeff Browna47425a2012-04-13 04:09:27 -07001620
1621 private final class VibratorToken implements DeathRecipient {
1622 public final int mDeviceId;
1623 public final IBinder mToken;
1624 public final int mTokenValue;
1625
1626 public boolean mVibrating;
1627
1628 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1629 mDeviceId = deviceId;
1630 mToken = token;
1631 mTokenValue = tokenValue;
1632 }
1633
1634 @Override
1635 public void binderDied() {
1636 if (DEBUG) {
1637 Slog.d(TAG, "Vibrator token died.");
1638 }
1639 onVibratorTokenDied(this);
1640 }
1641 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001642}