blob: 1522fd130750b9da619fb201659ab24614324c04 [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 Brown4ccb8232014-01-16 22:16:42 -080021import com.android.server.DisplayThread;
22import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070023import com.android.server.Watchdog;
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 Brown4ccb8232014-01-16 22:16:42 -080047import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070048import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070049import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080050import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070051import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080052import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070053import android.hardware.input.KeyboardLayout;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070055import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070056import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070057import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070059import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070060import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080061import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070062import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070063import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070064import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070065import android.provider.Settings;
66import android.provider.Settings.SettingNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070067import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070070import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070073import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070074import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070075import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080076import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070077import android.view.PointerIcon;
Jeff Browna4547672011-03-02 21:38:11 -080078import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070079import android.view.WindowManagerPolicy;
Jeff Browncf39bdf2012-05-18 14:41:19 -070080import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070081
Jeff Brown46b9ac02010-04-22 18:58:52 -070082import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070083import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070084import java.io.FileNotFoundException;
85import java.io.FileReader;
86import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -070087import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -070088import java.io.PrintWriter;
89import java.util.ArrayList;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070090import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -070091import java.util.HashSet;
Jeff Browna3bc5652012-04-17 11:42:25 -070092
Jeff Brown6ec6f792012-04-17 16:52:41 -070093import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -070094import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -070095
96/*
97 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -070098 */
Jeff Brownd728bf52012-09-08 18:05:28 -070099public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800100 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700101 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700102 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700103
Jeff Brown4532e612012-04-05 14:27:12 -0700104 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
105
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700106 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700107 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
108 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
109 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
110 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700111
Jeff Brown4532e612012-04-05 14:27:12 -0700112 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000113 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700114
Jeff Brown46b9ac02010-04-22 18:58:52 -0700115 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700116 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700117
118 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700119 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700120 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700121 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700122
Jeff Browna3bc5652012-04-17 11:42:25 -0700123 // Persistent data store. Must be locked each time during use.
124 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700125
126 // List of currently registered input devices changed listeners by process id.
127 private Object mInputDevicesLock = new Object();
128 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
129 private InputDevice[] mInputDevices = new InputDevice[0];
130 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
131 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
132 private final ArrayList<InputDevicesChangedListenerRecord>
133 mTempInputDevicesChangedListenersToNotify =
134 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700135 private final ArrayList<InputDevice>
136 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
137 private boolean mKeyboardLayoutNotificationShown;
138 private PendingIntent mKeyboardLayoutIntent;
139 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700140
Jeff Browna47425a2012-04-13 04:09:27 -0700141 // State for vibrator tokens.
142 private Object mVibratorLock = new Object();
143 private HashMap<IBinder, VibratorToken> mVibratorTokens =
144 new HashMap<IBinder, VibratorToken>();
145 private int mNextVibratorTokenValue;
146
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700147 // State for the currently installed input filter.
148 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700149 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700150 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700151
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000152 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700153 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000154 private static native void nativeStart(long ptr);
155 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700156 int displayId, int rotation,
157 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700158 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
159 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700160
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000161 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700162 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000163 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700164 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000165 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700166 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000167 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700168 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000169 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800170 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000171 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
172 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
173 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700174 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
175 int policyFlags);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000176 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
177 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
178 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
179 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700180 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000181 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700182 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000183 private static native void nativeSetPointerSpeed(long ptr, int speed);
184 private static native void nativeSetShowTouches(long ptr, boolean enabled);
185 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700186 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
188 private static native void nativeReloadKeyboardLayouts(long ptr);
189 private static native void nativeReloadDeviceAliases(long ptr);
190 private static native String nativeDump(long ptr);
191 private static native void nativeMonitor(long ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700192
Jeff Brownac143512012-04-05 18:57:33 -0700193 // Input event injection constants defined in InputDispatcher.h.
194 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
195 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
196 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
197 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
198
199 // Maximum number of milliseconds to wait for input event injection.
200 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
201
Jeff Brown6d0fec22010-07-23 21:28:06 -0700202 // Key states (may be returned by queries about the current state of a
203 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700204
Jeff Brown6d0fec22010-07-23 21:28:06 -0700205 /** The key state is unknown or the requested key itself is not supported. */
206 public static final int KEY_STATE_UNKNOWN = -1;
207
208 /** The key is up. /*/
209 public static final int KEY_STATE_UP = 0;
210
211 /** The key is down. */
212 public static final int KEY_STATE_DOWN = 1;
213
214 /** The key is down but is a virtual key press that is being emulated by the system. */
215 public static final int KEY_STATE_VIRTUAL = 2;
216
Jeff Brownc458ce92012-04-30 14:58:40 -0700217 /** Scan code: Mouse / trackball button. */
218 public static final int BTN_MOUSE = 0x110;
219
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700220 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700221 /** Switch code: Lid switch. When set, lid is shut. */
222 public static final int SW_LID = 0x00;
223
224 /** Switch code: Keypad slide. When set, keyboard is exposed. */
225 public static final int SW_KEYPAD_SLIDE = 0x0a;
226
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700227 /** Switch code: Headphone. When set, headphone is inserted. */
228 public static final int SW_HEADPHONE_INSERT = 0x02;
229
230 /** Switch code: Microphone. When set, microphone is inserted. */
231 public static final int SW_MICROPHONE_INSERT = 0x04;
232
233 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
234 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
235
236 public static final int SW_LID_BIT = 1 << SW_LID;
237 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
238 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
239 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
240 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
241 public static final int SW_JACK_BITS =
242 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT;
243
244 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
245 final boolean mUseDevInputEventForAudioJack;
246
Jeff Brown4ccb8232014-01-16 22:16:42 -0800247 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700248 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800249 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800250
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700251 mUseDevInputEventForAudioJack =
252 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
253 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
254 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700255 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800256
257 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700258 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700259
Jeff Browna9d131c2012-09-20 16:48:17 -0700260 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
261 mWindowManagerCallbacks = callbacks;
262 }
263
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700264 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
265 mWiredAccessoryCallbacks = callbacks;
266 }
267
Jeff Brown46b9ac02010-04-22 18:58:52 -0700268 public void start() {
269 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700270 nativeStart(mPtr);
271
272 // Add ourself to the Watchdog monitors.
273 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700274
275 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700276 registerShowTouchesSettingObserver();
277
Jeff Brownd4935962012-09-25 13:27:20 -0700278 mContext.registerReceiver(new BroadcastReceiver() {
279 @Override
280 public void onReceive(Context context, Intent intent) {
281 updatePointerSpeedFromSettings();
282 updateShowTouchesFromSettings();
283 }
284 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
285
Jeff Brown1a84fd12011-06-02 01:26:32 -0700286 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700287 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700288 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700289
Matthew Xie96313142012-06-29 16:57:31 -0700290 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700291 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700292 if (DEBUG) {
293 Slog.d(TAG, "System ready.");
294 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700295 mNotificationManager = (NotificationManager)mContext.getSystemService(
296 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700297 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700298
299 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
300 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
301 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800302 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700303 filter.addDataScheme("package");
304 mContext.registerReceiver(new BroadcastReceiver() {
305 @Override
306 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700307 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700308 }
309 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700310
311 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
312 mContext.registerReceiver(new BroadcastReceiver() {
313 @Override
314 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700315 reloadDeviceAliases();
316 }
317 }, filter, null, mHandler);
318
Jeff Browncf39bdf2012-05-18 14:41:19 -0700319 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
320 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700321 }
322
323 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700324 if (DEBUG) {
325 Slog.d(TAG, "Reloading keyboard layouts.");
326 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700327 nativeReloadKeyboardLayouts(mPtr);
328 }
329
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700330 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700331 if (DEBUG) {
332 Slog.d(TAG, "Reloading device names.");
333 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700334 nativeReloadDeviceAliases(mPtr);
335 }
336
Jeff Brown4ccb8232014-01-16 22:16:42 -0800337 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Jeff Brownd728bf52012-09-08 18:05:28 -0700338 DisplayViewport externalTouchViewport) {
339 if (defaultViewport.valid) {
340 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700341 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700342
343 if (externalTouchViewport.valid) {
344 setDisplayViewport(true, externalTouchViewport);
345 } else if (defaultViewport.valid) {
346 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700347 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700348 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700349
Jeff Brownd728bf52012-09-08 18:05:28 -0700350 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
351 nativeSetDisplayViewport(mPtr, external,
352 viewport.displayId, viewport.orientation,
353 viewport.logicalFrame.left, viewport.logicalFrame.top,
354 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
355 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700356 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
357 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700358 }
Jeff Brownac143512012-04-05 18:57:33 -0700359
Jeff Brown6d0fec22010-07-23 21:28:06 -0700360 /**
361 * Gets the current state of a key or button by key code.
362 * @param deviceId The input device id, or -1 to consult all devices.
363 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
364 * consider all input sources. An input device is consulted if at least one of its
365 * non-class input source bits matches the specified source mask.
366 * @param keyCode The key code to check.
367 * @return The key state.
368 */
369 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700370 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700371 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700372
Jeff Brown6d0fec22010-07-23 21:28:06 -0700373 /**
374 * Gets the current state of a key or button by scan code.
375 * @param deviceId The input device id, or -1 to consult all devices.
376 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
377 * consider all input sources. An input device is consulted if at least one of its
378 * non-class input source bits matches the specified source mask.
379 * @param scanCode The scan code to check.
380 * @return The key state.
381 */
382 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700383 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700384 }
RoboErikfb290df2013-12-16 11:27:55 -0800385
Jeff Brown6d0fec22010-07-23 21:28:06 -0700386 /**
387 * Gets the current state of a switch by switch code.
388 * @param deviceId The input device id, or -1 to consult all devices.
389 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
390 * consider all input sources. An input device is consulted if at least one of its
391 * non-class input source bits matches the specified source mask.
392 * @param switchCode The switch code to check.
393 * @return The switch state.
394 */
395 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700396 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700397 }
398
Jeff Brown6d0fec22010-07-23 21:28:06 -0700399 /**
400 * Determines whether the specified key codes are supported by a particular device.
401 * @param deviceId The input device id, or -1 to consult all devices.
402 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
403 * consider all input sources. An input device is consulted if at least one of its
404 * non-class input source bits matches the specified source mask.
405 * @param keyCodes The array of key codes to check.
406 * @param keyExists An array at least as large as keyCodes whose entries will be set
407 * to true or false based on the presence or absence of support for the corresponding
408 * key codes.
409 * @return True if the lookup was successful, false otherwise.
410 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700411 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700412 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700413 if (keyCodes == null) {
414 throw new IllegalArgumentException("keyCodes must not be null.");
415 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700416 if (keyExists == null || keyExists.length < keyCodes.length) {
417 throw new IllegalArgumentException("keyExists must not be null and must be at "
418 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700419 }
RoboErikfb290df2013-12-16 11:27:55 -0800420
Jeff Brown4532e612012-04-05 14:27:12 -0700421 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700422 }
RoboErikfb290df2013-12-16 11:27:55 -0800423
Jeff Browna41ca772010-08-11 14:46:32 -0700424 /**
425 * Creates an input channel that will receive all input from the input dispatcher.
426 * @param inputChannelName The input channel name.
427 * @return The input channel.
428 */
429 public InputChannel monitorInput(String inputChannelName) {
430 if (inputChannelName == null) {
431 throw new IllegalArgumentException("inputChannelName must not be null.");
432 }
RoboErikfb290df2013-12-16 11:27:55 -0800433
Jeff Browna41ca772010-08-11 14:46:32 -0700434 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700435 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700436 inputChannels[0].dispose(); // don't need to retain the Java object reference
437 return inputChannels[1];
438 }
439
440 /**
441 * Registers an input channel so that it can be used as an input event target.
442 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800443 * @param inputWindowHandle The handle of the input window associated with the
444 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700445 */
Jeff Brown928e0542011-01-10 11:17:36 -0800446 public void registerInputChannel(InputChannel inputChannel,
447 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700448 if (inputChannel == null) {
449 throw new IllegalArgumentException("inputChannel must not be null.");
450 }
RoboErikfb290df2013-12-16 11:27:55 -0800451
Jeff Brown4532e612012-04-05 14:27:12 -0700452 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700453 }
RoboErikfb290df2013-12-16 11:27:55 -0800454
Jeff Browna41ca772010-08-11 14:46:32 -0700455 /**
456 * Unregisters an input channel.
457 * @param inputChannel The input channel to unregister.
458 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700459 public void unregisterInputChannel(InputChannel inputChannel) {
460 if (inputChannel == null) {
461 throw new IllegalArgumentException("inputChannel must not be null.");
462 }
RoboErikfb290df2013-12-16 11:27:55 -0800463
Jeff Brown4532e612012-04-05 14:27:12 -0700464 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700465 }
Jeff Brown0029c662011-03-30 02:25:18 -0700466
467 /**
468 * Sets an input filter that will receive all input events before they are dispatched.
469 * The input filter may then reinterpret input events or inject new ones.
470 *
471 * To ensure consistency, the input dispatcher automatically drops all events
472 * in progress whenever an input filter is installed or uninstalled. After an input
473 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
474 * Any events it attempts to send after it has been uninstalled will be dropped.
475 *
476 * @param filter The input filter, or null to remove the current filter.
477 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700478 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700479 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700480 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700481 if (oldFilter == filter) {
482 return; // nothing to do
483 }
484
485 if (oldFilter != null) {
486 mInputFilter = null;
487 mInputFilterHost.disconnectLocked();
488 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700489 try {
490 oldFilter.uninstall();
491 } catch (RemoteException re) {
492 /* ignore */
493 }
Jeff Brown0029c662011-03-30 02:25:18 -0700494 }
495
496 if (filter != null) {
497 mInputFilter = filter;
498 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700499 try {
500 filter.install(mInputFilterHost);
501 } catch (RemoteException re) {
502 /* ignore */
503 }
Jeff Brown0029c662011-03-30 02:25:18 -0700504 }
505
Jeff Brown4532e612012-04-05 14:27:12 -0700506 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700507 }
508 }
509
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700510 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700511 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700512 if (event == null) {
513 throw new IllegalArgumentException("event must not be null");
514 }
Jeff Brownac143512012-04-05 18:57:33 -0700515 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
516 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
517 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
518 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700519 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700520
Jeff Brownac143512012-04-05 18:57:33 -0700521 final int pid = Binder.getCallingPid();
522 final int uid = Binder.getCallingUid();
523 final long ident = Binder.clearCallingIdentity();
524 final int result;
525 try {
526 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
527 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
528 } finally {
529 Binder.restoreCallingIdentity(ident);
530 }
531 switch (result) {
532 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
533 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
534 throw new SecurityException(
535 "Injecting to another application requires INJECT_EVENTS permission");
536 case INPUT_EVENT_INJECTION_SUCCEEDED:
537 return true;
538 case INPUT_EVENT_INJECTION_TIMED_OUT:
539 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
540 return false;
541 case INPUT_EVENT_INJECTION_FAILED:
542 default:
543 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
544 return false;
545 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700546 }
Jeff Brown0029c662011-03-30 02:25:18 -0700547
Jeff Brown8d608662010-08-30 03:02:23 -0700548 /**
549 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700550 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700551 * @return The input device or null if not found.
552 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700553 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700554 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700555 synchronized (mInputDevicesLock) {
556 final int count = mInputDevices.length;
557 for (int i = 0; i < count; i++) {
558 final InputDevice inputDevice = mInputDevices[i];
559 if (inputDevice.getId() == deviceId) {
560 return inputDevice;
561 }
562 }
563 }
564 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700565 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700566
Jeff Brown8d608662010-08-30 03:02:23 -0700567 /**
568 * Gets the ids of all input devices in the system.
569 * @return The input device ids.
570 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700571 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700572 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700573 synchronized (mInputDevicesLock) {
574 final int count = mInputDevices.length;
575 int[] ids = new int[count];
576 for (int i = 0; i < count; i++) {
577 ids[i] = mInputDevices[i].getId();
578 }
579 return ids;
580 }
581 }
582
Jeff Browndaa37532012-05-01 15:54:03 -0700583 /**
584 * Gets all input devices in the system.
585 * @return The array of input devices.
586 */
587 public InputDevice[] getInputDevices() {
588 synchronized (mInputDevicesLock) {
589 return mInputDevices;
590 }
591 }
592
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700593 @Override // Binder call
594 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
595 if (listener == null) {
596 throw new IllegalArgumentException("listener must not be null");
597 }
598
599 synchronized (mInputDevicesLock) {
600 int callingPid = Binder.getCallingPid();
601 if (mInputDevicesChangedListeners.get(callingPid) != null) {
602 throw new SecurityException("The calling process has already "
603 + "registered an InputDevicesChangedListener.");
604 }
605
606 InputDevicesChangedListenerRecord record =
607 new InputDevicesChangedListenerRecord(callingPid, listener);
608 try {
609 IBinder binder = listener.asBinder();
610 binder.linkToDeath(record, 0);
611 } catch (RemoteException ex) {
612 // give up
613 throw new RuntimeException(ex);
614 }
615
616 mInputDevicesChangedListeners.put(callingPid, record);
617 }
618 }
619
620 private void onInputDevicesChangedListenerDied(int pid) {
621 synchronized (mInputDevicesLock) {
622 mInputDevicesChangedListeners.remove(pid);
623 }
624 }
625
626 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700627 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
628 // Scan for changes.
629 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700630 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700631 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700632 final int numListeners;
633 final int[] deviceIdAndGeneration;
634 synchronized (mInputDevicesLock) {
635 if (!mInputDevicesChangedPending) {
636 return;
637 }
638 mInputDevicesChangedPending = false;
639
640 numListeners = mInputDevicesChangedListeners.size();
641 for (int i = 0; i < numListeners; i++) {
642 mTempInputDevicesChangedListenersToNotify.add(
643 mInputDevicesChangedListeners.valueAt(i));
644 }
645
646 final int numDevices = mInputDevices.length;
647 deviceIdAndGeneration = new int[numDevices * 2];
648 for (int i = 0; i < numDevices; i++) {
649 final InputDevice inputDevice = mInputDevices[i];
650 deviceIdAndGeneration[i * 2] = inputDevice.getId();
651 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700652
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700653 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700654 if (!containsInputDeviceWithDescriptor(oldInputDevices,
655 inputDevice.getDescriptor())) {
656 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
657 } else {
658 mTempFullKeyboards.add(inputDevice);
659 }
660 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700661 }
662 }
663
Jeff Browncf39bdf2012-05-18 14:41:19 -0700664 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700665 for (int i = 0; i < numListeners; i++) {
666 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
667 deviceIdAndGeneration);
668 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700669 mTempInputDevicesChangedListenersToNotify.clear();
670
671 // Check for missing keyboard layouts.
672 if (mNotificationManager != null) {
673 final int numFullKeyboards = mTempFullKeyboards.size();
674 boolean missingLayoutForExternalKeyboard = false;
675 boolean missingLayoutForExternalKeyboardAdded = false;
676 synchronized (mDataStore) {
677 for (int i = 0; i < numFullKeyboards; i++) {
678 final InputDevice inputDevice = mTempFullKeyboards.get(i);
679 if (mDataStore.getCurrentKeyboardLayout(inputDevice.getDescriptor()) == null) {
680 missingLayoutForExternalKeyboard = true;
681 if (i < numFullKeyboardsAdded) {
682 missingLayoutForExternalKeyboardAdded = true;
683 }
684 }
685 }
686 }
687 if (missingLayoutForExternalKeyboard) {
688 if (missingLayoutForExternalKeyboardAdded) {
689 showMissingKeyboardLayoutNotification();
690 }
691 } else if (mKeyboardLayoutNotificationShown) {
692 hideMissingKeyboardLayoutNotification();
693 }
694 }
695 mTempFullKeyboards.clear();
696 }
697
698 // Must be called on handler.
699 private void showMissingKeyboardLayoutNotification() {
700 if (!mKeyboardLayoutNotificationShown) {
701 if (mKeyboardLayoutIntent == null) {
702 final Intent intent = new Intent("android.settings.INPUT_METHOD_SETTINGS");
703 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
704 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
705 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700706 mKeyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
707 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700708 }
709
710 Resources r = mContext.getResources();
711 Notification notification = new Notification.Builder(mContext)
712 .setContentTitle(r.getString(
713 R.string.select_keyboard_layout_notification_title))
714 .setContentText(r.getString(
715 R.string.select_keyboard_layout_notification_message))
716 .setContentIntent(mKeyboardLayoutIntent)
717 .setSmallIcon(R.drawable.ic_settings_language)
718 .setPriority(Notification.PRIORITY_LOW)
719 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700720 mNotificationManager.notifyAsUser(null,
721 R.string.select_keyboard_layout_notification_title,
722 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700723 mKeyboardLayoutNotificationShown = true;
724 }
725 }
726
727 // Must be called on handler.
728 private void hideMissingKeyboardLayoutNotification() {
729 if (mKeyboardLayoutNotificationShown) {
730 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700731 mNotificationManager.cancelAsUser(null,
732 R.string.select_keyboard_layout_notification_title,
733 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700734 }
735 }
736
737 // Must be called on handler.
738 private void updateKeyboardLayouts() {
739 // Scan all input devices state for keyboard layouts that have been uninstalled.
740 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
741 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
742 @Override
743 public void visitKeyboardLayout(Resources resources,
744 String descriptor, String label, String collection, int keyboardLayoutResId) {
745 availableKeyboardLayouts.add(descriptor);
746 }
747 });
748 synchronized (mDataStore) {
749 try {
750 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
751 } finally {
752 mDataStore.saveIfNeeded();
753 }
754 }
755
756 // Reload keyboard layouts.
757 reloadKeyboardLayouts();
758 }
759
Jeff Browncf39bdf2012-05-18 14:41:19 -0700760 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
761 String descriptor) {
762 final int numDevices = inputDevices.length;
763 for (int i = 0; i < numDevices; i++) {
764 final InputDevice inputDevice = inputDevices[i];
765 if (inputDevice.getDescriptor().equals(descriptor)) {
766 return true;
767 }
768 }
769 return false;
Jeff Brown8d608662010-08-30 03:02:23 -0700770 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700771
772 @Override // Binder call
773 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700774 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
775 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
776 @Override
777 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700778 String descriptor, String label, String collection, int keyboardLayoutResId) {
779 list.add(new KeyboardLayout(descriptor, label, collection));
Jeff Brown6ec6f792012-04-17 16:52:41 -0700780 }
781 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700782 return list.toArray(new KeyboardLayout[list.size()]);
783 }
784
785 @Override // Binder call
786 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
787 if (keyboardLayoutDescriptor == null) {
788 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
789 }
790
Jeff Brown6ec6f792012-04-17 16:52:41 -0700791 final KeyboardLayout[] result = new KeyboardLayout[1];
792 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
793 @Override
794 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700795 String descriptor, String label, String collection, int keyboardLayoutResId) {
796 result[0] = new KeyboardLayout(descriptor, label, collection);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700797 }
798 });
799 if (result[0] == null) {
800 Log.w(TAG, "Could not get keyboard layout with descriptor '"
801 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700802 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700803 return result[0];
804 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700805
Jeff Brown6ec6f792012-04-17 16:52:41 -0700806 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700807 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700808 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
809 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
810 PackageManager.GET_META_DATA)) {
811 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700812 }
813 }
814
Jeff Brown6ec6f792012-04-17 16:52:41 -0700815 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
816 KeyboardLayoutVisitor visitor) {
817 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
818 if (d != null) {
819 final PackageManager pm = mContext.getPackageManager();
820 try {
821 ActivityInfo receiver = pm.getReceiverInfo(
822 new ComponentName(d.packageName, d.receiverName),
823 PackageManager.GET_META_DATA);
824 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
825 } catch (NameNotFoundException ex) {
826 }
827 }
828 }
829
830 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
831 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700832 Bundle metaData = receiver.metaData;
833 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700834 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700835 }
836
837 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
838 if (configResId == 0) {
839 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
840 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700841 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700842 }
843
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700844 CharSequence receiverLabel = receiver.loadLabel(pm);
845 String collection = receiverLabel != null ? receiverLabel.toString() : "";
846
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700847 try {
848 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
849 XmlResourceParser parser = resources.getXml(configResId);
850 try {
851 XmlUtils.beginDocument(parser, "keyboard-layouts");
852
853 for (;;) {
854 XmlUtils.nextElement(parser);
855 String element = parser.getName();
856 if (element == null) {
857 break;
858 }
859 if (element.equals("keyboard-layout")) {
860 TypedArray a = resources.obtainAttributes(
861 parser, com.android.internal.R.styleable.KeyboardLayout);
862 try {
863 String name = a.getString(
864 com.android.internal.R.styleable.KeyboardLayout_name);
865 String label = a.getString(
866 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -0700867 int keyboardLayoutResId = a.getResourceId(
868 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
869 0);
870 if (name == null || label == null || keyboardLayoutResId == 0) {
871 Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700872 + "attributes in keyboard layout "
873 + "resource from receiver "
874 + receiver.packageName + "/" + receiver.name);
875 } else {
876 String descriptor = KeyboardLayoutDescriptor.format(
877 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700878 if (keyboardName == null || name.equals(keyboardName)) {
879 visitor.visitKeyboardLayout(resources, descriptor,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700880 label, collection, keyboardLayoutResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700881 }
882 }
883 } finally {
884 a.recycle();
885 }
886 } else {
887 Log.w(TAG, "Skipping unrecognized element '" + element
888 + "' in keyboard layout resource from receiver "
889 + receiver.packageName + "/" + receiver.name);
890 }
891 }
892 } finally {
893 parser.close();
894 }
895 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700896 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700897 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700898 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700899 }
900
RoboErikfb290df2013-12-16 11:27:55 -0800901 /**
902 * Builds a layout descriptor for the vendor/product. This returns the
903 * descriptor for ids that aren't useful (such as the default 0, 0).
904 */
905 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
906 if (identifier == null || identifier.getDescriptor() == null) {
907 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700908 }
909
RoboErikfb290df2013-12-16 11:27:55 -0800910 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
911 return identifier.getDescriptor();
912 }
913 StringBuilder bob = new StringBuilder();
914 bob.append("vendor:").append(identifier.getVendorId());
915 bob.append(",product:").append(identifier.getProductId());
916 return bob.toString();
917 }
918
919 @Override // Binder call
920 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
921
922 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -0700923 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -0800924 String layout = null;
925 // try loading it using the layout descriptor if we have it
926 layout = mDataStore.getCurrentKeyboardLayout(key);
927 if (layout == null && !key.equals(identifier.getDescriptor())) {
928 // if it doesn't exist fall back to the device descriptor
929 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
930 }
931 if (DEBUG) {
932 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
933 + layout);
934 }
935 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -0700936 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700937 }
938
939 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800940 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700941 String keyboardLayoutDescriptor) {
942 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700943 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700944 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
945 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700946 if (keyboardLayoutDescriptor == null) {
947 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
948 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700949
RoboErikfb290df2013-12-16 11:27:55 -0800950 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -0700951 synchronized (mDataStore) {
952 try {
RoboErikfb290df2013-12-16 11:27:55 -0800953 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
954 if (DEBUG) {
955 Slog.d(TAG, "Saved keyboard layout using " + key);
956 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700957 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
958 }
Jeff Browna3bc5652012-04-17 11:42:25 -0700959 } finally {
960 mDataStore.saveIfNeeded();
961 }
962 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700963 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700964
Jeff Browncf39bdf2012-05-18 14:41:19 -0700965 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800966 public String[] getKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
967 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700968 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -0800969 String[] layouts = mDataStore.getKeyboardLayouts(key);
970 if ((layouts == null || layouts.length == 0)
971 && !key.equals(identifier.getDescriptor())) {
972 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
973 }
974 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700975 }
976 }
977
978 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -0800979 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700980 String keyboardLayoutDescriptor) {
981 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
982 "addKeyboardLayoutForInputDevice()")) {
983 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
984 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700985 if (keyboardLayoutDescriptor == null) {
986 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
987 }
988
RoboErikfb290df2013-12-16 11:27:55 -0800989 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700990 synchronized (mDataStore) {
991 try {
RoboErikfb290df2013-12-16 11:27:55 -0800992 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
993 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
994 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
995 }
996 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700997 && !Objects.equal(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -0800998 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700999 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1000 }
1001 } finally {
1002 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001003 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001004 }
1005 }
1006
1007 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001008 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001009 String keyboardLayoutDescriptor) {
1010 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1011 "removeKeyboardLayoutForInputDevice()")) {
1012 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1013 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001014 if (keyboardLayoutDescriptor == null) {
1015 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1016 }
1017
RoboErikfb290df2013-12-16 11:27:55 -08001018 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001019 synchronized (mDataStore) {
1020 try {
RoboErikfb290df2013-12-16 11:27:55 -08001021 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1022 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1023 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1024 }
1025 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1026 if (!key.equals(identifier.getDescriptor())) {
1027 // We need to remove from both places to ensure it is gone
1028 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1029 keyboardLayoutDescriptor);
1030 }
1031 if (removed && !Objects.equal(oldLayout,
1032 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001033 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1034 }
1035 } finally {
1036 mDataStore.saveIfNeeded();
1037 }
1038 }
1039 }
1040
1041 public void switchKeyboardLayout(int deviceId, int direction) {
1042 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
1043 }
1044
1045 // Must be called on handler.
1046 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1047 final InputDevice device = getInputDevice(deviceId);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001048 if (device != null) {
1049 final boolean changed;
1050 final String keyboardLayoutDescriptor;
RoboErikfb290df2013-12-16 11:27:55 -08001051
1052 String key = getLayoutDescriptor(device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001053 synchronized (mDataStore) {
1054 try {
RoboErikfb290df2013-12-16 11:27:55 -08001055 changed = mDataStore.switchKeyboardLayout(key, direction);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001056 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
RoboErikfb290df2013-12-16 11:27:55 -08001057 key);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001058 } finally {
1059 mDataStore.saveIfNeeded();
1060 }
1061 }
1062
1063 if (changed) {
1064 if (mSwitchedKeyboardLayoutToast != null) {
1065 mSwitchedKeyboardLayoutToast.cancel();
1066 mSwitchedKeyboardLayoutToast = null;
1067 }
1068 if (keyboardLayoutDescriptor != null) {
1069 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1070 if (keyboardLayout != null) {
1071 mSwitchedKeyboardLayoutToast = Toast.makeText(
1072 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1073 mSwitchedKeyboardLayoutToast.show();
1074 }
1075 }
1076
1077 reloadKeyboardLayouts();
1078 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001079 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001080 }
1081
Jeff Brown9302c872011-07-13 22:51:29 -07001082 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001083 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001084 }
RoboErikfb290df2013-12-16 11:27:55 -08001085
Jeff Brown9302c872011-07-13 22:51:29 -07001086 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001087 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001088 }
RoboErikfb290df2013-12-16 11:27:55 -08001089
Jeff Brown349703e2010-06-22 01:27:15 -07001090 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001091 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001092 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001093
1094 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001095 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001096 }
1097
Jeff Browne6504122010-09-27 14:52:15 -07001098 /**
1099 * Atomically transfers touch focus from one window to another as identified by
1100 * their input channels. It is possible for multiple windows to have
1101 * touch focus if they support split touch dispatch
1102 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1103 * method only transfers touch focus of the specified window without affecting
1104 * other windows that may also have touch focus at the same time.
1105 * @param fromChannel The channel of a window that currently has touch focus.
1106 * @param toChannel The channel of the window that should receive touch focus in
1107 * place of the first.
1108 * @return True if the transfer was successful. False if the window with the
1109 * specified channel did not actually have touch focus at the time of the request.
1110 */
1111 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1112 if (fromChannel == null) {
1113 throw new IllegalArgumentException("fromChannel must not be null.");
1114 }
1115 if (toChannel == null) {
1116 throw new IllegalArgumentException("toChannel must not be null.");
1117 }
Jeff Brown4532e612012-04-05 14:27:12 -07001118 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001119 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001120
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001121 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001122 public void tryPointerSpeed(int speed) {
1123 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1124 "tryPointerSpeed()")) {
1125 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1126 }
1127
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001128 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1129 throw new IllegalArgumentException("speed out of range");
1130 }
1131
Jeff Brownac143512012-04-05 18:57:33 -07001132 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001133 }
1134
1135 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001136 int speed = getPointerSpeedSetting();
1137 setPointerSpeedUnchecked(speed);
1138 }
1139
1140 private void setPointerSpeedUnchecked(int speed) {
1141 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1142 InputManager.MAX_POINTER_SPEED);
1143 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001144 }
1145
1146 private void registerPointerSpeedSettingObserver() {
1147 mContext.getContentResolver().registerContentObserver(
1148 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001149 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001150 @Override
1151 public void onChange(boolean selfChange) {
1152 updatePointerSpeedFromSettings();
1153 }
Jeff Brownd4935962012-09-25 13:27:20 -07001154 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001155 }
1156
Jeff Brownac143512012-04-05 18:57:33 -07001157 private int getPointerSpeedSetting() {
1158 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001159 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001160 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1161 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001162 } catch (SettingNotFoundException snfe) {
1163 }
1164 return speed;
1165 }
1166
Jeff Browndaf4a122011-08-26 17:14:14 -07001167 public void updateShowTouchesFromSettings() {
1168 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001169 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001170 }
1171
1172 private void registerShowTouchesSettingObserver() {
1173 mContext.getContentResolver().registerContentObserver(
1174 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001175 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001176 @Override
1177 public void onChange(boolean selfChange) {
1178 updateShowTouchesFromSettings();
1179 }
Jeff Brownd4935962012-09-25 13:27:20 -07001180 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001181 }
1182
1183 private int getShowTouchesSetting(int defaultValue) {
1184 int result = defaultValue;
1185 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001186 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1187 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001188 } catch (SettingNotFoundException snfe) {
1189 }
1190 return result;
1191 }
1192
Jeff Browna47425a2012-04-13 04:09:27 -07001193 // Binder call
1194 @Override
1195 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1196 if (repeat >= pattern.length) {
1197 throw new ArrayIndexOutOfBoundsException();
1198 }
1199
1200 VibratorToken v;
1201 synchronized (mVibratorLock) {
1202 v = mVibratorTokens.get(token);
1203 if (v == null) {
1204 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1205 try {
1206 token.linkToDeath(v, 0);
1207 } catch (RemoteException ex) {
1208 // give up
1209 throw new RuntimeException(ex);
1210 }
1211 mVibratorTokens.put(token, v);
1212 }
1213 }
1214
1215 synchronized (v) {
1216 v.mVibrating = true;
1217 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1218 }
1219 }
1220
1221 // Binder call
1222 @Override
1223 public void cancelVibrate(int deviceId, IBinder token) {
1224 VibratorToken v;
1225 synchronized (mVibratorLock) {
1226 v = mVibratorTokens.get(token);
1227 if (v == null || v.mDeviceId != deviceId) {
1228 return; // nothing to cancel
1229 }
1230 }
1231
1232 cancelVibrateIfNeeded(v);
1233 }
1234
1235 void onVibratorTokenDied(VibratorToken v) {
1236 synchronized (mVibratorLock) {
1237 mVibratorTokens.remove(v.mToken);
1238 }
1239
1240 cancelVibrateIfNeeded(v);
1241 }
1242
1243 private void cancelVibrateIfNeeded(VibratorToken v) {
1244 synchronized (v) {
1245 if (v.mVibrating) {
1246 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1247 v.mVibrating = false;
1248 }
1249 }
1250 }
1251
Jeff Brown4532e612012-04-05 14:27:12 -07001252 @Override
1253 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001254 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001255 != PackageManager.PERMISSION_GRANTED) {
1256 pw.println("Permission Denial: can't dump InputManager from from pid="
1257 + Binder.getCallingPid()
1258 + ", uid=" + Binder.getCallingUid());
1259 return;
1260 }
1261
1262 pw.println("INPUT MANAGER (dumpsys input)\n");
1263 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001264 if (dumpStr != null) {
1265 pw.println(dumpStr);
1266 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001267 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001268
Jeff Brownac143512012-04-05 18:57:33 -07001269 private boolean checkCallingPermission(String permission, String func) {
1270 // Quick check: if the calling permission is me, it's all okay.
1271 if (Binder.getCallingPid() == Process.myPid()) {
1272 return true;
1273 }
1274
1275 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1276 return true;
1277 }
1278 String msg = "Permission Denial: " + func + " from pid="
1279 + Binder.getCallingPid()
1280 + ", uid=" + Binder.getCallingUid()
1281 + " requires " + permission;
1282 Slog.w(TAG, msg);
1283 return false;
1284 }
1285
Jeff Brown4532e612012-04-05 14:27:12 -07001286 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001287 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001288 public void monitor() {
1289 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001290 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001291 }
1292
Jeff Brown4532e612012-04-05 14:27:12 -07001293 // Native callback.
1294 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001295 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001296 }
1297
1298 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001299 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1300 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001301 if (!mInputDevicesChangedPending) {
1302 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001303 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1304 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001305 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001306
1307 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001308 }
1309 }
1310
1311 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001312 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1313 if (DEBUG) {
1314 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1315 + ", mask=" + Integer.toHexString(switchMask));
1316 }
1317
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001318 if ((switchMask & SW_LID_BIT) != 0) {
1319 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001320 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001321 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001322
1323 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1324 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1325 switchMask);
1326 }
Jeff Brown4532e612012-04-05 14:27:12 -07001327 }
1328
1329 // Native callback.
1330 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001331 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001332 }
1333
1334 // Native callback.
1335 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001336 InputWindowHandle inputWindowHandle, String reason) {
1337 return mWindowManagerCallbacks.notifyANR(
1338 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001339 }
1340
1341 // Native callback.
1342 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1343 synchronized (mInputFilterLock) {
1344 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001345 try {
1346 mInputFilter.filterInputEvent(event, policyFlags);
1347 } catch (RemoteException e) {
1348 /* ignore */
1349 }
Jeff Brown4532e612012-04-05 14:27:12 -07001350 return false;
1351 }
1352 }
1353 event.recycle();
1354 return true;
1355 }
1356
1357 // Native callback.
1358 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001359 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(
Jeff Brown4532e612012-04-05 14:27:12 -07001360 event, policyFlags, isScreenOn);
1361 }
1362
1363 // Native callback.
1364 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001365 return mWindowManagerCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001366 }
1367
1368 // Native callback.
1369 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1370 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001371 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001372 }
1373
1374 // Native callback.
1375 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1376 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001377 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001378 }
1379
1380 // Native callback.
1381 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1382 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1383 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1384 }
1385
1386 // Native callback.
1387 private int getVirtualKeyQuietTimeMillis() {
1388 return mContext.getResources().getInteger(
1389 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1390 }
1391
1392 // Native callback.
1393 private String[] getExcludedDeviceNames() {
1394 ArrayList<String> names = new ArrayList<String>();
1395
1396 // Read partner-provided list of excluded input devices
1397 XmlPullParser parser = null;
1398 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1399 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1400 FileReader confreader = null;
1401 try {
1402 confreader = new FileReader(confFile);
1403 parser = Xml.newPullParser();
1404 parser.setInput(confreader);
1405 XmlUtils.beginDocument(parser, "devices");
1406
1407 while (true) {
1408 XmlUtils.nextElement(parser);
1409 if (!"device".equals(parser.getName())) {
1410 break;
1411 }
1412 String name = parser.getAttributeValue(null, "name");
1413 if (name != null) {
1414 names.add(name);
1415 }
1416 }
1417 } catch (FileNotFoundException e) {
1418 // It's ok if the file does not exist.
1419 } catch (Exception e) {
1420 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1421 } finally {
1422 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1423 }
1424
1425 return names.toArray(new String[names.size()]);
1426 }
1427
1428 // Native callback.
1429 private int getKeyRepeatTimeout() {
1430 return ViewConfiguration.getKeyRepeatTimeout();
1431 }
1432
1433 // Native callback.
1434 private int getKeyRepeatDelay() {
1435 return ViewConfiguration.getKeyRepeatDelay();
1436 }
1437
1438 // Native callback.
1439 private int getHoverTapTimeout() {
1440 return ViewConfiguration.getHoverTapTimeout();
1441 }
1442
1443 // Native callback.
1444 private int getHoverTapSlop() {
1445 return ViewConfiguration.getHoverTapSlop();
1446 }
1447
1448 // Native callback.
1449 private int getDoubleTapTimeout() {
1450 return ViewConfiguration.getDoubleTapTimeout();
1451 }
1452
1453 // Native callback.
1454 private int getLongPressTimeout() {
1455 return ViewConfiguration.getLongPressTimeout();
1456 }
1457
1458 // Native callback.
1459 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001460 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001461 }
1462
1463 // Native callback.
1464 private PointerIcon getPointerIcon() {
1465 return PointerIcon.getDefaultIcon(mContext);
1466 }
1467
Jeff Brown6ec6f792012-04-17 16:52:41 -07001468 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001469 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001470 if (!mSystemReady) {
1471 return null;
1472 }
1473
RoboErikfb290df2013-12-16 11:27:55 -08001474 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001475 if (keyboardLayoutDescriptor == null) {
1476 return null;
1477 }
1478
1479 final String[] result = new String[2];
1480 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1481 @Override
1482 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001483 String descriptor, String label, String collection, int keyboardLayoutResId) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001484 try {
1485 result[0] = descriptor;
1486 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001487 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001488 } catch (IOException ex) {
1489 } catch (NotFoundException ex) {
1490 }
1491 }
1492 });
1493 if (result[0] == null) {
1494 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1495 + keyboardLayoutDescriptor + "'.");
1496 return null;
1497 }
1498 return result;
1499 }
1500
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001501 // Native callback.
1502 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001503 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1504 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1505 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001506 }
1507 return null;
1508 }
1509
Jeff Brown4532e612012-04-05 14:27:12 -07001510 /**
1511 * Callback interface implemented by the Window Manager.
1512 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001513 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001514 public void notifyConfigurationChanged();
1515
1516 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1517
1518 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1519
1520 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001521 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001522
1523 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1524
1525 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1526
1527 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1528 KeyEvent event, int policyFlags);
1529
1530 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1531 KeyEvent event, int policyFlags);
1532
1533 public int getPointerLayer();
1534 }
1535
1536 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001537 * Callback interface implemented by WiredAccessoryObserver.
1538 */
1539 public interface WiredAccessoryCallbacks {
1540 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
1541 }
1542
1543 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001544 * Private handler for the input manager.
1545 */
1546 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07001547 public InputManagerHandler(Looper looper) {
1548 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07001549 }
1550
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001551 @Override
1552 public void handleMessage(Message msg) {
1553 switch (msg.what) {
1554 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07001555 deliverInputDevicesChanged((InputDevice[])msg.obj);
1556 break;
1557 case MSG_SWITCH_KEYBOARD_LAYOUT:
1558 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
1559 break;
1560 case MSG_RELOAD_KEYBOARD_LAYOUTS:
1561 reloadKeyboardLayouts();
1562 break;
1563 case MSG_UPDATE_KEYBOARD_LAYOUTS:
1564 updateKeyboardLayouts();
1565 break;
1566 case MSG_RELOAD_DEVICE_ALIASES:
1567 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001568 break;
1569 }
1570 }
1571 }
1572
1573 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001574 * Hosting interface for input filters to call back into the input manager.
1575 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001576 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07001577 private boolean mDisconnected;
1578
1579 public void disconnectLocked() {
1580 mDisconnected = true;
1581 }
1582
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001583 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07001584 public void sendInputEvent(InputEvent event, int policyFlags) {
1585 if (event == null) {
1586 throw new IllegalArgumentException("event must not be null");
1587 }
1588
1589 synchronized (mInputFilterLock) {
1590 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001591 nativeInjectInputEvent(mPtr, event, 0, 0,
1592 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001593 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1594 }
1595 }
1596 }
1597 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001598
1599 private static final class KeyboardLayoutDescriptor {
1600 public String packageName;
1601 public String receiverName;
1602 public String keyboardLayoutName;
1603
1604 public static String format(String packageName,
1605 String receiverName, String keyboardName) {
1606 return packageName + "/" + receiverName + "/" + keyboardName;
1607 }
1608
1609 public static KeyboardLayoutDescriptor parse(String descriptor) {
1610 int pos = descriptor.indexOf('/');
1611 if (pos < 0 || pos + 1 == descriptor.length()) {
1612 return null;
1613 }
1614 int pos2 = descriptor.indexOf('/', pos + 1);
1615 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1616 return null;
1617 }
1618
1619 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1620 result.packageName = descriptor.substring(0, pos);
1621 result.receiverName = descriptor.substring(pos + 1, pos2);
1622 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1623 return result;
1624 }
1625 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001626
Jeff Brown6ec6f792012-04-17 16:52:41 -07001627 private interface KeyboardLayoutVisitor {
1628 void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001629 String descriptor, String label, String collection, int keyboardLayoutResId);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001630 }
1631
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001632 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1633 private final int mPid;
1634 private final IInputDevicesChangedListener mListener;
1635
1636 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1637 mPid = pid;
1638 mListener = listener;
1639 }
1640
1641 @Override
1642 public void binderDied() {
1643 if (DEBUG) {
1644 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1645 }
1646 onInputDevicesChangedListenerDied(mPid);
1647 }
1648
1649 public void notifyInputDevicesChanged(int[] info) {
1650 try {
1651 mListener.onInputDevicesChanged(info);
1652 } catch (RemoteException ex) {
1653 Slog.w(TAG, "Failed to notify process "
1654 + mPid + " that input devices changed, assuming it died.", ex);
1655 binderDied();
1656 }
1657 }
1658 }
Jeff Browna47425a2012-04-13 04:09:27 -07001659
1660 private final class VibratorToken implements DeathRecipient {
1661 public final int mDeviceId;
1662 public final IBinder mToken;
1663 public final int mTokenValue;
1664
1665 public boolean mVibrating;
1666
1667 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1668 mDeviceId = deviceId;
1669 mToken = token;
1670 mTokenValue = tokenValue;
1671 }
1672
1673 @Override
1674 public void binderDied() {
1675 if (DEBUG) {
1676 Slog.d(TAG, "Vibrator token died.");
1677 }
1678 onVibratorTokenDied(this);
1679 }
1680 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08001681
1682 private final class LocalService extends InputManagerInternal {
1683 @Override
1684 public void setDisplayViewports(
1685 DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
1686 setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
1687 }
1688 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001689}