blob: 5e4907e6820d89196577713b672ac77d25243500 [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.
110 private final int mPtr;
111
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
Jeff Brown4532e612012-04-05 14:27:12 -0700149 private static native int nativeInit(InputManagerService service,
150 Context context, MessageQueue messageQueue);
151 private static native void nativeStart(int ptr);
Jeff Brownd728bf52012-09-08 18:05:28 -0700152 private static native void nativeSetDisplayViewport(int ptr, boolean external,
153 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
Jeff Brown4532e612012-04-05 14:27:12 -0700158 private static native int nativeGetScanCodeState(int ptr,
159 int deviceId, int sourceMask, int scanCode);
160 private static native int nativeGetKeyCodeState(int ptr,
161 int deviceId, int sourceMask, int keyCode);
162 private static native int nativeGetSwitchState(int ptr,
163 int deviceId, int sourceMask, int sw);
164 private static native boolean nativeHasKeys(int ptr,
165 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
166 private static native void nativeRegisterInputChannel(int ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800167 InputWindowHandle inputWindowHandle, boolean monitor);
Jeff Brown4532e612012-04-05 14:27:12 -0700168 private static native void nativeUnregisterInputChannel(int ptr, InputChannel inputChannel);
169 private static native void nativeSetInputFilterEnabled(int ptr, boolean enable);
170 private static native int nativeInjectInputEvent(int ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700171 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
172 int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -0700173 private static native void nativeSetInputWindows(int ptr, InputWindowHandle[] windowHandles);
174 private static native void nativeSetInputDispatchMode(int ptr, boolean enabled, boolean frozen);
175 private static native void nativeSetSystemUiVisibility(int ptr, int visibility);
176 private static native void nativeSetFocusedApplication(int ptr,
177 InputApplicationHandle application);
Jeff Brown4532e612012-04-05 14:27:12 -0700178 private static native boolean nativeTransferTouchFocus(int ptr,
179 InputChannel fromChannel, InputChannel toChannel);
180 private static native void nativeSetPointerSpeed(int ptr, int speed);
181 private static native void nativeSetShowTouches(int ptr, boolean enabled);
Jeff Browna47425a2012-04-13 04:09:27 -0700182 private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
183 int repeat, int token);
184 private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700185 private static native void nativeReloadKeyboardLayouts(int ptr);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700186 private static native void nativeReloadDeviceAliases(int ptr);
Jeff Brown4532e612012-04-05 14:27:12 -0700187 private static native String nativeDump(int ptr);
188 private static native void nativeMonitor(int 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
286 public void systemReady() {
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);
297 filter.addDataScheme("package");
298 mContext.registerReceiver(new BroadcastReceiver() {
299 @Override
300 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700301 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700302 }
303 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700304
305 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
306 mContext.registerReceiver(new BroadcastReceiver() {
307 @Override
308 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700309 reloadDeviceAliases();
310 }
311 }, filter, null, mHandler);
312
Jeff Browncf39bdf2012-05-18 14:41:19 -0700313 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
314 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700315 }
316
317 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700318 if (DEBUG) {
319 Slog.d(TAG, "Reloading keyboard layouts.");
320 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700321 nativeReloadKeyboardLayouts(mPtr);
322 }
323
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700324 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700325 if (DEBUG) {
326 Slog.d(TAG, "Reloading device names.");
327 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700328 nativeReloadDeviceAliases(mPtr);
329 }
330
Jeff Brownd728bf52012-09-08 18:05:28 -0700331 @Override
332 public void setDisplayViewports(DisplayViewport defaultViewport,
333 DisplayViewport externalTouchViewport) {
334 if (defaultViewport.valid) {
335 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700336 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700337
338 if (externalTouchViewport.valid) {
339 setDisplayViewport(true, externalTouchViewport);
340 } else if (defaultViewport.valid) {
341 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700342 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700343 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700344
Jeff Brownd728bf52012-09-08 18:05:28 -0700345 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
346 nativeSetDisplayViewport(mPtr, external,
347 viewport.displayId, viewport.orientation,
348 viewport.logicalFrame.left, viewport.logicalFrame.top,
349 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
350 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700351 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
352 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700353 }
Jeff Brownac143512012-04-05 18:57:33 -0700354
Jeff Brown6d0fec22010-07-23 21:28:06 -0700355 /**
356 * Gets the current state of a key or button by key code.
357 * @param deviceId The input device id, or -1 to consult all devices.
358 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
359 * consider all input sources. An input device is consulted if at least one of its
360 * non-class input source bits matches the specified source mask.
361 * @param keyCode The key code to check.
362 * @return The key state.
363 */
364 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700365 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700366 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700367
Jeff Brown6d0fec22010-07-23 21:28:06 -0700368 /**
369 * Gets the current state of a key or button by scan code.
370 * @param deviceId The input device id, or -1 to consult all devices.
371 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
372 * consider all input sources. An input device is consulted if at least one of its
373 * non-class input source bits matches the specified source mask.
374 * @param scanCode The scan code to check.
375 * @return The key state.
376 */
377 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700378 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700379 }
380
Jeff Brown6d0fec22010-07-23 21:28:06 -0700381 /**
382 * Gets the current state of a switch by switch code.
383 * @param deviceId The input device id, or -1 to consult all devices.
384 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
385 * consider all input sources. An input device is consulted if at least one of its
386 * non-class input source bits matches the specified source mask.
387 * @param switchCode The switch code to check.
388 * @return The switch state.
389 */
390 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700391 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700392 }
393
Jeff Brown6d0fec22010-07-23 21:28:06 -0700394 /**
395 * Determines whether the specified key codes are supported by a particular device.
396 * @param deviceId The input device id, or -1 to consult all devices.
397 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
398 * consider all input sources. An input device is consulted if at least one of its
399 * non-class input source bits matches the specified source mask.
400 * @param keyCodes The array of key codes to check.
401 * @param keyExists An array at least as large as keyCodes whose entries will be set
402 * to true or false based on the presence or absence of support for the corresponding
403 * key codes.
404 * @return True if the lookup was successful, false otherwise.
405 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700406 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700407 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700408 if (keyCodes == null) {
409 throw new IllegalArgumentException("keyCodes must not be null.");
410 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700411 if (keyExists == null || keyExists.length < keyCodes.length) {
412 throw new IllegalArgumentException("keyExists must not be null and must be at "
413 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700414 }
415
Jeff Brown4532e612012-04-05 14:27:12 -0700416 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700417 }
418
Jeff Browna41ca772010-08-11 14:46:32 -0700419 /**
420 * Creates an input channel that will receive all input from the input dispatcher.
421 * @param inputChannelName The input channel name.
422 * @return The input channel.
423 */
424 public InputChannel monitorInput(String inputChannelName) {
425 if (inputChannelName == null) {
426 throw new IllegalArgumentException("inputChannelName must not be null.");
427 }
428
429 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700430 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700431 inputChannels[0].dispose(); // don't need to retain the Java object reference
432 return inputChannels[1];
433 }
434
435 /**
436 * Registers an input channel so that it can be used as an input event target.
437 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800438 * @param inputWindowHandle The handle of the input window associated with the
439 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700440 */
Jeff Brown928e0542011-01-10 11:17:36 -0800441 public void registerInputChannel(InputChannel inputChannel,
442 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700443 if (inputChannel == null) {
444 throw new IllegalArgumentException("inputChannel must not be null.");
445 }
446
Jeff Brown4532e612012-04-05 14:27:12 -0700447 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700448 }
449
Jeff Browna41ca772010-08-11 14:46:32 -0700450 /**
451 * Unregisters an input channel.
452 * @param inputChannel The input channel to unregister.
453 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700454 public void unregisterInputChannel(InputChannel inputChannel) {
455 if (inputChannel == null) {
456 throw new IllegalArgumentException("inputChannel must not be null.");
457 }
458
Jeff Brown4532e612012-04-05 14:27:12 -0700459 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700460 }
Jeff Brown0029c662011-03-30 02:25:18 -0700461
462 /**
463 * Sets an input filter that will receive all input events before they are dispatched.
464 * The input filter may then reinterpret input events or inject new ones.
465 *
466 * To ensure consistency, the input dispatcher automatically drops all events
467 * in progress whenever an input filter is installed or uninstalled. After an input
468 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
469 * Any events it attempts to send after it has been uninstalled will be dropped.
470 *
471 * @param filter The input filter, or null to remove the current filter.
472 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700473 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700474 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700475 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700476 if (oldFilter == filter) {
477 return; // nothing to do
478 }
479
480 if (oldFilter != null) {
481 mInputFilter = null;
482 mInputFilterHost.disconnectLocked();
483 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700484 try {
485 oldFilter.uninstall();
486 } catch (RemoteException re) {
487 /* ignore */
488 }
Jeff Brown0029c662011-03-30 02:25:18 -0700489 }
490
491 if (filter != null) {
492 mInputFilter = filter;
493 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700494 try {
495 filter.install(mInputFilterHost);
496 } catch (RemoteException re) {
497 /* ignore */
498 }
Jeff Brown0029c662011-03-30 02:25:18 -0700499 }
500
Jeff Brown4532e612012-04-05 14:27:12 -0700501 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700502 }
503 }
504
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700505 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700506 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700507 if (event == null) {
508 throw new IllegalArgumentException("event must not be null");
509 }
Jeff Brownac143512012-04-05 18:57:33 -0700510 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
511 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
512 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
513 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700514 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700515
Jeff Brownac143512012-04-05 18:57:33 -0700516 final int pid = Binder.getCallingPid();
517 final int uid = Binder.getCallingUid();
518 final long ident = Binder.clearCallingIdentity();
519 final int result;
520 try {
521 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
522 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
523 } finally {
524 Binder.restoreCallingIdentity(ident);
525 }
526 switch (result) {
527 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
528 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
529 throw new SecurityException(
530 "Injecting to another application requires INJECT_EVENTS permission");
531 case INPUT_EVENT_INJECTION_SUCCEEDED:
532 return true;
533 case INPUT_EVENT_INJECTION_TIMED_OUT:
534 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
535 return false;
536 case INPUT_EVENT_INJECTION_FAILED:
537 default:
538 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
539 return false;
540 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700541 }
Jeff Brown0029c662011-03-30 02:25:18 -0700542
Jeff Brown8d608662010-08-30 03:02:23 -0700543 /**
544 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700545 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700546 * @return The input device or null if not found.
547 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700548 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700549 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700550 synchronized (mInputDevicesLock) {
551 final int count = mInputDevices.length;
552 for (int i = 0; i < count; i++) {
553 final InputDevice inputDevice = mInputDevices[i];
554 if (inputDevice.getId() == deviceId) {
555 return inputDevice;
556 }
557 }
558 }
559 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700560 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700561
Jeff Brown8d608662010-08-30 03:02:23 -0700562 /**
563 * Gets the ids of all input devices in the system.
564 * @return The input device ids.
565 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700566 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700567 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700568 synchronized (mInputDevicesLock) {
569 final int count = mInputDevices.length;
570 int[] ids = new int[count];
571 for (int i = 0; i < count; i++) {
572 ids[i] = mInputDevices[i].getId();
573 }
574 return ids;
575 }
576 }
577
Jeff Browndaa37532012-05-01 15:54:03 -0700578 /**
579 * Gets all input devices in the system.
580 * @return The array of input devices.
581 */
582 public InputDevice[] getInputDevices() {
583 synchronized (mInputDevicesLock) {
584 return mInputDevices;
585 }
586 }
587
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700588 @Override // Binder call
589 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
590 if (listener == null) {
591 throw new IllegalArgumentException("listener must not be null");
592 }
593
594 synchronized (mInputDevicesLock) {
595 int callingPid = Binder.getCallingPid();
596 if (mInputDevicesChangedListeners.get(callingPid) != null) {
597 throw new SecurityException("The calling process has already "
598 + "registered an InputDevicesChangedListener.");
599 }
600
601 InputDevicesChangedListenerRecord record =
602 new InputDevicesChangedListenerRecord(callingPid, listener);
603 try {
604 IBinder binder = listener.asBinder();
605 binder.linkToDeath(record, 0);
606 } catch (RemoteException ex) {
607 // give up
608 throw new RuntimeException(ex);
609 }
610
611 mInputDevicesChangedListeners.put(callingPid, record);
612 }
613 }
614
615 private void onInputDevicesChangedListenerDied(int pid) {
616 synchronized (mInputDevicesLock) {
617 mInputDevicesChangedListeners.remove(pid);
618 }
619 }
620
621 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700622 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
623 // Scan for changes.
624 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700625 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700626 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700627 final int numListeners;
628 final int[] deviceIdAndGeneration;
629 synchronized (mInputDevicesLock) {
630 if (!mInputDevicesChangedPending) {
631 return;
632 }
633 mInputDevicesChangedPending = false;
634
635 numListeners = mInputDevicesChangedListeners.size();
636 for (int i = 0; i < numListeners; i++) {
637 mTempInputDevicesChangedListenersToNotify.add(
638 mInputDevicesChangedListeners.valueAt(i));
639 }
640
641 final int numDevices = mInputDevices.length;
642 deviceIdAndGeneration = new int[numDevices * 2];
643 for (int i = 0; i < numDevices; i++) {
644 final InputDevice inputDevice = mInputDevices[i];
645 deviceIdAndGeneration[i * 2] = inputDevice.getId();
646 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700647
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700648 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700649 if (!containsInputDeviceWithDescriptor(oldInputDevices,
650 inputDevice.getDescriptor())) {
651 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
652 } else {
653 mTempFullKeyboards.add(inputDevice);
654 }
655 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700656 }
657 }
658
Jeff Browncf39bdf2012-05-18 14:41:19 -0700659 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700660 for (int i = 0; i < numListeners; i++) {
661 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
662 deviceIdAndGeneration);
663 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700664 mTempInputDevicesChangedListenersToNotify.clear();
665
666 // Check for missing keyboard layouts.
667 if (mNotificationManager != null) {
668 final int numFullKeyboards = mTempFullKeyboards.size();
669 boolean missingLayoutForExternalKeyboard = false;
670 boolean missingLayoutForExternalKeyboardAdded = false;
671 synchronized (mDataStore) {
672 for (int i = 0; i < numFullKeyboards; i++) {
673 final InputDevice inputDevice = mTempFullKeyboards.get(i);
674 if (mDataStore.getCurrentKeyboardLayout(inputDevice.getDescriptor()) == null) {
675 missingLayoutForExternalKeyboard = true;
676 if (i < numFullKeyboardsAdded) {
677 missingLayoutForExternalKeyboardAdded = true;
678 }
679 }
680 }
681 }
682 if (missingLayoutForExternalKeyboard) {
683 if (missingLayoutForExternalKeyboardAdded) {
684 showMissingKeyboardLayoutNotification();
685 }
686 } else if (mKeyboardLayoutNotificationShown) {
687 hideMissingKeyboardLayoutNotification();
688 }
689 }
690 mTempFullKeyboards.clear();
691 }
692
693 // Must be called on handler.
694 private void showMissingKeyboardLayoutNotification() {
695 if (!mKeyboardLayoutNotificationShown) {
696 if (mKeyboardLayoutIntent == null) {
697 final Intent intent = new Intent("android.settings.INPUT_METHOD_SETTINGS");
698 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
699 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
700 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700701 mKeyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
702 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700703 }
704
705 Resources r = mContext.getResources();
706 Notification notification = new Notification.Builder(mContext)
707 .setContentTitle(r.getString(
708 R.string.select_keyboard_layout_notification_title))
709 .setContentText(r.getString(
710 R.string.select_keyboard_layout_notification_message))
711 .setContentIntent(mKeyboardLayoutIntent)
712 .setSmallIcon(R.drawable.ic_settings_language)
713 .setPriority(Notification.PRIORITY_LOW)
714 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700715 mNotificationManager.notifyAsUser(null,
716 R.string.select_keyboard_layout_notification_title,
717 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700718 mKeyboardLayoutNotificationShown = true;
719 }
720 }
721
722 // Must be called on handler.
723 private void hideMissingKeyboardLayoutNotification() {
724 if (mKeyboardLayoutNotificationShown) {
725 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700726 mNotificationManager.cancelAsUser(null,
727 R.string.select_keyboard_layout_notification_title,
728 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700729 }
730 }
731
732 // Must be called on handler.
733 private void updateKeyboardLayouts() {
734 // Scan all input devices state for keyboard layouts that have been uninstalled.
735 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
736 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
737 @Override
738 public void visitKeyboardLayout(Resources resources,
739 String descriptor, String label, String collection, int keyboardLayoutResId) {
740 availableKeyboardLayouts.add(descriptor);
741 }
742 });
743 synchronized (mDataStore) {
744 try {
745 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
746 } finally {
747 mDataStore.saveIfNeeded();
748 }
749 }
750
751 // Reload keyboard layouts.
752 reloadKeyboardLayouts();
753 }
754
Jeff Browncf39bdf2012-05-18 14:41:19 -0700755 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
756 String descriptor) {
757 final int numDevices = inputDevices.length;
758 for (int i = 0; i < numDevices; i++) {
759 final InputDevice inputDevice = inputDevices[i];
760 if (inputDevice.getDescriptor().equals(descriptor)) {
761 return true;
762 }
763 }
764 return false;
Jeff Brown8d608662010-08-30 03:02:23 -0700765 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700766
767 @Override // Binder call
768 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700769 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
770 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
771 @Override
772 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700773 String descriptor, String label, String collection, int keyboardLayoutResId) {
774 list.add(new KeyboardLayout(descriptor, label, collection));
Jeff Brown6ec6f792012-04-17 16:52:41 -0700775 }
776 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700777 return list.toArray(new KeyboardLayout[list.size()]);
778 }
779
780 @Override // Binder call
781 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
782 if (keyboardLayoutDescriptor == null) {
783 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
784 }
785
Jeff Brown6ec6f792012-04-17 16:52:41 -0700786 final KeyboardLayout[] result = new KeyboardLayout[1];
787 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
788 @Override
789 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700790 String descriptor, String label, String collection, int keyboardLayoutResId) {
791 result[0] = new KeyboardLayout(descriptor, label, collection);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700792 }
793 });
794 if (result[0] == null) {
795 Log.w(TAG, "Could not get keyboard layout with descriptor '"
796 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700797 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700798 return result[0];
799 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700800
Jeff Brown6ec6f792012-04-17 16:52:41 -0700801 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700802 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700803 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
804 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
805 PackageManager.GET_META_DATA)) {
806 visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700807 }
808 }
809
Jeff Brown6ec6f792012-04-17 16:52:41 -0700810 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
811 KeyboardLayoutVisitor visitor) {
812 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
813 if (d != null) {
814 final PackageManager pm = mContext.getPackageManager();
815 try {
816 ActivityInfo receiver = pm.getReceiverInfo(
817 new ComponentName(d.packageName, d.receiverName),
818 PackageManager.GET_META_DATA);
819 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
820 } catch (NameNotFoundException ex) {
821 }
822 }
823 }
824
825 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
826 String keyboardName, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700827 Bundle metaData = receiver.metaData;
828 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700829 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700830 }
831
832 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
833 if (configResId == 0) {
834 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
835 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700836 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700837 }
838
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700839 CharSequence receiverLabel = receiver.loadLabel(pm);
840 String collection = receiverLabel != null ? receiverLabel.toString() : "";
841
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700842 try {
843 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
844 XmlResourceParser parser = resources.getXml(configResId);
845 try {
846 XmlUtils.beginDocument(parser, "keyboard-layouts");
847
848 for (;;) {
849 XmlUtils.nextElement(parser);
850 String element = parser.getName();
851 if (element == null) {
852 break;
853 }
854 if (element.equals("keyboard-layout")) {
855 TypedArray a = resources.obtainAttributes(
856 parser, com.android.internal.R.styleable.KeyboardLayout);
857 try {
858 String name = a.getString(
859 com.android.internal.R.styleable.KeyboardLayout_name);
860 String label = a.getString(
861 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -0700862 int keyboardLayoutResId = a.getResourceId(
863 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
864 0);
865 if (name == null || label == null || keyboardLayoutResId == 0) {
866 Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700867 + "attributes in keyboard layout "
868 + "resource from receiver "
869 + receiver.packageName + "/" + receiver.name);
870 } else {
871 String descriptor = KeyboardLayoutDescriptor.format(
872 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700873 if (keyboardName == null || name.equals(keyboardName)) {
874 visitor.visitKeyboardLayout(resources, descriptor,
Jeff Brownd9fec5d2012-05-17 16:01:54 -0700875 label, collection, keyboardLayoutResId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700876 }
877 }
878 } finally {
879 a.recycle();
880 }
881 } else {
882 Log.w(TAG, "Skipping unrecognized element '" + element
883 + "' in keyboard layout resource from receiver "
884 + receiver.packageName + "/" + receiver.name);
885 }
886 }
887 } finally {
888 parser.close();
889 }
890 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700891 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700892 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700893 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700894 }
895
896 @Override // Binder call
Jeff Browncf39bdf2012-05-18 14:41:19 -0700897 public String getCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700898 if (inputDeviceDescriptor == null) {
899 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
900 }
901
Jeff Browna3bc5652012-04-17 11:42:25 -0700902 synchronized (mDataStore) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700903 return mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
Jeff Browna3bc5652012-04-17 11:42:25 -0700904 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700905 }
906
907 @Override // Binder call
Jeff Browncf39bdf2012-05-18 14:41:19 -0700908 public void setCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700909 String keyboardLayoutDescriptor) {
910 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -0700911 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700912 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
913 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700914 if (inputDeviceDescriptor == null) {
915 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
916 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700917 if (keyboardLayoutDescriptor == null) {
918 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
919 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700920
Jeff Browna3bc5652012-04-17 11:42:25 -0700921 synchronized (mDataStore) {
922 try {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700923 if (mDataStore.setCurrentKeyboardLayout(
924 inputDeviceDescriptor, keyboardLayoutDescriptor)) {
925 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
926 }
Jeff Browna3bc5652012-04-17 11:42:25 -0700927 } finally {
928 mDataStore.saveIfNeeded();
929 }
930 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700931 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700932
Jeff Browncf39bdf2012-05-18 14:41:19 -0700933 @Override // Binder call
934 public String[] getKeyboardLayoutsForInputDevice(String inputDeviceDescriptor) {
935 if (inputDeviceDescriptor == null) {
936 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
937 }
938
939 synchronized (mDataStore) {
940 return mDataStore.getKeyboardLayouts(inputDeviceDescriptor);
941 }
942 }
943
944 @Override // Binder call
945 public void addKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
946 String keyboardLayoutDescriptor) {
947 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
948 "addKeyboardLayoutForInputDevice()")) {
949 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
950 }
951 if (inputDeviceDescriptor == null) {
952 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
953 }
954 if (keyboardLayoutDescriptor == null) {
955 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
956 }
957
958 synchronized (mDataStore) {
959 try {
960 String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
961 if (mDataStore.addKeyboardLayout(inputDeviceDescriptor, keyboardLayoutDescriptor)
962 && !Objects.equal(oldLayout,
963 mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
964 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
965 }
966 } finally {
967 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700968 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700969 }
970 }
971
972 @Override // Binder call
973 public void removeKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
974 String keyboardLayoutDescriptor) {
975 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
976 "removeKeyboardLayoutForInputDevice()")) {
977 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
978 }
979 if (inputDeviceDescriptor == null) {
980 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
981 }
982 if (keyboardLayoutDescriptor == null) {
983 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
984 }
985
986 synchronized (mDataStore) {
987 try {
988 String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
989 if (mDataStore.removeKeyboardLayout(inputDeviceDescriptor,
990 keyboardLayoutDescriptor)
991 && !Objects.equal(oldLayout,
992 mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
993 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
994 }
995 } finally {
996 mDataStore.saveIfNeeded();
997 }
998 }
999 }
1000
1001 public void switchKeyboardLayout(int deviceId, int direction) {
1002 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
1003 }
1004
1005 // Must be called on handler.
1006 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1007 final InputDevice device = getInputDevice(deviceId);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001008 if (device != null) {
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001009 final String inputDeviceDescriptor = device.getDescriptor();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001010 final boolean changed;
1011 final String keyboardLayoutDescriptor;
1012 synchronized (mDataStore) {
1013 try {
1014 changed = mDataStore.switchKeyboardLayout(inputDeviceDescriptor, direction);
1015 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1016 inputDeviceDescriptor);
1017 } finally {
1018 mDataStore.saveIfNeeded();
1019 }
1020 }
1021
1022 if (changed) {
1023 if (mSwitchedKeyboardLayoutToast != null) {
1024 mSwitchedKeyboardLayoutToast.cancel();
1025 mSwitchedKeyboardLayoutToast = null;
1026 }
1027 if (keyboardLayoutDescriptor != null) {
1028 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1029 if (keyboardLayout != null) {
1030 mSwitchedKeyboardLayoutToast = Toast.makeText(
1031 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1032 mSwitchedKeyboardLayoutToast.show();
1033 }
1034 }
1035
1036 reloadKeyboardLayouts();
1037 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001038 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001039 }
1040
Jeff Brown9302c872011-07-13 22:51:29 -07001041 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001042 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001043 }
1044
Jeff Brown9302c872011-07-13 22:51:29 -07001045 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001046 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001047 }
1048
Jeff Brown349703e2010-06-22 01:27:15 -07001049 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001050 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001051 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001052
1053 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001054 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001055 }
1056
Jeff Browne6504122010-09-27 14:52:15 -07001057 /**
1058 * Atomically transfers touch focus from one window to another as identified by
1059 * their input channels. It is possible for multiple windows to have
1060 * touch focus if they support split touch dispatch
1061 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1062 * method only transfers touch focus of the specified window without affecting
1063 * other windows that may also have touch focus at the same time.
1064 * @param fromChannel The channel of a window that currently has touch focus.
1065 * @param toChannel The channel of the window that should receive touch focus in
1066 * place of the first.
1067 * @return True if the transfer was successful. False if the window with the
1068 * specified channel did not actually have touch focus at the time of the request.
1069 */
1070 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1071 if (fromChannel == null) {
1072 throw new IllegalArgumentException("fromChannel must not be null.");
1073 }
1074 if (toChannel == null) {
1075 throw new IllegalArgumentException("toChannel must not be null.");
1076 }
Jeff Brown4532e612012-04-05 14:27:12 -07001077 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001078 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001079
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001080 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001081 public void tryPointerSpeed(int speed) {
1082 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1083 "tryPointerSpeed()")) {
1084 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1085 }
1086
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001087 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1088 throw new IllegalArgumentException("speed out of range");
1089 }
1090
Jeff Brownac143512012-04-05 18:57:33 -07001091 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001092 }
1093
1094 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001095 int speed = getPointerSpeedSetting();
1096 setPointerSpeedUnchecked(speed);
1097 }
1098
1099 private void setPointerSpeedUnchecked(int speed) {
1100 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1101 InputManager.MAX_POINTER_SPEED);
1102 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001103 }
1104
1105 private void registerPointerSpeedSettingObserver() {
1106 mContext.getContentResolver().registerContentObserver(
1107 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001108 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001109 @Override
1110 public void onChange(boolean selfChange) {
1111 updatePointerSpeedFromSettings();
1112 }
Jeff Brownd4935962012-09-25 13:27:20 -07001113 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001114 }
1115
Jeff Brownac143512012-04-05 18:57:33 -07001116 private int getPointerSpeedSetting() {
1117 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001118 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001119 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1120 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001121 } catch (SettingNotFoundException snfe) {
1122 }
1123 return speed;
1124 }
1125
Jeff Browndaf4a122011-08-26 17:14:14 -07001126 public void updateShowTouchesFromSettings() {
1127 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001128 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001129 }
1130
1131 private void registerShowTouchesSettingObserver() {
1132 mContext.getContentResolver().registerContentObserver(
1133 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001134 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001135 @Override
1136 public void onChange(boolean selfChange) {
1137 updateShowTouchesFromSettings();
1138 }
Jeff Brownd4935962012-09-25 13:27:20 -07001139 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001140 }
1141
1142 private int getShowTouchesSetting(int defaultValue) {
1143 int result = defaultValue;
1144 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001145 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1146 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001147 } catch (SettingNotFoundException snfe) {
1148 }
1149 return result;
1150 }
1151
Jeff Browna47425a2012-04-13 04:09:27 -07001152 // Binder call
1153 @Override
1154 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1155 if (repeat >= pattern.length) {
1156 throw new ArrayIndexOutOfBoundsException();
1157 }
1158
1159 VibratorToken v;
1160 synchronized (mVibratorLock) {
1161 v = mVibratorTokens.get(token);
1162 if (v == null) {
1163 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1164 try {
1165 token.linkToDeath(v, 0);
1166 } catch (RemoteException ex) {
1167 // give up
1168 throw new RuntimeException(ex);
1169 }
1170 mVibratorTokens.put(token, v);
1171 }
1172 }
1173
1174 synchronized (v) {
1175 v.mVibrating = true;
1176 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1177 }
1178 }
1179
1180 // Binder call
1181 @Override
1182 public void cancelVibrate(int deviceId, IBinder token) {
1183 VibratorToken v;
1184 synchronized (mVibratorLock) {
1185 v = mVibratorTokens.get(token);
1186 if (v == null || v.mDeviceId != deviceId) {
1187 return; // nothing to cancel
1188 }
1189 }
1190
1191 cancelVibrateIfNeeded(v);
1192 }
1193
1194 void onVibratorTokenDied(VibratorToken v) {
1195 synchronized (mVibratorLock) {
1196 mVibratorTokens.remove(v.mToken);
1197 }
1198
1199 cancelVibrateIfNeeded(v);
1200 }
1201
1202 private void cancelVibrateIfNeeded(VibratorToken v) {
1203 synchronized (v) {
1204 if (v.mVibrating) {
1205 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1206 v.mVibrating = false;
1207 }
1208 }
1209 }
1210
Jeff Brown4532e612012-04-05 14:27:12 -07001211 @Override
1212 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001213 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001214 != PackageManager.PERMISSION_GRANTED) {
1215 pw.println("Permission Denial: can't dump InputManager from from pid="
1216 + Binder.getCallingPid()
1217 + ", uid=" + Binder.getCallingUid());
1218 return;
1219 }
1220
1221 pw.println("INPUT MANAGER (dumpsys input)\n");
1222 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001223 if (dumpStr != null) {
1224 pw.println(dumpStr);
1225 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001226 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001227
Jeff Brownac143512012-04-05 18:57:33 -07001228 private boolean checkCallingPermission(String permission, String func) {
1229 // Quick check: if the calling permission is me, it's all okay.
1230 if (Binder.getCallingPid() == Process.myPid()) {
1231 return true;
1232 }
1233
1234 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1235 return true;
1236 }
1237 String msg = "Permission Denial: " + func + " from pid="
1238 + Binder.getCallingPid()
1239 + ", uid=" + Binder.getCallingUid()
1240 + " requires " + permission;
1241 Slog.w(TAG, msg);
1242 return false;
1243 }
1244
Jeff Brown4532e612012-04-05 14:27:12 -07001245 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001246 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001247 public void monitor() {
1248 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001249 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001250 }
1251
Jeff Brown4532e612012-04-05 14:27:12 -07001252 // Native callback.
1253 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001254 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001255 }
1256
1257 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001258 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1259 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001260 if (!mInputDevicesChangedPending) {
1261 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001262 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1263 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001264 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001265
1266 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001267 }
1268 }
1269
1270 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001271 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1272 if (DEBUG) {
1273 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1274 + ", mask=" + Integer.toHexString(switchMask));
1275 }
1276
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001277 if ((switchMask & SW_LID_BIT) != 0) {
1278 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001279 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001280 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001281
1282 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1283 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1284 switchMask);
1285 }
Jeff Brown4532e612012-04-05 14:27:12 -07001286 }
1287
1288 // Native callback.
1289 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001290 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001291 }
1292
1293 // Native callback.
1294 private long notifyANR(InputApplicationHandle inputApplicationHandle,
1295 InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001296 return mWindowManagerCallbacks.notifyANR(inputApplicationHandle, inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001297 }
1298
1299 // Native callback.
1300 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1301 synchronized (mInputFilterLock) {
1302 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001303 try {
1304 mInputFilter.filterInputEvent(event, policyFlags);
1305 } catch (RemoteException e) {
1306 /* ignore */
1307 }
Jeff Brown4532e612012-04-05 14:27:12 -07001308 return false;
1309 }
1310 }
1311 event.recycle();
1312 return true;
1313 }
1314
1315 // Native callback.
1316 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001317 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(
Jeff Brown4532e612012-04-05 14:27:12 -07001318 event, policyFlags, isScreenOn);
1319 }
1320
1321 // Native callback.
1322 private int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001323 return mWindowManagerCallbacks.interceptMotionBeforeQueueingWhenScreenOff(policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001324 }
1325
1326 // Native callback.
1327 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1328 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001329 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001330 }
1331
1332 // Native callback.
1333 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1334 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001335 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001336 }
1337
1338 // Native callback.
1339 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1340 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1341 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1342 }
1343
1344 // Native callback.
1345 private int getVirtualKeyQuietTimeMillis() {
1346 return mContext.getResources().getInteger(
1347 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1348 }
1349
1350 // Native callback.
1351 private String[] getExcludedDeviceNames() {
1352 ArrayList<String> names = new ArrayList<String>();
1353
1354 // Read partner-provided list of excluded input devices
1355 XmlPullParser parser = null;
1356 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1357 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1358 FileReader confreader = null;
1359 try {
1360 confreader = new FileReader(confFile);
1361 parser = Xml.newPullParser();
1362 parser.setInput(confreader);
1363 XmlUtils.beginDocument(parser, "devices");
1364
1365 while (true) {
1366 XmlUtils.nextElement(parser);
1367 if (!"device".equals(parser.getName())) {
1368 break;
1369 }
1370 String name = parser.getAttributeValue(null, "name");
1371 if (name != null) {
1372 names.add(name);
1373 }
1374 }
1375 } catch (FileNotFoundException e) {
1376 // It's ok if the file does not exist.
1377 } catch (Exception e) {
1378 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1379 } finally {
1380 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1381 }
1382
1383 return names.toArray(new String[names.size()]);
1384 }
1385
1386 // Native callback.
1387 private int getKeyRepeatTimeout() {
1388 return ViewConfiguration.getKeyRepeatTimeout();
1389 }
1390
1391 // Native callback.
1392 private int getKeyRepeatDelay() {
1393 return ViewConfiguration.getKeyRepeatDelay();
1394 }
1395
1396 // Native callback.
1397 private int getHoverTapTimeout() {
1398 return ViewConfiguration.getHoverTapTimeout();
1399 }
1400
1401 // Native callback.
1402 private int getHoverTapSlop() {
1403 return ViewConfiguration.getHoverTapSlop();
1404 }
1405
1406 // Native callback.
1407 private int getDoubleTapTimeout() {
1408 return ViewConfiguration.getDoubleTapTimeout();
1409 }
1410
1411 // Native callback.
1412 private int getLongPressTimeout() {
1413 return ViewConfiguration.getLongPressTimeout();
1414 }
1415
1416 // Native callback.
1417 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001418 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001419 }
1420
1421 // Native callback.
1422 private PointerIcon getPointerIcon() {
1423 return PointerIcon.getDefaultIcon(mContext);
1424 }
1425
Jeff Brown6ec6f792012-04-17 16:52:41 -07001426 // Native callback.
1427 private String[] getKeyboardLayoutOverlay(String inputDeviceDescriptor) {
1428 if (!mSystemReady) {
1429 return null;
1430 }
1431
Jeff Browncf39bdf2012-05-18 14:41:19 -07001432 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(
1433 inputDeviceDescriptor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001434 if (keyboardLayoutDescriptor == null) {
1435 return null;
1436 }
1437
1438 final String[] result = new String[2];
1439 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1440 @Override
1441 public void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001442 String descriptor, String label, String collection, int keyboardLayoutResId) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001443 try {
1444 result[0] = descriptor;
1445 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001446 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001447 } catch (IOException ex) {
1448 } catch (NotFoundException ex) {
1449 }
1450 }
1451 });
1452 if (result[0] == null) {
1453 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1454 + keyboardLayoutDescriptor + "'.");
1455 return null;
1456 }
1457 return result;
1458 }
1459
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001460 // Native callback.
1461 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001462 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1463 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1464 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001465 }
1466 return null;
1467 }
1468
Jeff Brown4532e612012-04-05 14:27:12 -07001469 /**
1470 * Callback interface implemented by the Window Manager.
1471 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001472 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001473 public void notifyConfigurationChanged();
1474
1475 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1476
1477 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1478
1479 public long notifyANR(InputApplicationHandle inputApplicationHandle,
1480 InputWindowHandle inputWindowHandle);
1481
1482 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn);
1483
1484 public int interceptMotionBeforeQueueingWhenScreenOff(int policyFlags);
1485
1486 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1487 KeyEvent event, int policyFlags);
1488
1489 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1490 KeyEvent event, int policyFlags);
1491
1492 public int getPointerLayer();
1493 }
1494
1495 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001496 * Callback interface implemented by WiredAccessoryObserver.
1497 */
1498 public interface WiredAccessoryCallbacks {
1499 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
1500 }
1501
1502 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001503 * Private handler for the input manager.
1504 */
1505 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07001506 public InputManagerHandler(Looper looper) {
1507 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07001508 }
1509
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001510 @Override
1511 public void handleMessage(Message msg) {
1512 switch (msg.what) {
1513 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07001514 deliverInputDevicesChanged((InputDevice[])msg.obj);
1515 break;
1516 case MSG_SWITCH_KEYBOARD_LAYOUT:
1517 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
1518 break;
1519 case MSG_RELOAD_KEYBOARD_LAYOUTS:
1520 reloadKeyboardLayouts();
1521 break;
1522 case MSG_UPDATE_KEYBOARD_LAYOUTS:
1523 updateKeyboardLayouts();
1524 break;
1525 case MSG_RELOAD_DEVICE_ALIASES:
1526 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001527 break;
1528 }
1529 }
1530 }
1531
1532 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001533 * Hosting interface for input filters to call back into the input manager.
1534 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001535 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07001536 private boolean mDisconnected;
1537
1538 public void disconnectLocked() {
1539 mDisconnected = true;
1540 }
1541
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001542 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07001543 public void sendInputEvent(InputEvent event, int policyFlags) {
1544 if (event == null) {
1545 throw new IllegalArgumentException("event must not be null");
1546 }
1547
1548 synchronized (mInputFilterLock) {
1549 if (!mDisconnected) {
Jeff Brownac143512012-04-05 18:57:33 -07001550 nativeInjectInputEvent(mPtr, event, 0, 0,
1551 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001552 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1553 }
1554 }
1555 }
1556 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001557
1558 private static final class KeyboardLayoutDescriptor {
1559 public String packageName;
1560 public String receiverName;
1561 public String keyboardLayoutName;
1562
1563 public static String format(String packageName,
1564 String receiverName, String keyboardName) {
1565 return packageName + "/" + receiverName + "/" + keyboardName;
1566 }
1567
1568 public static KeyboardLayoutDescriptor parse(String descriptor) {
1569 int pos = descriptor.indexOf('/');
1570 if (pos < 0 || pos + 1 == descriptor.length()) {
1571 return null;
1572 }
1573 int pos2 = descriptor.indexOf('/', pos + 1);
1574 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1575 return null;
1576 }
1577
1578 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1579 result.packageName = descriptor.substring(0, pos);
1580 result.receiverName = descriptor.substring(pos + 1, pos2);
1581 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1582 return result;
1583 }
1584 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001585
Jeff Brown6ec6f792012-04-17 16:52:41 -07001586 private interface KeyboardLayoutVisitor {
1587 void visitKeyboardLayout(Resources resources,
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001588 String descriptor, String label, String collection, int keyboardLayoutResId);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001589 }
1590
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001591 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1592 private final int mPid;
1593 private final IInputDevicesChangedListener mListener;
1594
1595 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1596 mPid = pid;
1597 mListener = listener;
1598 }
1599
1600 @Override
1601 public void binderDied() {
1602 if (DEBUG) {
1603 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1604 }
1605 onInputDevicesChangedListenerDied(mPid);
1606 }
1607
1608 public void notifyInputDevicesChanged(int[] info) {
1609 try {
1610 mListener.onInputDevicesChanged(info);
1611 } catch (RemoteException ex) {
1612 Slog.w(TAG, "Failed to notify process "
1613 + mPid + " that input devices changed, assuming it died.", ex);
1614 binderDied();
1615 }
1616 }
1617 }
Jeff Browna47425a2012-04-13 04:09:27 -07001618
1619 private final class VibratorToken implements DeathRecipient {
1620 public final int mDeviceId;
1621 public final IBinder mToken;
1622 public final int mTokenValue;
1623
1624 public boolean mVibrating;
1625
1626 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1627 mDeviceId = deviceId;
1628 mToken = token;
1629 mTokenValue = tokenValue;
1630 }
1631
1632 @Override
1633 public void binderDied() {
1634 if (DEBUG) {
1635 Slog.d(TAG, "Vibrator token died.");
1636 }
1637 onVibratorTokenDied(this);
1638 }
1639 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001640}