blob: ae8fca83754cf20f09f64fa7b39104f2741665e1 [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
Yohei Yukawab097b822015-12-01 10:43:08 -080019import android.annotation.Nullable;
Jeff Brownca9bc702014-02-11 14:32:56 -080020import android.view.Display;
Michael Wright39e5e942015-08-19 22:52:47 +010021import com.android.internal.os.SomeArgs;
Jeff Browncf39bdf2012-05-18 14:41:19 -070022import com.android.internal.R;
Jeff Brown46b9ac02010-04-22 18:58:52 -070023import com.android.internal.util.XmlUtils;
Jeff Brown4ccb8232014-01-16 22:16:42 -080024import com.android.server.DisplayThread;
25import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070026import com.android.server.Watchdog;
Jeff Brown46b9ac02010-04-22 18:58:52 -070027
28import org.xmlpull.v1.XmlPullParser;
29
Jeff Browna3bc5652012-04-17 11:42:25 -070030import android.Manifest;
Jeff Browncf39bdf2012-05-18 14:41:19 -070031import android.app.Notification;
32import android.app.NotificationManager;
33import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070034import android.bluetooth.BluetoothAdapter;
35import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070036import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070037import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070038import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070039import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070040import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070041import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070042import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070043import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070044import android.content.pm.ResolveInfo;
45import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070046import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070047import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070048import android.content.res.TypedArray;
49import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070050import android.database.ContentObserver;
Jeff Brown4ccb8232014-01-16 22:16:42 -080051import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070052import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070053import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080054import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070055import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080056import android.hardware.input.InputManagerInternal;
Michael Wright39e5e942015-08-19 22:52:47 +010057import android.hardware.input.ITabletModeChangedListener;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070058import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080059import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070060import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070061import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070062import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070063import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070064import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070065import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070066import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080067import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070068import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070070import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070071import android.provider.Settings;
72import android.provider.Settings.SettingNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070073import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070075import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070076import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070077import android.view.IInputFilter;
78import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070079import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070080import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070081import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080082import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070083import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070084import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080085import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070086import android.view.WindowManagerPolicy;
Yohei Yukawab097b822015-12-01 10:43:08 -080087import android.view.inputmethod.InputMethod;
88import android.view.inputmethod.InputMethodInfo;
89import android.view.inputmethod.InputMethodSubtype;
Jeff Browncf39bdf2012-05-18 14:41:19 -070090import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070091
Jeff Brown46b9ac02010-04-22 18:58:52 -070092import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070093import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070094import java.io.FileNotFoundException;
95import java.io.FileReader;
96import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -070097import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -070098import java.io.PrintWriter;
99import java.util.ArrayList;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700100import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700101import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100102import java.util.List;
Jeff Browna3bc5652012-04-17 11:42:25 -0700103
Jeff Brown6ec6f792012-04-17 16:52:41 -0700104import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -0700105import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700106
107/*
108 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700109 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700110public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800111 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700112 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700113 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700114
Jeff Brown4532e612012-04-05 14:27:12 -0700115 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
116
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700117 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700118 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
119 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
120 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
121 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100122 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Yohei Yukawab097b822015-12-01 10:43:08 -0800123 private static final int MSG_INPUT_METHOD_SUBTYPE_CHANGED = 7;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700124
Jeff Brown4532e612012-04-05 14:27:12 -0700125 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000126 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700127
Jeff Brown46b9ac02010-04-22 18:58:52 -0700128 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700129 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700130
131 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700132 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700133 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700134 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700135
Michael Wright39e5e942015-08-19 22:52:47 +0100136 private final Object mTabletModeLock = new Object();
137 // List of currently registered tablet mode changed listeners by process id
138 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
139 new SparseArray<>(); // guarded by mTabletModeLock
140 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
141 new ArrayList<>();
142
Jeff Browna3bc5652012-04-17 11:42:25 -0700143 // Persistent data store. Must be locked each time during use.
144 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145
146 // List of currently registered input devices changed listeners by process id.
147 private Object mInputDevicesLock = new Object();
148 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
149 private InputDevice[] mInputDevices = new InputDevice[0];
150 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
151 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
152 private final ArrayList<InputDevicesChangedListenerRecord>
153 mTempInputDevicesChangedListenersToNotify =
154 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700155 private final ArrayList<InputDevice>
156 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
157 private boolean mKeyboardLayoutNotificationShown;
158 private PendingIntent mKeyboardLayoutIntent;
159 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700160
Jeff Browna47425a2012-04-13 04:09:27 -0700161 // State for vibrator tokens.
162 private Object mVibratorLock = new Object();
163 private HashMap<IBinder, VibratorToken> mVibratorTokens =
164 new HashMap<IBinder, VibratorToken>();
165 private int mNextVibratorTokenValue;
166
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700167 // State for the currently installed input filter.
168 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700169 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700170 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700171
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000172 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700173 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000174 private static native void nativeStart(long ptr);
175 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700176 int displayId, int rotation,
177 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700178 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
179 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700180
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000181 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700182 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000183 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700184 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000185 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700186 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700188 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000189 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800190 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000191 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
192 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Jeff Brownca9bc702014-02-11 14:32:56 -0800193 private static native int nativeInjectInputEvent(long ptr, InputEvent event, int displayId,
Jeff Brown0029c662011-03-30 02:25:18 -0700194 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
195 int policyFlags);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
197 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
198 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
199 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700200 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000201 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700202 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000203 private static native void nativeSetPointerSpeed(long ptr, int speed);
204 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700205 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800206 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000207 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700208 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000209 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
210 private static native void nativeReloadKeyboardLayouts(long ptr);
211 private static native void nativeReloadDeviceAliases(long ptr);
212 private static native String nativeDump(long ptr);
213 private static native void nativeMonitor(long ptr);
Jun Mukai1db53972015-09-11 18:08:31 -0700214 private static native void nativeSetPointerIconShape(long ptr, int iconId);
Jeff Brown4532e612012-04-05 14:27:12 -0700215
Jeff Brownac143512012-04-05 18:57:33 -0700216 // Input event injection constants defined in InputDispatcher.h.
217 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
218 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
219 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
220 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
221
222 // Maximum number of milliseconds to wait for input event injection.
223 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
224
Jeff Brown6d0fec22010-07-23 21:28:06 -0700225 // Key states (may be returned by queries about the current state of a
226 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700227
Jeff Brown6d0fec22010-07-23 21:28:06 -0700228 /** The key state is unknown or the requested key itself is not supported. */
229 public static final int KEY_STATE_UNKNOWN = -1;
230
231 /** The key is up. /*/
232 public static final int KEY_STATE_UP = 0;
233
234 /** The key is down. */
235 public static final int KEY_STATE_DOWN = 1;
236
237 /** The key is down but is a virtual key press that is being emulated by the system. */
238 public static final int KEY_STATE_VIRTUAL = 2;
239
Jeff Brownc458ce92012-04-30 14:58:40 -0700240 /** Scan code: Mouse / trackball button. */
241 public static final int BTN_MOUSE = 0x110;
242
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700243 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700244 /** Switch code: Lid switch. When set, lid is shut. */
245 public static final int SW_LID = 0x00;
246
Michael Wright39e5e942015-08-19 22:52:47 +0100247 /** Switch code: Tablet mode switch.
248 * When set, the device is in tablet mode (i.e. no keyboard is connected).
249 */
250 public static final int SW_TABLET_MODE = 0x01;
251
Jeff Brownc458ce92012-04-30 14:58:40 -0700252 /** Switch code: Keypad slide. When set, keyboard is exposed. */
253 public static final int SW_KEYPAD_SLIDE = 0x0a;
254
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700255 /** Switch code: Headphone. When set, headphone is inserted. */
256 public static final int SW_HEADPHONE_INSERT = 0x02;
257
258 /** Switch code: Microphone. When set, microphone is inserted. */
259 public static final int SW_MICROPHONE_INSERT = 0x04;
260
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500261 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
262 public static final int SW_LINEOUT_INSERT = 0x06;
263
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700264 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
265 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
266
Michael Wright3818c922014-09-02 13:59:07 -0700267 /** Switch code: Camera lens cover. When set the lens is covered. */
268 public static final int SW_CAMERA_LENS_COVER = 0x09;
269
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700270 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100271 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700272 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
273 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
274 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500275 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700276 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
277 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500278 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700279 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700280
281 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
282 final boolean mUseDevInputEventForAudioJack;
283
Jeff Brown4ccb8232014-01-16 22:16:42 -0800284 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700285 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800286 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800287
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700288 mUseDevInputEventForAudioJack =
289 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
290 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
291 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700292 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800293
294 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700295 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700296
Jeff Browna9d131c2012-09-20 16:48:17 -0700297 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
298 mWindowManagerCallbacks = callbacks;
299 }
300
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700301 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
302 mWiredAccessoryCallbacks = callbacks;
303 }
304
Jeff Brown46b9ac02010-04-22 18:58:52 -0700305 public void start() {
306 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700307 nativeStart(mPtr);
308
309 // Add ourself to the Watchdog monitors.
310 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700311
312 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700313 registerShowTouchesSettingObserver();
314
Jeff Brownd4935962012-09-25 13:27:20 -0700315 mContext.registerReceiver(new BroadcastReceiver() {
316 @Override
317 public void onReceive(Context context, Intent intent) {
318 updatePointerSpeedFromSettings();
319 updateShowTouchesFromSettings();
320 }
321 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
322
Jeff Brown1a84fd12011-06-02 01:26:32 -0700323 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700324 updateShowTouchesFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700325 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700326
Matthew Xie96313142012-06-29 16:57:31 -0700327 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700328 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700329 if (DEBUG) {
330 Slog.d(TAG, "System ready.");
331 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700332 mNotificationManager = (NotificationManager)mContext.getSystemService(
333 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700334 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700335
336 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
337 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
338 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800339 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700340 filter.addDataScheme("package");
341 mContext.registerReceiver(new BroadcastReceiver() {
342 @Override
343 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700344 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700345 }
346 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700347
348 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
349 mContext.registerReceiver(new BroadcastReceiver() {
350 @Override
351 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700352 reloadDeviceAliases();
353 }
354 }, filter, null, mHandler);
355
Jeff Browncf39bdf2012-05-18 14:41:19 -0700356 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
357 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700358
359 if (mWiredAccessoryCallbacks != null) {
360 mWiredAccessoryCallbacks.systemReady();
361 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700362 }
363
364 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700365 if (DEBUG) {
366 Slog.d(TAG, "Reloading keyboard layouts.");
367 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700368 nativeReloadKeyboardLayouts(mPtr);
369 }
370
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700371 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700372 if (DEBUG) {
373 Slog.d(TAG, "Reloading device names.");
374 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700375 nativeReloadDeviceAliases(mPtr);
376 }
377
Jeff Brown4ccb8232014-01-16 22:16:42 -0800378 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Jeff Brownd728bf52012-09-08 18:05:28 -0700379 DisplayViewport externalTouchViewport) {
380 if (defaultViewport.valid) {
381 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700382 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700383
384 if (externalTouchViewport.valid) {
385 setDisplayViewport(true, externalTouchViewport);
386 } else if (defaultViewport.valid) {
387 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700388 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700389 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700390
Jeff Brownd728bf52012-09-08 18:05:28 -0700391 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
392 nativeSetDisplayViewport(mPtr, external,
393 viewport.displayId, viewport.orientation,
394 viewport.logicalFrame.left, viewport.logicalFrame.top,
395 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
396 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700397 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
398 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700399 }
Jeff Brownac143512012-04-05 18:57:33 -0700400
Jeff Brown6d0fec22010-07-23 21:28:06 -0700401 /**
402 * Gets the current state of a key or button by key code.
403 * @param deviceId The input device id, or -1 to consult all devices.
404 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
405 * consider all input sources. An input device is consulted if at least one of its
406 * non-class input source bits matches the specified source mask.
407 * @param keyCode The key code to check.
408 * @return The key state.
409 */
410 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700411 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700412 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700413
Jeff Brown6d0fec22010-07-23 21:28:06 -0700414 /**
415 * Gets the current state of a key or button by scan code.
416 * @param deviceId The input device id, or -1 to consult all devices.
417 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
418 * consider all input sources. An input device is consulted if at least one of its
419 * non-class input source bits matches the specified source mask.
420 * @param scanCode The scan code to check.
421 * @return The key state.
422 */
423 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700424 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425 }
RoboErikfb290df2013-12-16 11:27:55 -0800426
Jeff Brown6d0fec22010-07-23 21:28:06 -0700427 /**
428 * Gets the current state of a switch by switch code.
429 * @param deviceId The input device id, or -1 to consult all devices.
430 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
431 * consider all input sources. An input device is consulted if at least one of its
432 * non-class input source bits matches the specified source mask.
433 * @param switchCode The switch code to check.
434 * @return The switch state.
435 */
436 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700437 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700438 }
439
Jeff Brown6d0fec22010-07-23 21:28:06 -0700440 /**
441 * Determines whether the specified key codes are supported by a particular device.
442 * @param deviceId The input device id, or -1 to consult all devices.
443 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
444 * consider all input sources. An input device is consulted if at least one of its
445 * non-class input source bits matches the specified source mask.
446 * @param keyCodes The array of key codes to check.
447 * @param keyExists An array at least as large as keyCodes whose entries will be set
448 * to true or false based on the presence or absence of support for the corresponding
449 * key codes.
450 * @return True if the lookup was successful, false otherwise.
451 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700452 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700453 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700454 if (keyCodes == null) {
455 throw new IllegalArgumentException("keyCodes must not be null.");
456 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700457 if (keyExists == null || keyExists.length < keyCodes.length) {
458 throw new IllegalArgumentException("keyExists must not be null and must be at "
459 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700460 }
RoboErikfb290df2013-12-16 11:27:55 -0800461
Jeff Brown4532e612012-04-05 14:27:12 -0700462 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700463 }
RoboErikfb290df2013-12-16 11:27:55 -0800464
Jeff Browna41ca772010-08-11 14:46:32 -0700465 /**
466 * Creates an input channel that will receive all input from the input dispatcher.
467 * @param inputChannelName The input channel name.
468 * @return The input channel.
469 */
470 public InputChannel monitorInput(String inputChannelName) {
471 if (inputChannelName == null) {
472 throw new IllegalArgumentException("inputChannelName must not be null.");
473 }
RoboErikfb290df2013-12-16 11:27:55 -0800474
Jeff Browna41ca772010-08-11 14:46:32 -0700475 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700476 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700477 inputChannels[0].dispose(); // don't need to retain the Java object reference
478 return inputChannels[1];
479 }
480
481 /**
482 * Registers an input channel so that it can be used as an input event target.
483 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800484 * @param inputWindowHandle The handle of the input window associated with the
485 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700486 */
Jeff Brown928e0542011-01-10 11:17:36 -0800487 public void registerInputChannel(InputChannel inputChannel,
488 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700489 if (inputChannel == null) {
490 throw new IllegalArgumentException("inputChannel must not be null.");
491 }
RoboErikfb290df2013-12-16 11:27:55 -0800492
Jeff Brown4532e612012-04-05 14:27:12 -0700493 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700494 }
RoboErikfb290df2013-12-16 11:27:55 -0800495
Jeff Browna41ca772010-08-11 14:46:32 -0700496 /**
497 * Unregisters an input channel.
498 * @param inputChannel The input channel to unregister.
499 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700500 public void unregisterInputChannel(InputChannel inputChannel) {
501 if (inputChannel == null) {
502 throw new IllegalArgumentException("inputChannel must not be null.");
503 }
RoboErikfb290df2013-12-16 11:27:55 -0800504
Jeff Brown4532e612012-04-05 14:27:12 -0700505 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700506 }
Jeff Brown0029c662011-03-30 02:25:18 -0700507
508 /**
509 * Sets an input filter that will receive all input events before they are dispatched.
510 * The input filter may then reinterpret input events or inject new ones.
511 *
512 * To ensure consistency, the input dispatcher automatically drops all events
513 * in progress whenever an input filter is installed or uninstalled. After an input
514 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
515 * Any events it attempts to send after it has been uninstalled will be dropped.
516 *
517 * @param filter The input filter, or null to remove the current filter.
518 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700519 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700520 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700521 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700522 if (oldFilter == filter) {
523 return; // nothing to do
524 }
525
526 if (oldFilter != null) {
527 mInputFilter = null;
528 mInputFilterHost.disconnectLocked();
529 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700530 try {
531 oldFilter.uninstall();
532 } catch (RemoteException re) {
533 /* ignore */
534 }
Jeff Brown0029c662011-03-30 02:25:18 -0700535 }
536
537 if (filter != null) {
538 mInputFilter = filter;
539 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700540 try {
541 filter.install(mInputFilterHost);
542 } catch (RemoteException re) {
543 /* ignore */
544 }
Jeff Brown0029c662011-03-30 02:25:18 -0700545 }
546
Jeff Brown4532e612012-04-05 14:27:12 -0700547 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700548 }
549 }
550
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700551 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700552 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brownca9bc702014-02-11 14:32:56 -0800553 return injectInputEventInternal(event, Display.DEFAULT_DISPLAY, mode);
554 }
555
556 private boolean injectInputEventInternal(InputEvent event, int displayId, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700557 if (event == null) {
558 throw new IllegalArgumentException("event must not be null");
559 }
Jeff Brownac143512012-04-05 18:57:33 -0700560 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
561 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
562 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
563 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700564 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700565
Jeff Brownac143512012-04-05 18:57:33 -0700566 final int pid = Binder.getCallingPid();
567 final int uid = Binder.getCallingUid();
568 final long ident = Binder.clearCallingIdentity();
569 final int result;
570 try {
Jeff Brownca9bc702014-02-11 14:32:56 -0800571 result = nativeInjectInputEvent(mPtr, event, displayId, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700572 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
573 } finally {
574 Binder.restoreCallingIdentity(ident);
575 }
576 switch (result) {
577 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
578 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
579 throw new SecurityException(
580 "Injecting to another application requires INJECT_EVENTS permission");
581 case INPUT_EVENT_INJECTION_SUCCEEDED:
582 return true;
583 case INPUT_EVENT_INJECTION_TIMED_OUT:
584 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
585 return false;
586 case INPUT_EVENT_INJECTION_FAILED:
587 default:
588 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
589 return false;
590 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700591 }
Jeff Brown0029c662011-03-30 02:25:18 -0700592
Jeff Brown8d608662010-08-30 03:02:23 -0700593 /**
594 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700595 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700596 * @return The input device or null if not found.
597 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700598 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700599 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700600 synchronized (mInputDevicesLock) {
601 final int count = mInputDevices.length;
602 for (int i = 0; i < count; i++) {
603 final InputDevice inputDevice = mInputDevices[i];
604 if (inputDevice.getId() == deviceId) {
605 return inputDevice;
606 }
607 }
608 }
609 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700610 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700611
Jeff Brown8d608662010-08-30 03:02:23 -0700612 /**
613 * Gets the ids of all input devices in the system.
614 * @return The input device ids.
615 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700616 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700617 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700618 synchronized (mInputDevicesLock) {
619 final int count = mInputDevices.length;
620 int[] ids = new int[count];
621 for (int i = 0; i < count; i++) {
622 ids[i] = mInputDevices[i].getId();
623 }
624 return ids;
625 }
626 }
627
Jeff Browndaa37532012-05-01 15:54:03 -0700628 /**
629 * Gets all input devices in the system.
630 * @return The array of input devices.
631 */
632 public InputDevice[] getInputDevices() {
633 synchronized (mInputDevicesLock) {
634 return mInputDevices;
635 }
636 }
637
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700638 @Override // Binder call
639 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
640 if (listener == null) {
641 throw new IllegalArgumentException("listener must not be null");
642 }
643
644 synchronized (mInputDevicesLock) {
645 int callingPid = Binder.getCallingPid();
646 if (mInputDevicesChangedListeners.get(callingPid) != null) {
647 throw new SecurityException("The calling process has already "
648 + "registered an InputDevicesChangedListener.");
649 }
650
651 InputDevicesChangedListenerRecord record =
652 new InputDevicesChangedListenerRecord(callingPid, listener);
653 try {
654 IBinder binder = listener.asBinder();
655 binder.linkToDeath(record, 0);
656 } catch (RemoteException ex) {
657 // give up
658 throw new RuntimeException(ex);
659 }
660
661 mInputDevicesChangedListeners.put(callingPid, record);
662 }
663 }
664
665 private void onInputDevicesChangedListenerDied(int pid) {
666 synchronized (mInputDevicesLock) {
667 mInputDevicesChangedListeners.remove(pid);
668 }
669 }
670
671 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700672 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
673 // Scan for changes.
674 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700675 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700676 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700677 final int numListeners;
678 final int[] deviceIdAndGeneration;
679 synchronized (mInputDevicesLock) {
680 if (!mInputDevicesChangedPending) {
681 return;
682 }
683 mInputDevicesChangedPending = false;
684
685 numListeners = mInputDevicesChangedListeners.size();
686 for (int i = 0; i < numListeners; i++) {
687 mTempInputDevicesChangedListenersToNotify.add(
688 mInputDevicesChangedListeners.valueAt(i));
689 }
690
691 final int numDevices = mInputDevices.length;
692 deviceIdAndGeneration = new int[numDevices * 2];
693 for (int i = 0; i < numDevices; i++) {
694 final InputDevice inputDevice = mInputDevices[i];
695 deviceIdAndGeneration[i * 2] = inputDevice.getId();
696 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700697
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700698 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700699 if (!containsInputDeviceWithDescriptor(oldInputDevices,
700 inputDevice.getDescriptor())) {
701 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
702 } else {
703 mTempFullKeyboards.add(inputDevice);
704 }
705 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700706 }
707 }
708
Jeff Browncf39bdf2012-05-18 14:41:19 -0700709 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700710 for (int i = 0; i < numListeners; i++) {
711 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
712 deviceIdAndGeneration);
713 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700714 mTempInputDevicesChangedListenersToNotify.clear();
715
716 // Check for missing keyboard layouts.
717 if (mNotificationManager != null) {
718 final int numFullKeyboards = mTempFullKeyboards.size();
719 boolean missingLayoutForExternalKeyboard = false;
720 boolean missingLayoutForExternalKeyboardAdded = false;
Michael Wrightc93fbd12014-09-22 20:07:59 -0700721 boolean multipleMissingLayoutsForExternalKeyboardsAdded = false;
722 InputDevice keyboardMissingLayout = null;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700723 synchronized (mDataStore) {
724 for (int i = 0; i < numFullKeyboards; i++) {
725 final InputDevice inputDevice = mTempFullKeyboards.get(i);
Michael Wright86aaca62014-09-08 18:54:45 -0700726 final String layout =
727 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
728 if (layout == null) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700729 missingLayoutForExternalKeyboard = true;
730 if (i < numFullKeyboardsAdded) {
731 missingLayoutForExternalKeyboardAdded = true;
Michael Wrightc93fbd12014-09-22 20:07:59 -0700732 if (keyboardMissingLayout == null) {
733 keyboardMissingLayout = inputDevice;
734 } else {
735 multipleMissingLayoutsForExternalKeyboardsAdded = true;
736 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700737 }
738 }
739 }
740 }
741 if (missingLayoutForExternalKeyboard) {
742 if (missingLayoutForExternalKeyboardAdded) {
Michael Wrightc93fbd12014-09-22 20:07:59 -0700743 if (multipleMissingLayoutsForExternalKeyboardsAdded) {
744 // We have more than one keyboard missing a layout, so drop the
745 // user at the generic input methods page so they can pick which
746 // one to set.
747 showMissingKeyboardLayoutNotification(null);
748 } else {
749 showMissingKeyboardLayoutNotification(keyboardMissingLayout);
750 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700751 }
752 } else if (mKeyboardLayoutNotificationShown) {
753 hideMissingKeyboardLayoutNotification();
754 }
755 }
756 mTempFullKeyboards.clear();
757 }
758
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800759 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700760 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
761 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800762 if (inputDeviceDescriptor == null) {
763 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
764 }
765
766 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700767 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800768 }
769 }
770
771 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700772 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800773 TouchCalibration calibration) {
774 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
775 "setTouchCalibrationForInputDevice()")) {
776 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
777 }
778 if (inputDeviceDescriptor == null) {
779 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
780 }
781 if (calibration == null) {
782 throw new IllegalArgumentException("calibration must not be null");
783 }
Jason Gerecked5220742014-03-10 09:47:59 -0700784 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
785 throw new IllegalArgumentException("surfaceRotation value out of bounds");
786 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800787
788 synchronized (mDataStore) {
789 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700790 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
791 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800792 nativeReloadCalibration(mPtr);
793 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800794 } finally {
795 mDataStore.saveIfNeeded();
796 }
797 }
798 }
799
Michael Wright39e5e942015-08-19 22:52:47 +0100800 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100801 public int isInTabletMode() {
802 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
803 "isInTabletMode()")) {
804 throw new SecurityException("Requires TABLET_MODE permission");
805 }
806 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
807 }
808
809 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100810 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100811 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100812 "registerTabletModeChangedListener()")) {
813 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
814 }
815 if (listener == null) {
816 throw new IllegalArgumentException("listener must not be null");
817 }
818
819 synchronized (mTabletModeLock) {
820 final int callingPid = Binder.getCallingPid();
821 if (mTabletModeChangedListeners.get(callingPid) != null) {
822 throw new IllegalStateException("The calling process has already registered "
823 + "a TabletModeChangedListener.");
824 }
825 TabletModeChangedListenerRecord record =
826 new TabletModeChangedListenerRecord(callingPid, listener);
827 try {
828 IBinder binder = listener.asBinder();
829 binder.linkToDeath(record, 0);
830 } catch (RemoteException ex) {
831 throw new RuntimeException(ex);
832 }
833 mTabletModeChangedListeners.put(callingPid, record);
834 }
835 }
836
837 private void onTabletModeChangedListenerDied(int pid) {
838 synchronized (mTabletModeLock) {
839 mTabletModeChangedListeners.remove(pid);
840 }
841 }
842
843 // Must be called on handler
844 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
845 mTempTabletModeChangedListenersToNotify.clear();
846 final int numListeners;
847 synchronized (mTabletModeLock) {
848 numListeners = mTabletModeChangedListeners.size();
849 for (int i = 0; i < numListeners; i++) {
850 mTempTabletModeChangedListenersToNotify.add(
851 mTabletModeChangedListeners.valueAt(i));
852 }
853 }
854 for (int i = 0; i < numListeners; i++) {
855 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
856 whenNanos, inTabletMode);
857 }
858 }
859
Jeff Browncf39bdf2012-05-18 14:41:19 -0700860 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700861 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700862 if (!mKeyboardLayoutNotificationShown) {
Michael Wrightc93fbd12014-09-22 20:07:59 -0700863 final Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
864 if (device != null) {
865 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700866 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700867 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
868 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
869 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
870 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
871 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700872
873 Resources r = mContext.getResources();
874 Notification notification = new Notification.Builder(mContext)
875 .setContentTitle(r.getString(
876 R.string.select_keyboard_layout_notification_title))
877 .setContentText(r.getString(
878 R.string.select_keyboard_layout_notification_message))
Michael Wrightc93fbd12014-09-22 20:07:59 -0700879 .setContentIntent(keyboardLayoutIntent)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700880 .setSmallIcon(R.drawable.ic_settings_language)
881 .setPriority(Notification.PRIORITY_LOW)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700882 .setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200883 com.android.internal.R.color.system_notification_accent_color))
Jeff Browncf39bdf2012-05-18 14:41:19 -0700884 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700885 mNotificationManager.notifyAsUser(null,
886 R.string.select_keyboard_layout_notification_title,
887 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700888 mKeyboardLayoutNotificationShown = true;
889 }
890 }
891
892 // Must be called on handler.
893 private void hideMissingKeyboardLayoutNotification() {
894 if (mKeyboardLayoutNotificationShown) {
895 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700896 mNotificationManager.cancelAsUser(null,
897 R.string.select_keyboard_layout_notification_title,
898 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700899 }
900 }
901
902 // Must be called on handler.
903 private void updateKeyboardLayouts() {
904 // Scan all input devices state for keyboard layouts that have been uninstalled.
905 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
906 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
907 @Override
Michael Wright8ebac232014-09-18 18:29:49 -0700908 public void visitKeyboardLayout(Resources resources, String descriptor, String label,
909 String collection, int keyboardLayoutResId, int priority) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700910 availableKeyboardLayouts.add(descriptor);
911 }
912 });
913 synchronized (mDataStore) {
914 try {
915 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
916 } finally {
917 mDataStore.saveIfNeeded();
918 }
919 }
920
921 // Reload keyboard layouts.
922 reloadKeyboardLayouts();
923 }
924
Jeff Browncf39bdf2012-05-18 14:41:19 -0700925 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
926 String descriptor) {
927 final int numDevices = inputDevices.length;
928 for (int i = 0; i < numDevices; i++) {
929 final InputDevice inputDevice = inputDevices[i];
930 if (inputDevice.getDescriptor().equals(descriptor)) {
931 return true;
932 }
933 }
934 return false;
Jeff Brown8d608662010-08-30 03:02:23 -0700935 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700936
937 @Override // Binder call
938 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700939 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
940 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
941 @Override
Michael Wright8ebac232014-09-18 18:29:49 -0700942 public void visitKeyboardLayout(Resources resources, String descriptor, String label,
943 String collection, int keyboardLayoutResId, int priority) {
944 list.add(new KeyboardLayout(descriptor, label, collection, priority));
Jeff Brown6ec6f792012-04-17 16:52:41 -0700945 }
946 });
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700947 return list.toArray(new KeyboardLayout[list.size()]);
948 }
949
950 @Override // Binder call
951 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
952 if (keyboardLayoutDescriptor == null) {
953 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
954 }
955
Jeff Brown6ec6f792012-04-17 16:52:41 -0700956 final KeyboardLayout[] result = new KeyboardLayout[1];
957 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
958 @Override
Michael Wright8ebac232014-09-18 18:29:49 -0700959 public void visitKeyboardLayout(Resources resources, String descriptor,
960 String label, String collection, int keyboardLayoutResId, int priority) {
961 result[0] = new KeyboardLayout(descriptor, label, collection, priority);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700962 }
963 });
964 if (result[0] == null) {
965 Log.w(TAG, "Could not get keyboard layout with descriptor '"
966 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700967 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700968 return result[0];
969 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700970
Jeff Brown6ec6f792012-04-17 16:52:41 -0700971 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700972 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700973 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
974 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
975 PackageManager.GET_META_DATA)) {
Michael Wright8ebac232014-09-18 18:29:49 -0700976 final ActivityInfo activityInfo = resolveInfo.activityInfo;
977 final int priority = resolveInfo.priority;
978 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700979 }
980 }
981
Jeff Brown6ec6f792012-04-17 16:52:41 -0700982 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
983 KeyboardLayoutVisitor visitor) {
984 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
985 if (d != null) {
986 final PackageManager pm = mContext.getPackageManager();
987 try {
988 ActivityInfo receiver = pm.getReceiverInfo(
989 new ComponentName(d.packageName, d.receiverName),
990 PackageManager.GET_META_DATA);
Michael Wright8ebac232014-09-18 18:29:49 -0700991 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700992 } catch (NameNotFoundException ex) {
993 }
994 }
995 }
996
997 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -0700998 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700999 Bundle metaData = receiver.metaData;
1000 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001001 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001002 }
1003
1004 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1005 if (configResId == 0) {
1006 Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
1007 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001008 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001009 }
1010
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001011 CharSequence receiverLabel = receiver.loadLabel(pm);
1012 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001013 int priority;
1014 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1015 priority = requestedPriority;
1016 } else {
1017 priority = 0;
1018 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001019
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001020 try {
1021 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1022 XmlResourceParser parser = resources.getXml(configResId);
1023 try {
1024 XmlUtils.beginDocument(parser, "keyboard-layouts");
1025
1026 for (;;) {
1027 XmlUtils.nextElement(parser);
1028 String element = parser.getName();
1029 if (element == null) {
1030 break;
1031 }
1032 if (element.equals("keyboard-layout")) {
1033 TypedArray a = resources.obtainAttributes(
1034 parser, com.android.internal.R.styleable.KeyboardLayout);
1035 try {
1036 String name = a.getString(
1037 com.android.internal.R.styleable.KeyboardLayout_name);
1038 String label = a.getString(
1039 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001040 int keyboardLayoutResId = a.getResourceId(
1041 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1042 0);
1043 if (name == null || label == null || keyboardLayoutResId == 0) {
1044 Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001045 + "attributes in keyboard layout "
1046 + "resource from receiver "
1047 + receiver.packageName + "/" + receiver.name);
1048 } else {
1049 String descriptor = KeyboardLayoutDescriptor.format(
1050 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001051 if (keyboardName == null || name.equals(keyboardName)) {
1052 visitor.visitKeyboardLayout(resources, descriptor,
Michael Wright8ebac232014-09-18 18:29:49 -07001053 label, collection, keyboardLayoutResId, priority);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001054 }
1055 }
1056 } finally {
1057 a.recycle();
1058 }
1059 } else {
1060 Log.w(TAG, "Skipping unrecognized element '" + element
1061 + "' in keyboard layout resource from receiver "
1062 + receiver.packageName + "/" + receiver.name);
1063 }
1064 }
1065 } finally {
1066 parser.close();
1067 }
1068 } catch (Exception ex) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001069 Log.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001070 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001071 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001072 }
1073
RoboErikfb290df2013-12-16 11:27:55 -08001074 /**
1075 * Builds a layout descriptor for the vendor/product. This returns the
1076 * descriptor for ids that aren't useful (such as the default 0, 0).
1077 */
1078 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1079 if (identifier == null || identifier.getDescriptor() == null) {
1080 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001081 }
1082
RoboErikfb290df2013-12-16 11:27:55 -08001083 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1084 return identifier.getDescriptor();
1085 }
1086 StringBuilder bob = new StringBuilder();
1087 bob.append("vendor:").append(identifier.getVendorId());
1088 bob.append(",product:").append(identifier.getProductId());
1089 return bob.toString();
1090 }
1091
1092 @Override // Binder call
1093 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1094
1095 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001096 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001097 String layout = null;
1098 // try loading it using the layout descriptor if we have it
1099 layout = mDataStore.getCurrentKeyboardLayout(key);
1100 if (layout == null && !key.equals(identifier.getDescriptor())) {
1101 // if it doesn't exist fall back to the device descriptor
1102 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1103 }
1104 if (DEBUG) {
1105 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1106 + layout);
1107 }
1108 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001109 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001110 }
1111
1112 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001113 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001114 String keyboardLayoutDescriptor) {
1115 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001116 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001117 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1118 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001119 if (keyboardLayoutDescriptor == null) {
1120 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1121 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001122
RoboErikfb290df2013-12-16 11:27:55 -08001123 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001124 synchronized (mDataStore) {
1125 try {
RoboErikfb290df2013-12-16 11:27:55 -08001126 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1127 if (DEBUG) {
1128 Slog.d(TAG, "Saved keyboard layout using " + key);
1129 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001130 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1131 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001132 } finally {
1133 mDataStore.saveIfNeeded();
1134 }
1135 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001136 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001137
Jeff Browncf39bdf2012-05-18 14:41:19 -07001138 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001139 public String[] getKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
1140 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001141 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001142 String[] layouts = mDataStore.getKeyboardLayouts(key);
1143 if ((layouts == null || layouts.length == 0)
1144 && !key.equals(identifier.getDescriptor())) {
1145 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1146 }
1147 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001148 }
1149 }
1150
1151 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001152 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001153 String keyboardLayoutDescriptor) {
1154 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1155 "addKeyboardLayoutForInputDevice()")) {
1156 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1157 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001158 if (keyboardLayoutDescriptor == null) {
1159 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1160 }
1161
RoboErikfb290df2013-12-16 11:27:55 -08001162 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001163 synchronized (mDataStore) {
1164 try {
RoboErikfb290df2013-12-16 11:27:55 -08001165 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1166 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1167 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1168 }
1169 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Jeff Browncf39bdf2012-05-18 14:41:19 -07001170 && !Objects.equal(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001171 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001172 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1173 }
1174 } finally {
1175 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001176 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001177 }
1178 }
1179
1180 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001181 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001182 String keyboardLayoutDescriptor) {
1183 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1184 "removeKeyboardLayoutForInputDevice()")) {
1185 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1186 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001187 if (keyboardLayoutDescriptor == null) {
1188 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1189 }
1190
RoboErikfb290df2013-12-16 11:27:55 -08001191 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001192 synchronized (mDataStore) {
1193 try {
RoboErikfb290df2013-12-16 11:27:55 -08001194 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1195 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1196 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1197 }
1198 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1199 if (!key.equals(identifier.getDescriptor())) {
1200 // We need to remove from both places to ensure it is gone
1201 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1202 keyboardLayoutDescriptor);
1203 }
1204 if (removed && !Objects.equal(oldLayout,
1205 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001206 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1207 }
1208 } finally {
1209 mDataStore.saveIfNeeded();
1210 }
1211 }
1212 }
1213
Yohei Yukawab097b822015-12-01 10:43:08 -08001214 // Must be called on handler.
1215 private void handleSwitchInputMethodSubtype(int userId,
1216 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1217 if (DEBUG) {
1218 Slog.i(TAG, "InputMethodSubtype changed: userId=" + userId
1219 + " ime=" + inputMethodInfo + " subtype=" + subtype);
1220 }
1221 }
1222
Jeff Browncf39bdf2012-05-18 14:41:19 -07001223 public void switchKeyboardLayout(int deviceId, int direction) {
1224 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
1225 }
1226
1227 // Must be called on handler.
1228 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1229 final InputDevice device = getInputDevice(deviceId);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001230 if (device != null) {
1231 final boolean changed;
1232 final String keyboardLayoutDescriptor;
RoboErikfb290df2013-12-16 11:27:55 -08001233
1234 String key = getLayoutDescriptor(device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001235 synchronized (mDataStore) {
1236 try {
RoboErikfb290df2013-12-16 11:27:55 -08001237 changed = mDataStore.switchKeyboardLayout(key, direction);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001238 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
RoboErikfb290df2013-12-16 11:27:55 -08001239 key);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001240 } finally {
1241 mDataStore.saveIfNeeded();
1242 }
1243 }
1244
1245 if (changed) {
1246 if (mSwitchedKeyboardLayoutToast != null) {
1247 mSwitchedKeyboardLayoutToast.cancel();
1248 mSwitchedKeyboardLayoutToast = null;
1249 }
1250 if (keyboardLayoutDescriptor != null) {
1251 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1252 if (keyboardLayout != null) {
1253 mSwitchedKeyboardLayoutToast = Toast.makeText(
1254 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1255 mSwitchedKeyboardLayoutToast.show();
1256 }
1257 }
1258
1259 reloadKeyboardLayouts();
1260 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001261 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001262 }
1263
Jeff Brown9302c872011-07-13 22:51:29 -07001264 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001265 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001266 }
RoboErikfb290df2013-12-16 11:27:55 -08001267
Jeff Brown9302c872011-07-13 22:51:29 -07001268 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001269 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001270 }
RoboErikfb290df2013-12-16 11:27:55 -08001271
Jeff Brown349703e2010-06-22 01:27:15 -07001272 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001273 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001274 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001275
1276 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001277 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001278 }
1279
Jeff Browne6504122010-09-27 14:52:15 -07001280 /**
1281 * Atomically transfers touch focus from one window to another as identified by
1282 * their input channels. It is possible for multiple windows to have
1283 * touch focus if they support split touch dispatch
1284 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1285 * method only transfers touch focus of the specified window without affecting
1286 * other windows that may also have touch focus at the same time.
1287 * @param fromChannel The channel of a window that currently has touch focus.
1288 * @param toChannel The channel of the window that should receive touch focus in
1289 * place of the first.
1290 * @return True if the transfer was successful. False if the window with the
1291 * specified channel did not actually have touch focus at the time of the request.
1292 */
1293 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1294 if (fromChannel == null) {
1295 throw new IllegalArgumentException("fromChannel must not be null.");
1296 }
1297 if (toChannel == null) {
1298 throw new IllegalArgumentException("toChannel must not be null.");
1299 }
Jeff Brown4532e612012-04-05 14:27:12 -07001300 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001301 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001302
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001303 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001304 public void tryPointerSpeed(int speed) {
1305 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1306 "tryPointerSpeed()")) {
1307 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1308 }
1309
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001310 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1311 throw new IllegalArgumentException("speed out of range");
1312 }
1313
Jeff Brownac143512012-04-05 18:57:33 -07001314 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001315 }
1316
1317 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001318 int speed = getPointerSpeedSetting();
1319 setPointerSpeedUnchecked(speed);
1320 }
1321
1322 private void setPointerSpeedUnchecked(int speed) {
1323 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1324 InputManager.MAX_POINTER_SPEED);
1325 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001326 }
1327
1328 private void registerPointerSpeedSettingObserver() {
1329 mContext.getContentResolver().registerContentObserver(
1330 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001331 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001332 @Override
1333 public void onChange(boolean selfChange) {
1334 updatePointerSpeedFromSettings();
1335 }
Jeff Brownd4935962012-09-25 13:27:20 -07001336 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001337 }
1338
Jeff Brownac143512012-04-05 18:57:33 -07001339 private int getPointerSpeedSetting() {
1340 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001341 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001342 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1343 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001344 } catch (SettingNotFoundException snfe) {
1345 }
1346 return speed;
1347 }
1348
Jeff Browndaf4a122011-08-26 17:14:14 -07001349 public void updateShowTouchesFromSettings() {
1350 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001351 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001352 }
1353
1354 private void registerShowTouchesSettingObserver() {
1355 mContext.getContentResolver().registerContentObserver(
1356 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001357 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001358 @Override
1359 public void onChange(boolean selfChange) {
1360 updateShowTouchesFromSettings();
1361 }
Jeff Brownd4935962012-09-25 13:27:20 -07001362 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001363 }
1364
1365 private int getShowTouchesSetting(int defaultValue) {
1366 int result = defaultValue;
1367 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001368 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1369 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001370 } catch (SettingNotFoundException snfe) {
1371 }
1372 return result;
1373 }
1374
Jeff Browna47425a2012-04-13 04:09:27 -07001375 // Binder call
1376 @Override
1377 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1378 if (repeat >= pattern.length) {
1379 throw new ArrayIndexOutOfBoundsException();
1380 }
1381
1382 VibratorToken v;
1383 synchronized (mVibratorLock) {
1384 v = mVibratorTokens.get(token);
1385 if (v == null) {
1386 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1387 try {
1388 token.linkToDeath(v, 0);
1389 } catch (RemoteException ex) {
1390 // give up
1391 throw new RuntimeException(ex);
1392 }
1393 mVibratorTokens.put(token, v);
1394 }
1395 }
1396
1397 synchronized (v) {
1398 v.mVibrating = true;
1399 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1400 }
1401 }
1402
1403 // Binder call
1404 @Override
1405 public void cancelVibrate(int deviceId, IBinder token) {
1406 VibratorToken v;
1407 synchronized (mVibratorLock) {
1408 v = mVibratorTokens.get(token);
1409 if (v == null || v.mDeviceId != deviceId) {
1410 return; // nothing to cancel
1411 }
1412 }
1413
1414 cancelVibrateIfNeeded(v);
1415 }
1416
1417 void onVibratorTokenDied(VibratorToken v) {
1418 synchronized (mVibratorLock) {
1419 mVibratorTokens.remove(v.mToken);
1420 }
1421
1422 cancelVibrateIfNeeded(v);
1423 }
1424
1425 private void cancelVibrateIfNeeded(VibratorToken v) {
1426 synchronized (v) {
1427 if (v.mVibrating) {
1428 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1429 v.mVibrating = false;
1430 }
1431 }
1432 }
1433
Jun Mukai1db53972015-09-11 18:08:31 -07001434 // Binder call
1435 @Override
1436 public void setPointerIconShape(int iconId) {
1437 nativeSetPointerIconShape(mPtr, iconId);
1438 }
1439
Jeff Brown4532e612012-04-05 14:27:12 -07001440 @Override
1441 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001442 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001443 != PackageManager.PERMISSION_GRANTED) {
1444 pw.println("Permission Denial: can't dump InputManager from from pid="
1445 + Binder.getCallingPid()
1446 + ", uid=" + Binder.getCallingUid());
1447 return;
1448 }
1449
1450 pw.println("INPUT MANAGER (dumpsys input)\n");
1451 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001452 if (dumpStr != null) {
1453 pw.println(dumpStr);
1454 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001455 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001456
Jeff Brownac143512012-04-05 18:57:33 -07001457 private boolean checkCallingPermission(String permission, String func) {
1458 // Quick check: if the calling permission is me, it's all okay.
1459 if (Binder.getCallingPid() == Process.myPid()) {
1460 return true;
1461 }
1462
1463 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1464 return true;
1465 }
1466 String msg = "Permission Denial: " + func + " from pid="
1467 + Binder.getCallingPid()
1468 + ", uid=" + Binder.getCallingUid()
1469 + " requires " + permission;
1470 Slog.w(TAG, msg);
1471 return false;
1472 }
1473
Jeff Brown4532e612012-04-05 14:27:12 -07001474 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001475 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001476 public void monitor() {
1477 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001478 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001479 }
1480
Jeff Brown4532e612012-04-05 14:27:12 -07001481 // Native callback.
1482 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001483 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001484 }
1485
1486 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001487 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1488 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001489 if (!mInputDevicesChangedPending) {
1490 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001491 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1492 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001493 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001494
1495 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001496 }
1497 }
1498
1499 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001500 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1501 if (DEBUG) {
1502 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1503 + ", mask=" + Integer.toHexString(switchMask));
1504 }
1505
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001506 if ((switchMask & SW_LID_BIT) != 0) {
1507 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001508 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001509 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001510
Michael Wright3818c922014-09-02 13:59:07 -07001511 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001512 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001513 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1514 }
1515
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001516 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1517 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1518 switchMask);
1519 }
Michael Wright39e5e942015-08-19 22:52:47 +01001520
Michael Wright9209c9c2015-09-03 17:57:01 +01001521 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001522 SomeArgs args = SomeArgs.obtain();
1523 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1524 args.argi2 = (int) (whenNanos >> 32);
1525 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1526 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1527 args).sendToTarget();
1528 }
Jeff Brown4532e612012-04-05 14:27:12 -07001529 }
1530
1531 // Native callback.
1532 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001533 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001534 }
1535
1536 // Native callback.
1537 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001538 InputWindowHandle inputWindowHandle, String reason) {
1539 return mWindowManagerCallbacks.notifyANR(
1540 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001541 }
1542
1543 // Native callback.
1544 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1545 synchronized (mInputFilterLock) {
1546 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001547 try {
1548 mInputFilter.filterInputEvent(event, policyFlags);
1549 } catch (RemoteException e) {
1550 /* ignore */
1551 }
Jeff Brown4532e612012-04-05 14:27:12 -07001552 return false;
1553 }
1554 }
1555 event.recycle();
1556 return true;
1557 }
1558
1559 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001560 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1561 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001562 }
1563
1564 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001565 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1566 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001567 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001568 }
1569
1570 // Native callback.
1571 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1572 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001573 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001574 }
1575
1576 // Native callback.
1577 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1578 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001579 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001580 }
1581
1582 // Native callback.
1583 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1584 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1585 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1586 }
1587
1588 // Native callback.
1589 private int getVirtualKeyQuietTimeMillis() {
1590 return mContext.getResources().getInteger(
1591 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1592 }
1593
1594 // Native callback.
1595 private String[] getExcludedDeviceNames() {
1596 ArrayList<String> names = new ArrayList<String>();
1597
1598 // Read partner-provided list of excluded input devices
1599 XmlPullParser parser = null;
1600 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1601 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1602 FileReader confreader = null;
1603 try {
1604 confreader = new FileReader(confFile);
1605 parser = Xml.newPullParser();
1606 parser.setInput(confreader);
1607 XmlUtils.beginDocument(parser, "devices");
1608
1609 while (true) {
1610 XmlUtils.nextElement(parser);
1611 if (!"device".equals(parser.getName())) {
1612 break;
1613 }
1614 String name = parser.getAttributeValue(null, "name");
1615 if (name != null) {
1616 names.add(name);
1617 }
1618 }
1619 } catch (FileNotFoundException e) {
1620 // It's ok if the file does not exist.
1621 } catch (Exception e) {
1622 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1623 } finally {
1624 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1625 }
1626
1627 return names.toArray(new String[names.size()]);
1628 }
1629
1630 // Native callback.
1631 private int getKeyRepeatTimeout() {
1632 return ViewConfiguration.getKeyRepeatTimeout();
1633 }
1634
1635 // Native callback.
1636 private int getKeyRepeatDelay() {
1637 return ViewConfiguration.getKeyRepeatDelay();
1638 }
1639
1640 // Native callback.
1641 private int getHoverTapTimeout() {
1642 return ViewConfiguration.getHoverTapTimeout();
1643 }
1644
1645 // Native callback.
1646 private int getHoverTapSlop() {
1647 return ViewConfiguration.getHoverTapSlop();
1648 }
1649
1650 // Native callback.
1651 private int getDoubleTapTimeout() {
1652 return ViewConfiguration.getDoubleTapTimeout();
1653 }
1654
1655 // Native callback.
1656 private int getLongPressTimeout() {
1657 return ViewConfiguration.getLongPressTimeout();
1658 }
1659
1660 // Native callback.
1661 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001662 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001663 }
1664
1665 // Native callback.
1666 private PointerIcon getPointerIcon() {
1667 return PointerIcon.getDefaultIcon(mContext);
1668 }
1669
Jeff Brown6ec6f792012-04-17 16:52:41 -07001670 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001671 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001672 if (!mSystemReady) {
1673 return null;
1674 }
1675
RoboErikfb290df2013-12-16 11:27:55 -08001676 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001677 if (keyboardLayoutDescriptor == null) {
1678 return null;
1679 }
1680
1681 final String[] result = new String[2];
1682 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1683 @Override
Michael Wright8ebac232014-09-18 18:29:49 -07001684 public void visitKeyboardLayout(Resources resources, String descriptor, String label,
1685 String collection, int keyboardLayoutResId, int priority) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001686 try {
1687 result[0] = descriptor;
1688 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001689 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001690 } catch (IOException ex) {
1691 } catch (NotFoundException ex) {
1692 }
1693 }
1694 });
1695 if (result[0] == null) {
1696 Log.w(TAG, "Could not get keyboard layout with descriptor '"
1697 + keyboardLayoutDescriptor + "'.");
1698 return null;
1699 }
1700 return result;
1701 }
1702
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001703 // Native callback.
1704 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001705 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1706 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1707 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001708 }
1709 return null;
1710 }
1711
Jeff Brown4532e612012-04-05 14:27:12 -07001712 /**
1713 * Callback interface implemented by the Window Manager.
1714 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001715 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001716 public void notifyConfigurationChanged();
1717
1718 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1719
Michael Wright3818c922014-09-02 13:59:07 -07001720 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
1721
Jeff Brown4532e612012-04-05 14:27:12 -07001722 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1723
1724 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001725 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001726
Jeff Brown037c33e2014-04-09 00:31:55 -07001727 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001728
Michael Wright70af00a2014-09-03 19:30:20 -07001729 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001730
1731 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1732 KeyEvent event, int policyFlags);
1733
1734 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1735 KeyEvent event, int policyFlags);
1736
1737 public int getPointerLayer();
1738 }
1739
1740 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001741 * Callback interface implemented by WiredAccessoryObserver.
1742 */
1743 public interface WiredAccessoryCallbacks {
1744 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07001745 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001746 }
1747
1748 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001749 * Private handler for the input manager.
1750 */
1751 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07001752 public InputManagerHandler(Looper looper) {
1753 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07001754 }
1755
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001756 @Override
1757 public void handleMessage(Message msg) {
1758 switch (msg.what) {
1759 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07001760 deliverInputDevicesChanged((InputDevice[])msg.obj);
1761 break;
1762 case MSG_SWITCH_KEYBOARD_LAYOUT:
1763 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
1764 break;
1765 case MSG_RELOAD_KEYBOARD_LAYOUTS:
1766 reloadKeyboardLayouts();
1767 break;
1768 case MSG_UPDATE_KEYBOARD_LAYOUTS:
1769 updateKeyboardLayouts();
1770 break;
1771 case MSG_RELOAD_DEVICE_ALIASES:
1772 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001773 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08001774 case MSG_DELIVER_TABLET_MODE_CHANGED: {
Michael Wright39e5e942015-08-19 22:52:47 +01001775 SomeArgs args = (SomeArgs) msg.obj;
1776 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
1777 boolean inTabletMode = (boolean) args.arg1;
1778 deliverTabletModeChanged(whenNanos, inTabletMode);
1779 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08001780 }
1781 case MSG_INPUT_METHOD_SUBTYPE_CHANGED: {
1782 final int userId = msg.arg1;
1783 final SomeArgs args = (SomeArgs) msg.obj;
1784 final InputMethodInfo inputMethodInfo = (InputMethodInfo) args.arg1;
1785 final InputMethodSubtype subtype = (InputMethodSubtype) args.arg2;
1786 args.recycle();
1787 handleSwitchInputMethodSubtype(userId, inputMethodInfo, subtype);
1788 break;
1789 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001790 }
1791 }
1792 }
1793
1794 /**
Jeff Brown4532e612012-04-05 14:27:12 -07001795 * Hosting interface for input filters to call back into the input manager.
1796 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001797 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07001798 private boolean mDisconnected;
1799
1800 public void disconnectLocked() {
1801 mDisconnected = true;
1802 }
1803
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001804 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07001805 public void sendInputEvent(InputEvent event, int policyFlags) {
1806 if (event == null) {
1807 throw new IllegalArgumentException("event must not be null");
1808 }
1809
1810 synchronized (mInputFilterLock) {
1811 if (!mDisconnected) {
Jeff Brownca9bc702014-02-11 14:32:56 -08001812 nativeInjectInputEvent(mPtr, event, Display.DEFAULT_DISPLAY, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07001813 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07001814 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
1815 }
1816 }
1817 }
1818 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001819
1820 private static final class KeyboardLayoutDescriptor {
1821 public String packageName;
1822 public String receiverName;
1823 public String keyboardLayoutName;
1824
1825 public static String format(String packageName,
1826 String receiverName, String keyboardName) {
1827 return packageName + "/" + receiverName + "/" + keyboardName;
1828 }
1829
1830 public static KeyboardLayoutDescriptor parse(String descriptor) {
1831 int pos = descriptor.indexOf('/');
1832 if (pos < 0 || pos + 1 == descriptor.length()) {
1833 return null;
1834 }
1835 int pos2 = descriptor.indexOf('/', pos + 1);
1836 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
1837 return null;
1838 }
1839
1840 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
1841 result.packageName = descriptor.substring(0, pos);
1842 result.receiverName = descriptor.substring(pos + 1, pos2);
1843 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
1844 return result;
1845 }
1846 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001847
Jeff Brown6ec6f792012-04-17 16:52:41 -07001848 private interface KeyboardLayoutVisitor {
Michael Wright8ebac232014-09-18 18:29:49 -07001849 void visitKeyboardLayout(Resources resources, String descriptor, String label,
1850 String collection, int keyboardLayoutResId, int priority);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001851 }
1852
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001853 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
1854 private final int mPid;
1855 private final IInputDevicesChangedListener mListener;
1856
1857 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
1858 mPid = pid;
1859 mListener = listener;
1860 }
1861
1862 @Override
1863 public void binderDied() {
1864 if (DEBUG) {
1865 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
1866 }
1867 onInputDevicesChangedListenerDied(mPid);
1868 }
1869
1870 public void notifyInputDevicesChanged(int[] info) {
1871 try {
1872 mListener.onInputDevicesChanged(info);
1873 } catch (RemoteException ex) {
1874 Slog.w(TAG, "Failed to notify process "
1875 + mPid + " that input devices changed, assuming it died.", ex);
1876 binderDied();
1877 }
1878 }
1879 }
Jeff Browna47425a2012-04-13 04:09:27 -07001880
Michael Wright39e5e942015-08-19 22:52:47 +01001881 private final class TabletModeChangedListenerRecord implements DeathRecipient {
1882 private final int mPid;
1883 private final ITabletModeChangedListener mListener;
1884
1885 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
1886 mPid = pid;
1887 mListener = listener;
1888 }
1889
1890 @Override
1891 public void binderDied() {
1892 if (DEBUG) {
1893 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
1894 }
1895 onTabletModeChangedListenerDied(mPid);
1896 }
1897
1898 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
1899 try {
1900 mListener.onTabletModeChanged(whenNanos, inTabletMode);
1901 } catch (RemoteException ex) {
1902 Slog.w(TAG, "Failed to notify process " + mPid +
1903 " that tablet mode changed, assuming it died.", ex);
1904 binderDied();
1905 }
1906 }
1907 }
1908
Jeff Browna47425a2012-04-13 04:09:27 -07001909 private final class VibratorToken implements DeathRecipient {
1910 public final int mDeviceId;
1911 public final IBinder mToken;
1912 public final int mTokenValue;
1913
1914 public boolean mVibrating;
1915
1916 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
1917 mDeviceId = deviceId;
1918 mToken = token;
1919 mTokenValue = tokenValue;
1920 }
1921
1922 @Override
1923 public void binderDied() {
1924 if (DEBUG) {
1925 Slog.d(TAG, "Vibrator token died.");
1926 }
1927 onVibratorTokenDied(this);
1928 }
1929 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08001930
1931 private final class LocalService extends InputManagerInternal {
1932 @Override
1933 public void setDisplayViewports(
1934 DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
1935 setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
1936 }
Jeff Brownca9bc702014-02-11 14:32:56 -08001937
1938 @Override
1939 public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
1940 return injectInputEventInternal(event, displayId, mode);
1941 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001942
1943 @Override
1944 public void setInteractive(boolean interactive) {
1945 nativeSetInteractive(mPtr, interactive);
1946 }
Yohei Yukawab097b822015-12-01 10:43:08 -08001947
1948 @Override
1949 public void onInputMethodSubtypeChanged(int userId,
1950 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1951 final SomeArgs someArgs = SomeArgs.obtain();
1952 someArgs.arg1 = inputMethodInfo;
1953 someArgs.arg2 = subtype;
1954 mHandler.obtainMessage(MSG_INPUT_METHOD_SUBTYPE_CHANGED, userId, 0, someArgs)
1955 .sendToTarget();
1956 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08001957 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001958}