blob: 490764f24764af1812278dd7ac1e3e756565c754 [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 Yukawa5660fad2016-01-27 22:04:09 -080019import android.annotation.NonNull;
Yohei Yukawab097b822015-12-01 10:43:08 -080020import android.annotation.Nullable;
Yohei Yukawa5660fad2016-01-27 22:04:09 -080021import android.util.LocaleList;
Jeff Brownca9bc702014-02-11 14:32:56 -080022import android.view.Display;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080023import com.android.internal.inputmethod.InputMethodSubtypeHandle;
Michael Wright39e5e942015-08-19 22:52:47 +010024import com.android.internal.os.SomeArgs;
Jeff Browncf39bdf2012-05-18 14:41:19 -070025import com.android.internal.R;
Jeff Brown46b9ac02010-04-22 18:58:52 -070026import com.android.internal.util.XmlUtils;
Jeff Brown4ccb8232014-01-16 22:16:42 -080027import com.android.server.DisplayThread;
28import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070029import com.android.server.Watchdog;
Jeff Brown46b9ac02010-04-22 18:58:52 -070030
31import org.xmlpull.v1.XmlPullParser;
32
Jeff Browna3bc5652012-04-17 11:42:25 -070033import android.Manifest;
Jeff Browncf39bdf2012-05-18 14:41:19 -070034import android.app.Notification;
35import android.app.NotificationManager;
36import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070037import android.bluetooth.BluetoothAdapter;
38import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070039import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070040import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070041import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070042import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070043import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070044import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070045import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070046import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070047import android.content.pm.ResolveInfo;
48import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070050import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070051import android.content.res.TypedArray;
52import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070053import android.database.ContentObserver;
Jeff Brown4ccb8232014-01-16 22:16:42 -080054import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070056import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080057import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070058import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080059import android.hardware.input.InputManagerInternal;
Michael Wright39e5e942015-08-19 22:52:47 +010060import android.hardware.input.ITabletModeChangedListener;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070061import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080062import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070063import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070064import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070065import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070066import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070067import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070068import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080070import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070071import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070072import android.os.RemoteException;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080073import android.os.ResultReceiver;
74import android.os.ShellCommand;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070075import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070076import android.provider.Settings;
77import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000078import android.text.TextUtils;
Jeff Brown46b9ac02010-04-22 18:58:52 -070079import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070080import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070081import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070082import android.view.IInputFilter;
83import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070084import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070085import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070086import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080087import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070088import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070089import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080090import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070091import android.view.WindowManagerPolicy;
Yohei Yukawab097b822015-12-01 10:43:08 -080092import android.view.inputmethod.InputMethod;
93import android.view.inputmethod.InputMethodInfo;
94import android.view.inputmethod.InputMethodSubtype;
Jeff Browncf39bdf2012-05-18 14:41:19 -070095import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070096
Jeff Brown46b9ac02010-04-22 18:58:52 -070097import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -070098import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -070099import java.io.FileNotFoundException;
100import java.io.FileReader;
101import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700102import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700103import java.io.PrintWriter;
104import java.util.ArrayList;
Michael Wrightd5f7ed92016-01-19 11:23:51 -0800105import java.util.Arrays;
Michael Wright07483422015-10-30 16:20:13 +0000106import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700107import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700108import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100109import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000110import java.util.Locale;
Jeff Browna3bc5652012-04-17 11:42:25 -0700111
Jeff Brown6ec6f792012-04-17 16:52:41 -0700112import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -0700113import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700114
115/*
116 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700117 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700118public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800119 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700120 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700121 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700122
Jeff Brown4532e612012-04-05 14:27:12 -0700123 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
124
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700125 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700126 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
127 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
128 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
129 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100130 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Yohei Yukawab097b822015-12-01 10:43:08 -0800131 private static final int MSG_INPUT_METHOD_SUBTYPE_CHANGED = 7;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132
Jeff Brown4532e612012-04-05 14:27:12 -0700133 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000134 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700135
Jeff Brown46b9ac02010-04-22 18:58:52 -0700136 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700138
139 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700140 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700141 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700142 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700143
Michael Wright39e5e942015-08-19 22:52:47 +0100144 private final Object mTabletModeLock = new Object();
145 // List of currently registered tablet mode changed listeners by process id
146 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
147 new SparseArray<>(); // guarded by mTabletModeLock
148 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
149 new ArrayList<>();
150
Jeff Browna3bc5652012-04-17 11:42:25 -0700151 // Persistent data store. Must be locked each time during use.
152 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700153
154 // List of currently registered input devices changed listeners by process id.
155 private Object mInputDevicesLock = new Object();
156 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
157 private InputDevice[] mInputDevices = new InputDevice[0];
158 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
159 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
160 private final ArrayList<InputDevicesChangedListenerRecord>
161 mTempInputDevicesChangedListenersToNotify =
162 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700163 private final ArrayList<InputDevice>
164 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
165 private boolean mKeyboardLayoutNotificationShown;
Michael Wrightd5f7ed92016-01-19 11:23:51 -0800166 private InputMethodSubtypeHandle mCurrentImeHandle;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700167
Jeff Browna47425a2012-04-13 04:09:27 -0700168 // State for vibrator tokens.
169 private Object mVibratorLock = new Object();
170 private HashMap<IBinder, VibratorToken> mVibratorTokens =
171 new HashMap<IBinder, VibratorToken>();
172 private int mNextVibratorTokenValue;
173
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700174 // State for the currently installed input filter.
175 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700176 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700178
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000179 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700180 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000181 private static native void nativeStart(long ptr);
182 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700183 int displayId, int rotation,
184 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700185 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
186 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700187
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000188 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700189 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000190 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700191 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000192 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700193 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000194 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700195 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800197 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
199 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Jeff Brownca9bc702014-02-11 14:32:56 -0800200 private static native int nativeInjectInputEvent(long ptr, InputEvent event, int displayId,
Jeff Brown0029c662011-03-30 02:25:18 -0700201 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
202 int policyFlags);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000203 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
204 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
205 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
206 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700207 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000208 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700209 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000210 private static native void nativeSetPointerSpeed(long ptr, int speed);
211 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700212 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800213 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000214 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700215 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000216 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
217 private static native void nativeReloadKeyboardLayouts(long ptr);
218 private static native void nativeReloadDeviceAliases(long ptr);
219 private static native String nativeDump(long ptr);
220 private static native void nativeMonitor(long ptr);
Jun Mukai1db53972015-09-11 18:08:31 -0700221 private static native void nativeSetPointerIconShape(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800222 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700223 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Jun Mukai347e5d42015-12-03 01:13:31 -0800224 private static native void nativeSetPointerIconDetached(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700225
Jeff Brownac143512012-04-05 18:57:33 -0700226 // Input event injection constants defined in InputDispatcher.h.
227 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
228 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
229 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
230 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
231
232 // Maximum number of milliseconds to wait for input event injection.
233 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
234
Jeff Brown6d0fec22010-07-23 21:28:06 -0700235 // Key states (may be returned by queries about the current state of a
236 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700237
Jeff Brown6d0fec22010-07-23 21:28:06 -0700238 /** The key state is unknown or the requested key itself is not supported. */
239 public static final int KEY_STATE_UNKNOWN = -1;
240
241 /** The key is up. /*/
242 public static final int KEY_STATE_UP = 0;
243
244 /** The key is down. */
245 public static final int KEY_STATE_DOWN = 1;
246
247 /** The key is down but is a virtual key press that is being emulated by the system. */
248 public static final int KEY_STATE_VIRTUAL = 2;
249
Jeff Brownc458ce92012-04-30 14:58:40 -0700250 /** Scan code: Mouse / trackball button. */
251 public static final int BTN_MOUSE = 0x110;
252
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700253 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700254 /** Switch code: Lid switch. When set, lid is shut. */
255 public static final int SW_LID = 0x00;
256
Michael Wright39e5e942015-08-19 22:52:47 +0100257 /** Switch code: Tablet mode switch.
258 * When set, the device is in tablet mode (i.e. no keyboard is connected).
259 */
260 public static final int SW_TABLET_MODE = 0x01;
261
Jeff Brownc458ce92012-04-30 14:58:40 -0700262 /** Switch code: Keypad slide. When set, keyboard is exposed. */
263 public static final int SW_KEYPAD_SLIDE = 0x0a;
264
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700265 /** Switch code: Headphone. When set, headphone is inserted. */
266 public static final int SW_HEADPHONE_INSERT = 0x02;
267
268 /** Switch code: Microphone. When set, microphone is inserted. */
269 public static final int SW_MICROPHONE_INSERT = 0x04;
270
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500271 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
272 public static final int SW_LINEOUT_INSERT = 0x06;
273
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700274 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
275 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
276
Michael Wright3818c922014-09-02 13:59:07 -0700277 /** Switch code: Camera lens cover. When set the lens is covered. */
278 public static final int SW_CAMERA_LENS_COVER = 0x09;
279
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700280 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100281 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700282 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
283 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
284 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500285 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700286 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
287 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500288 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700289 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700290
291 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
292 final boolean mUseDevInputEventForAudioJack;
293
Jeff Brown4ccb8232014-01-16 22:16:42 -0800294 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700295 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800296 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800297
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700298 mUseDevInputEventForAudioJack =
299 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
300 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
301 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700302 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800303
304 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700305 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700306
Jeff Browna9d131c2012-09-20 16:48:17 -0700307 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
308 mWindowManagerCallbacks = callbacks;
309 }
310
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700311 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
312 mWiredAccessoryCallbacks = callbacks;
313 }
314
Jeff Brown46b9ac02010-04-22 18:58:52 -0700315 public void start() {
316 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700317 nativeStart(mPtr);
318
319 // Add ourself to the Watchdog monitors.
320 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700321
322 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700323 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800324 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700325
Jeff Brownd4935962012-09-25 13:27:20 -0700326 mContext.registerReceiver(new BroadcastReceiver() {
327 @Override
328 public void onReceive(Context context, Intent intent) {
329 updatePointerSpeedFromSettings();
330 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800331 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700332 }
333 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
334
Jeff Brown1a84fd12011-06-02 01:26:32 -0700335 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700336 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800337 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700338 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700339
Matthew Xie96313142012-06-29 16:57:31 -0700340 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700341 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700342 if (DEBUG) {
343 Slog.d(TAG, "System ready.");
344 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700345 mNotificationManager = (NotificationManager)mContext.getSystemService(
346 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700347 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700348
349 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
350 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
351 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800352 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700353 filter.addDataScheme("package");
354 mContext.registerReceiver(new BroadcastReceiver() {
355 @Override
356 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700357 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700358 }
359 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700360
361 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
362 mContext.registerReceiver(new BroadcastReceiver() {
363 @Override
364 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700365 reloadDeviceAliases();
366 }
367 }, filter, null, mHandler);
368
Jeff Browncf39bdf2012-05-18 14:41:19 -0700369 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
370 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700371
372 if (mWiredAccessoryCallbacks != null) {
373 mWiredAccessoryCallbacks.systemReady();
374 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700375 }
376
377 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700378 if (DEBUG) {
379 Slog.d(TAG, "Reloading keyboard layouts.");
380 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700381 nativeReloadKeyboardLayouts(mPtr);
382 }
383
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700384 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700385 if (DEBUG) {
386 Slog.d(TAG, "Reloading device names.");
387 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700388 nativeReloadDeviceAliases(mPtr);
389 }
390
Jeff Brown4ccb8232014-01-16 22:16:42 -0800391 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Jeff Brownd728bf52012-09-08 18:05:28 -0700392 DisplayViewport externalTouchViewport) {
393 if (defaultViewport.valid) {
394 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700395 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700396
397 if (externalTouchViewport.valid) {
398 setDisplayViewport(true, externalTouchViewport);
399 } else if (defaultViewport.valid) {
400 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700401 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700402 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700403
Jeff Brownd728bf52012-09-08 18:05:28 -0700404 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
405 nativeSetDisplayViewport(mPtr, external,
406 viewport.displayId, viewport.orientation,
407 viewport.logicalFrame.left, viewport.logicalFrame.top,
408 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
409 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700410 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
411 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700412 }
Jeff Brownac143512012-04-05 18:57:33 -0700413
Jeff Brown6d0fec22010-07-23 21:28:06 -0700414 /**
415 * Gets the current state of a key or button by key 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 keyCode The key code to check.
421 * @return The key state.
422 */
423 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700424 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700426
Jeff Brown6d0fec22010-07-23 21:28:06 -0700427 /**
428 * Gets the current state of a key or button by scan 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 scanCode The scan code to check.
434 * @return The key state.
435 */
436 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700437 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700438 }
RoboErikfb290df2013-12-16 11:27:55 -0800439
Jeff Brown6d0fec22010-07-23 21:28:06 -0700440 /**
441 * Gets the current state of a switch by switch code.
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 switchCode The switch code to check.
447 * @return The switch state.
448 */
449 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700450 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700451 }
452
Jeff Brown6d0fec22010-07-23 21:28:06 -0700453 /**
454 * Determines whether the specified key codes are supported by a particular device.
455 * @param deviceId The input device id, or -1 to consult all devices.
456 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
457 * consider all input sources. An input device is consulted if at least one of its
458 * non-class input source bits matches the specified source mask.
459 * @param keyCodes The array of key codes to check.
460 * @param keyExists An array at least as large as keyCodes whose entries will be set
461 * to true or false based on the presence or absence of support for the corresponding
462 * key codes.
463 * @return True if the lookup was successful, false otherwise.
464 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700465 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700466 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700467 if (keyCodes == null) {
468 throw new IllegalArgumentException("keyCodes must not be null.");
469 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700470 if (keyExists == null || keyExists.length < keyCodes.length) {
471 throw new IllegalArgumentException("keyExists must not be null and must be at "
472 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700473 }
RoboErikfb290df2013-12-16 11:27:55 -0800474
Jeff Brown4532e612012-04-05 14:27:12 -0700475 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700476 }
RoboErikfb290df2013-12-16 11:27:55 -0800477
Jeff Browna41ca772010-08-11 14:46:32 -0700478 /**
479 * Creates an input channel that will receive all input from the input dispatcher.
480 * @param inputChannelName The input channel name.
481 * @return The input channel.
482 */
483 public InputChannel monitorInput(String inputChannelName) {
484 if (inputChannelName == null) {
485 throw new IllegalArgumentException("inputChannelName must not be null.");
486 }
RoboErikfb290df2013-12-16 11:27:55 -0800487
Jeff Browna41ca772010-08-11 14:46:32 -0700488 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700489 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700490 inputChannels[0].dispose(); // don't need to retain the Java object reference
491 return inputChannels[1];
492 }
493
494 /**
495 * Registers an input channel so that it can be used as an input event target.
496 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800497 * @param inputWindowHandle The handle of the input window associated with the
498 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700499 */
Jeff Brown928e0542011-01-10 11:17:36 -0800500 public void registerInputChannel(InputChannel inputChannel,
501 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700502 if (inputChannel == null) {
503 throw new IllegalArgumentException("inputChannel must not be null.");
504 }
RoboErikfb290df2013-12-16 11:27:55 -0800505
Jeff Brown4532e612012-04-05 14:27:12 -0700506 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700507 }
RoboErikfb290df2013-12-16 11:27:55 -0800508
Jeff Browna41ca772010-08-11 14:46:32 -0700509 /**
510 * Unregisters an input channel.
511 * @param inputChannel The input channel to unregister.
512 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700513 public void unregisterInputChannel(InputChannel inputChannel) {
514 if (inputChannel == null) {
515 throw new IllegalArgumentException("inputChannel must not be null.");
516 }
RoboErikfb290df2013-12-16 11:27:55 -0800517
Jeff Brown4532e612012-04-05 14:27:12 -0700518 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700519 }
Jeff Brown0029c662011-03-30 02:25:18 -0700520
521 /**
522 * Sets an input filter that will receive all input events before they are dispatched.
523 * The input filter may then reinterpret input events or inject new ones.
524 *
525 * To ensure consistency, the input dispatcher automatically drops all events
526 * in progress whenever an input filter is installed or uninstalled. After an input
527 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
528 * Any events it attempts to send after it has been uninstalled will be dropped.
529 *
530 * @param filter The input filter, or null to remove the current filter.
531 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700532 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700533 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700534 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700535 if (oldFilter == filter) {
536 return; // nothing to do
537 }
538
539 if (oldFilter != null) {
540 mInputFilter = null;
541 mInputFilterHost.disconnectLocked();
542 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700543 try {
544 oldFilter.uninstall();
545 } catch (RemoteException re) {
546 /* ignore */
547 }
Jeff Brown0029c662011-03-30 02:25:18 -0700548 }
549
550 if (filter != null) {
551 mInputFilter = filter;
552 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700553 try {
554 filter.install(mInputFilterHost);
555 } catch (RemoteException re) {
556 /* ignore */
557 }
Jeff Brown0029c662011-03-30 02:25:18 -0700558 }
559
Jeff Brown4532e612012-04-05 14:27:12 -0700560 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700561 }
562 }
563
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700564 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700565 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brownca9bc702014-02-11 14:32:56 -0800566 return injectInputEventInternal(event, Display.DEFAULT_DISPLAY, mode);
567 }
568
569 private boolean injectInputEventInternal(InputEvent event, int displayId, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700570 if (event == null) {
571 throw new IllegalArgumentException("event must not be null");
572 }
Jeff Brownac143512012-04-05 18:57:33 -0700573 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
574 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
575 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
576 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700577 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700578
Jeff Brownac143512012-04-05 18:57:33 -0700579 final int pid = Binder.getCallingPid();
580 final int uid = Binder.getCallingUid();
581 final long ident = Binder.clearCallingIdentity();
582 final int result;
583 try {
Jeff Brownca9bc702014-02-11 14:32:56 -0800584 result = nativeInjectInputEvent(mPtr, event, displayId, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700585 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
586 } finally {
587 Binder.restoreCallingIdentity(ident);
588 }
589 switch (result) {
590 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
591 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
592 throw new SecurityException(
593 "Injecting to another application requires INJECT_EVENTS permission");
594 case INPUT_EVENT_INJECTION_SUCCEEDED:
595 return true;
596 case INPUT_EVENT_INJECTION_TIMED_OUT:
597 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
598 return false;
599 case INPUT_EVENT_INJECTION_FAILED:
600 default:
601 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
602 return false;
603 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700604 }
Jeff Brown0029c662011-03-30 02:25:18 -0700605
Jeff Brown8d608662010-08-30 03:02:23 -0700606 /**
607 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700608 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700609 * @return The input device or null if not found.
610 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700611 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700612 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700613 synchronized (mInputDevicesLock) {
614 final int count = mInputDevices.length;
615 for (int i = 0; i < count; i++) {
616 final InputDevice inputDevice = mInputDevices[i];
617 if (inputDevice.getId() == deviceId) {
618 return inputDevice;
619 }
620 }
621 }
622 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700623 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700624
Jeff Brown8d608662010-08-30 03:02:23 -0700625 /**
626 * Gets the ids of all input devices in the system.
627 * @return The input device ids.
628 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700629 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700630 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700631 synchronized (mInputDevicesLock) {
632 final int count = mInputDevices.length;
633 int[] ids = new int[count];
634 for (int i = 0; i < count; i++) {
635 ids[i] = mInputDevices[i].getId();
636 }
637 return ids;
638 }
639 }
640
Jeff Browndaa37532012-05-01 15:54:03 -0700641 /**
642 * Gets all input devices in the system.
643 * @return The array of input devices.
644 */
645 public InputDevice[] getInputDevices() {
646 synchronized (mInputDevicesLock) {
647 return mInputDevices;
648 }
649 }
650
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700651 @Override // Binder call
652 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
653 if (listener == null) {
654 throw new IllegalArgumentException("listener must not be null");
655 }
656
657 synchronized (mInputDevicesLock) {
658 int callingPid = Binder.getCallingPid();
659 if (mInputDevicesChangedListeners.get(callingPid) != null) {
660 throw new SecurityException("The calling process has already "
661 + "registered an InputDevicesChangedListener.");
662 }
663
664 InputDevicesChangedListenerRecord record =
665 new InputDevicesChangedListenerRecord(callingPid, listener);
666 try {
667 IBinder binder = listener.asBinder();
668 binder.linkToDeath(record, 0);
669 } catch (RemoteException ex) {
670 // give up
671 throw new RuntimeException(ex);
672 }
673
674 mInputDevicesChangedListeners.put(callingPid, record);
675 }
676 }
677
678 private void onInputDevicesChangedListenerDied(int pid) {
679 synchronized (mInputDevicesLock) {
680 mInputDevicesChangedListeners.remove(pid);
681 }
682 }
683
684 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700685 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
686 // Scan for changes.
687 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700688 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700689 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700690 final int numListeners;
691 final int[] deviceIdAndGeneration;
692 synchronized (mInputDevicesLock) {
693 if (!mInputDevicesChangedPending) {
694 return;
695 }
696 mInputDevicesChangedPending = false;
697
698 numListeners = mInputDevicesChangedListeners.size();
699 for (int i = 0; i < numListeners; i++) {
700 mTempInputDevicesChangedListenersToNotify.add(
701 mInputDevicesChangedListeners.valueAt(i));
702 }
703
704 final int numDevices = mInputDevices.length;
705 deviceIdAndGeneration = new int[numDevices * 2];
706 for (int i = 0; i < numDevices; i++) {
707 final InputDevice inputDevice = mInputDevices[i];
708 deviceIdAndGeneration[i * 2] = inputDevice.getId();
709 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700710
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700711 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700712 if (!containsInputDeviceWithDescriptor(oldInputDevices,
713 inputDevice.getDescriptor())) {
714 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
715 } else {
716 mTempFullKeyboards.add(inputDevice);
717 }
718 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700719 }
720 }
721
Jeff Browncf39bdf2012-05-18 14:41:19 -0700722 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700723 for (int i = 0; i < numListeners; i++) {
724 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
725 deviceIdAndGeneration);
726 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700727 mTempInputDevicesChangedListenersToNotify.clear();
728
729 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000730 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
731 final int numFullKeyboards = mTempFullKeyboards.size();
732 synchronized (mDataStore) {
733 for (int i = 0; i < numFullKeyboards; i++) {
734 final InputDevice inputDevice = mTempFullKeyboards.get(i);
735 String layout =
736 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
737 if (layout == null) {
738 layout = getDefaultKeyboardLayout(inputDevice);
739 if (layout != null) {
740 setCurrentKeyboardLayoutForInputDevice(
741 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700742 }
743 }
Michael Wright07483422015-10-30 16:20:13 +0000744 if (layout == null) {
745 keyboardsMissingLayout.add(inputDevice);
746 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700747 }
Michael Wright07483422015-10-30 16:20:13 +0000748 }
749
750 if (mNotificationManager != null) {
751 if (!keyboardsMissingLayout.isEmpty()) {
752 if (keyboardsMissingLayout.size() > 1) {
753 // We have more than one keyboard missing a layout, so drop the
754 // user at the generic input methods page so they can pick which
755 // one to set.
756 showMissingKeyboardLayoutNotification(null);
757 } else {
758 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700759 }
760 } else if (mKeyboardLayoutNotificationShown) {
761 hideMissingKeyboardLayoutNotification();
762 }
763 }
764 mTempFullKeyboards.clear();
765 }
766
Michael Wright07483422015-10-30 16:20:13 +0000767 private String getDefaultKeyboardLayout(final InputDevice d) {
768 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
769 // If our locale doesn't have a language for some reason, then we don't really have a
770 // reasonable default.
771 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
772 return null;
773 }
774 final List<KeyboardLayout> layouts = new ArrayList<>();
775 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
776 @Override
777 public void visitKeyboardLayout(Resources resources,
778 int keyboardLayoutResId, KeyboardLayout layout) {
779 // Only select a default when we know the layout is appropriate. For now, this
780 // means its a custom layout for a specific keyboard.
781 if (layout.getVendorId() != d.getVendorId()
782 || layout.getProductId() != d.getProductId()) {
783 return;
784 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800785 final LocaleList locales = layout.getLocales();
786 final int numLocales = locales.size();
787 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
788 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000789 layouts.add(layout);
790 break;
791 }
792 }
793 }
794 });
795
796 if (layouts.isEmpty()) {
797 return null;
798 }
799
800 // First sort so that ones with higher priority are listed at the top
801 Collections.sort(layouts);
802 // Next we want to try to find an exact match of language, country and variant.
803 final int N = layouts.size();
804 for (int i = 0; i < N; i++) {
805 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800806 final LocaleList locales = layout.getLocales();
807 final int numLocales = locales.size();
808 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
809 final Locale locale = locales.get(localeIndex);
810 if (locale.getCountry().equals(systemLocale.getCountry())
811 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000812 return layout.getDescriptor();
813 }
814 }
815 }
816 // Then try an exact match of language and country
817 for (int i = 0; i < N; i++) {
818 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800819 final LocaleList locales = layout.getLocales();
820 final int numLocales = locales.size();
821 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
822 final Locale locale = locales.get(localeIndex);
823 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000824 return layout.getDescriptor();
825 }
826 }
827 }
828
829 // Give up and just use the highest priority layout with matching language
830 return layouts.get(0).getDescriptor();
831 }
832
833 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
834 // Different languages are never compatible
835 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
836 return false;
837 }
838 // If both the system and the keyboard layout have a country specifier, they must be equal.
839 if (!TextUtils.isEmpty(systemLocale.getCountry())
840 && !TextUtils.isEmpty(keyboardLocale.getCountry())
841 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
842 return false;
843 }
844 return true;
845 }
846
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800847 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700848 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
849 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800850 if (inputDeviceDescriptor == null) {
851 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
852 }
853
854 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700855 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800856 }
857 }
858
859 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700860 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800861 TouchCalibration calibration) {
862 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
863 "setTouchCalibrationForInputDevice()")) {
864 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
865 }
866 if (inputDeviceDescriptor == null) {
867 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
868 }
869 if (calibration == null) {
870 throw new IllegalArgumentException("calibration must not be null");
871 }
Jason Gerecked5220742014-03-10 09:47:59 -0700872 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
873 throw new IllegalArgumentException("surfaceRotation value out of bounds");
874 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800875
876 synchronized (mDataStore) {
877 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700878 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
879 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800880 nativeReloadCalibration(mPtr);
881 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800882 } finally {
883 mDataStore.saveIfNeeded();
884 }
885 }
886 }
887
Michael Wright39e5e942015-08-19 22:52:47 +0100888 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100889 public int isInTabletMode() {
890 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
891 "isInTabletMode()")) {
892 throw new SecurityException("Requires TABLET_MODE permission");
893 }
894 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
895 }
896
897 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100898 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100899 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100900 "registerTabletModeChangedListener()")) {
901 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
902 }
903 if (listener == null) {
904 throw new IllegalArgumentException("listener must not be null");
905 }
906
907 synchronized (mTabletModeLock) {
908 final int callingPid = Binder.getCallingPid();
909 if (mTabletModeChangedListeners.get(callingPid) != null) {
910 throw new IllegalStateException("The calling process has already registered "
911 + "a TabletModeChangedListener.");
912 }
913 TabletModeChangedListenerRecord record =
914 new TabletModeChangedListenerRecord(callingPid, listener);
915 try {
916 IBinder binder = listener.asBinder();
917 binder.linkToDeath(record, 0);
918 } catch (RemoteException ex) {
919 throw new RuntimeException(ex);
920 }
921 mTabletModeChangedListeners.put(callingPid, record);
922 }
923 }
924
925 private void onTabletModeChangedListenerDied(int pid) {
926 synchronized (mTabletModeLock) {
927 mTabletModeChangedListeners.remove(pid);
928 }
929 }
930
931 // Must be called on handler
932 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
933 mTempTabletModeChangedListenersToNotify.clear();
934 final int numListeners;
935 synchronized (mTabletModeLock) {
936 numListeners = mTabletModeChangedListeners.size();
937 for (int i = 0; i < numListeners; i++) {
938 mTempTabletModeChangedListenersToNotify.add(
939 mTabletModeChangedListeners.valueAt(i));
940 }
941 }
942 for (int i = 0; i < numListeners; i++) {
943 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
944 whenNanos, inTabletMode);
945 }
946 }
947
Jeff Browncf39bdf2012-05-18 14:41:19 -0700948 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700949 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700950 if (!mKeyboardLayoutNotificationShown) {
Michael Wrightc93fbd12014-09-22 20:07:59 -0700951 final Intent intent = new Intent(Settings.ACTION_INPUT_METHOD_SETTINGS);
952 if (device != null) {
953 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700954 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700955 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
956 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
957 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
958 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
959 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700960
961 Resources r = mContext.getResources();
962 Notification notification = new Notification.Builder(mContext)
963 .setContentTitle(r.getString(
964 R.string.select_keyboard_layout_notification_title))
965 .setContentText(r.getString(
966 R.string.select_keyboard_layout_notification_message))
Michael Wrightc93fbd12014-09-22 20:07:59 -0700967 .setContentIntent(keyboardLayoutIntent)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700968 .setSmallIcon(R.drawable.ic_settings_language)
969 .setPriority(Notification.PRIORITY_LOW)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700970 .setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200971 com.android.internal.R.color.system_notification_accent_color))
Jeff Browncf39bdf2012-05-18 14:41:19 -0700972 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700973 mNotificationManager.notifyAsUser(null,
974 R.string.select_keyboard_layout_notification_title,
975 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700976 mKeyboardLayoutNotificationShown = true;
977 }
978 }
979
980 // Must be called on handler.
981 private void hideMissingKeyboardLayoutNotification() {
982 if (mKeyboardLayoutNotificationShown) {
983 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700984 mNotificationManager.cancelAsUser(null,
985 R.string.select_keyboard_layout_notification_title,
986 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700987 }
988 }
989
990 // Must be called on handler.
991 private void updateKeyboardLayouts() {
992 // Scan all input devices state for keyboard layouts that have been uninstalled.
993 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
994 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
995 @Override
Michael Wright07483422015-10-30 16:20:13 +0000996 public void visitKeyboardLayout(Resources resources,
997 int keyboardLayoutResId, KeyboardLayout layout) {
998 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700999 }
1000 });
1001 synchronized (mDataStore) {
1002 try {
1003 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1004 } finally {
1005 mDataStore.saveIfNeeded();
1006 }
1007 }
1008
1009 // Reload keyboard layouts.
1010 reloadKeyboardLayouts();
1011 }
1012
Jeff Browncf39bdf2012-05-18 14:41:19 -07001013 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1014 String descriptor) {
1015 final int numDevices = inputDevices.length;
1016 for (int i = 0; i < numDevices; i++) {
1017 final InputDevice inputDevice = inputDevices[i];
1018 if (inputDevice.getDescriptor().equals(descriptor)) {
1019 return true;
1020 }
1021 }
1022 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001023 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001024
1025 @Override // Binder call
1026 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001027 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1028 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1029 @Override
Michael Wright07483422015-10-30 16:20:13 +00001030 public void visitKeyboardLayout(Resources resources,
1031 int keyboardLayoutResId, KeyboardLayout layout) {
1032 list.add(layout);
1033 }
1034 });
1035 return list.toArray(new KeyboardLayout[list.size()]);
1036 }
1037
Michael Wrightb0e804a2016-01-04 16:48:53 -05001038 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001039 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1040 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001041 final String[] enabledLayoutDescriptors =
1042 getEnabledKeyboardLayoutsForInputDevice(identifier);
1043 final ArrayList<KeyboardLayout> enabledLayouts =
1044 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1045 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001046 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1047 boolean mHasSeenDeviceSpecificLayout;
1048
1049 @Override
1050 public void visitKeyboardLayout(Resources resources,
1051 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001052 // First check if it's enabled. If the keyboard layout is enabled then we always
1053 // want to return it as a possible layout for the device.
1054 for (String s : enabledLayoutDescriptors) {
1055 if (s != null && s.equals(layout.getDescriptor())) {
1056 enabledLayouts.add(layout);
1057 return;
1058 }
1059 }
1060 // Next find any potential layouts that aren't yet enabled for the device. For
1061 // devices that have special layouts we assume there's a reason that the generic
1062 // layouts don't work for them so we don't want to return them since it's likely
1063 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001064 if (layout.getVendorId() == identifier.getVendorId()
1065 && layout.getProductId() == identifier.getProductId()) {
1066 if (!mHasSeenDeviceSpecificLayout) {
1067 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001068 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001069 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001070 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001071 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1072 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001073 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001074 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001075 }
1076 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001077 final int enabledLayoutSize = enabledLayouts.size();
1078 final int potentialLayoutSize = potentialLayouts.size();
1079 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1080 enabledLayouts.toArray(layouts);
1081 for (int i = 0; i < potentialLayoutSize; i++) {
1082 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1083 }
1084 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001085 }
1086
1087 @Override // Binder call
1088 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1089 if (keyboardLayoutDescriptor == null) {
1090 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1091 }
1092
Jeff Brown6ec6f792012-04-17 16:52:41 -07001093 final KeyboardLayout[] result = new KeyboardLayout[1];
1094 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1095 @Override
Michael Wright07483422015-10-30 16:20:13 +00001096 public void visitKeyboardLayout(Resources resources,
1097 int keyboardLayoutResId, KeyboardLayout layout) {
1098 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001099 }
1100 });
1101 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001102 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001103 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001104 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001105 return result[0];
1106 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001107
Jeff Brown6ec6f792012-04-17 16:52:41 -07001108 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001109 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001110 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1111 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001112 PackageManager.GET_META_DATA | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001113 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1114 final int priority = resolveInfo.priority;
1115 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001116 }
1117 }
1118
Jeff Brown6ec6f792012-04-17 16:52:41 -07001119 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1120 KeyboardLayoutVisitor visitor) {
1121 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1122 if (d != null) {
1123 final PackageManager pm = mContext.getPackageManager();
1124 try {
1125 ActivityInfo receiver = pm.getReceiverInfo(
1126 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001127 PackageManager.GET_META_DATA
1128 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001129 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001130 } catch (NameNotFoundException ex) {
1131 }
1132 }
1133 }
1134
1135 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001136 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001137 Bundle metaData = receiver.metaData;
1138 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001139 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001140 }
1141
1142 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1143 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001144 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001145 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001146 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001147 }
1148
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001149 CharSequence receiverLabel = receiver.loadLabel(pm);
1150 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001151 int priority;
1152 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1153 priority = requestedPriority;
1154 } else {
1155 priority = 0;
1156 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001157
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001158 try {
1159 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1160 XmlResourceParser parser = resources.getXml(configResId);
1161 try {
1162 XmlUtils.beginDocument(parser, "keyboard-layouts");
1163
1164 for (;;) {
1165 XmlUtils.nextElement(parser);
1166 String element = parser.getName();
1167 if (element == null) {
1168 break;
1169 }
1170 if (element.equals("keyboard-layout")) {
1171 TypedArray a = resources.obtainAttributes(
1172 parser, com.android.internal.R.styleable.KeyboardLayout);
1173 try {
1174 String name = a.getString(
1175 com.android.internal.R.styleable.KeyboardLayout_name);
1176 String label = a.getString(
1177 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001178 int keyboardLayoutResId = a.getResourceId(
1179 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1180 0);
Michael Wright07483422015-10-30 16:20:13 +00001181 String languageTags = a.getString(
1182 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001183 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001184 int vid = a.getInt(
1185 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1186 int pid = a.getInt(
1187 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1188
Jeff Brown2f095762012-05-10 21:29:33 -07001189 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001190 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001191 + "attributes in keyboard layout "
1192 + "resource from receiver "
1193 + receiver.packageName + "/" + receiver.name);
1194 } else {
1195 String descriptor = KeyboardLayoutDescriptor.format(
1196 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001197 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001198 KeyboardLayout layout = new KeyboardLayout(
1199 descriptor, label, collection, priority,
1200 locales, vid, pid);
1201 visitor.visitKeyboardLayout(
1202 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001203 }
1204 }
1205 } finally {
1206 a.recycle();
1207 }
1208 } else {
Michael Wright07483422015-10-30 16:20:13 +00001209 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001210 + "' in keyboard layout resource from receiver "
1211 + receiver.packageName + "/" + receiver.name);
1212 }
1213 }
1214 } finally {
1215 parser.close();
1216 }
1217 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001218 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001219 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001220 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001221 }
1222
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001223 @NonNull
1224 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001225 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001226 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001227 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001228 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001229 }
1230
RoboErikfb290df2013-12-16 11:27:55 -08001231 /**
1232 * Builds a layout descriptor for the vendor/product. This returns the
1233 * descriptor for ids that aren't useful (such as the default 0, 0).
1234 */
1235 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1236 if (identifier == null || identifier.getDescriptor() == null) {
1237 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001238 }
1239
RoboErikfb290df2013-12-16 11:27:55 -08001240 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1241 return identifier.getDescriptor();
1242 }
1243 StringBuilder bob = new StringBuilder();
1244 bob.append("vendor:").append(identifier.getVendorId());
1245 bob.append(",product:").append(identifier.getProductId());
1246 return bob.toString();
1247 }
1248
1249 @Override // Binder call
1250 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1251
1252 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001253 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001254 String layout = null;
1255 // try loading it using the layout descriptor if we have it
1256 layout = mDataStore.getCurrentKeyboardLayout(key);
1257 if (layout == null && !key.equals(identifier.getDescriptor())) {
1258 // if it doesn't exist fall back to the device descriptor
1259 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1260 }
1261 if (DEBUG) {
1262 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1263 + layout);
1264 }
1265 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001266 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001267 }
1268
1269 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001270 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001271 String keyboardLayoutDescriptor) {
1272 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001273 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001274 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1275 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001276 if (keyboardLayoutDescriptor == null) {
1277 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1278 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001279
RoboErikfb290df2013-12-16 11:27:55 -08001280 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001281 synchronized (mDataStore) {
1282 try {
RoboErikfb290df2013-12-16 11:27:55 -08001283 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1284 if (DEBUG) {
1285 Slog.d(TAG, "Saved keyboard layout using " + key);
1286 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001287 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1288 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001289 } finally {
1290 mDataStore.saveIfNeeded();
1291 }
1292 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001293 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001294
Jeff Browncf39bdf2012-05-18 14:41:19 -07001295 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001296 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001297 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001298 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001299 String[] layouts = mDataStore.getKeyboardLayouts(key);
1300 if ((layouts == null || layouts.length == 0)
1301 && !key.equals(identifier.getDescriptor())) {
1302 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1303 }
1304 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001305 }
1306 }
1307
1308 @Override // Binder call
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001309 @Nullable
1310 public KeyboardLayout getKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1311 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype) {
1312 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1313 String key = getLayoutDescriptor(identifier);
1314 final String keyboardLayoutDescriptor;
1315 synchronized (mDataStore) {
1316 keyboardLayoutDescriptor = mDataStore.getKeyboardLayout(key, handle);
1317 }
1318
1319 if (keyboardLayoutDescriptor == null) {
1320 return null;
1321 }
1322
1323 final KeyboardLayout[] result = new KeyboardLayout[1];
1324 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1325 @Override
1326 public void visitKeyboardLayout(Resources resources,
1327 int keyboardLayoutResId, KeyboardLayout layout) {
1328 result[0] = layout;
1329 }
1330 });
1331 if (result[0] == null) {
1332 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
1333 + keyboardLayoutDescriptor + "'.");
1334 }
1335 return result[0];
1336 }
1337
1338 @Override
1339 public void setKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1340 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype,
1341 String keyboardLayoutDescriptor) {
1342 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1343 "setKeyboardLayoutForInputDevice()")) {
1344 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1345 }
1346 if (keyboardLayoutDescriptor == null) {
1347 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1348 }
1349 if (imeInfo == null || imeSubtype == null) {
1350 throw new IllegalArgumentException("imeInfo and imeSubtype must not be null");
1351 }
1352 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1353 setKeyboardLayoutForInputDeviceInner(identifier, handle, keyboardLayoutDescriptor);
1354 }
1355
1356 private void setKeyboardLayoutForInputDeviceInner(InputDeviceIdentifier identifier,
1357 InputMethodSubtypeHandle imeHandle, String keyboardLayoutDescriptor) {
1358 String key = getLayoutDescriptor(identifier);
1359 synchronized (mDataStore) {
1360 try {
1361 if (mDataStore.setKeyboardLayout(key, imeHandle, keyboardLayoutDescriptor)) {
1362 if (DEBUG) {
1363 Slog.d(TAG, "Set keyboard layout " + keyboardLayoutDescriptor +
1364 " for subtype " + imeHandle + " and device " + identifier +
1365 " using key " + key);
1366 }
1367 if (imeHandle.equals(mCurrentImeHandle)) {
1368 if (DEBUG) {
1369 Slog.d(TAG, "Layout for current subtype changed, switching layout");
1370 }
1371 SomeArgs args = SomeArgs.obtain();
1372 args.arg1 = identifier;
1373 args.arg2 = imeHandle;
1374 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, args).sendToTarget();
1375 }
1376 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1377 }
1378 } finally {
1379 mDataStore.saveIfNeeded();
1380 }
1381 }
1382 }
1383
1384 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001385 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001386 String keyboardLayoutDescriptor) {
1387 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1388 "addKeyboardLayoutForInputDevice()")) {
1389 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1390 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001391 if (keyboardLayoutDescriptor == null) {
1392 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1393 }
1394
RoboErikfb290df2013-12-16 11:27:55 -08001395 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001396 synchronized (mDataStore) {
1397 try {
RoboErikfb290df2013-12-16 11:27:55 -08001398 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1399 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1400 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1401 }
1402 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001403 && !Objects.equal(oldLayout, mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001404 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1405 }
1406 } finally {
1407 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001408 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001409 }
1410 }
1411
1412 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001413 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001414 String keyboardLayoutDescriptor) {
1415 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1416 "removeKeyboardLayoutForInputDevice()")) {
1417 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1418 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001419 if (keyboardLayoutDescriptor == null) {
1420 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1421 }
1422
RoboErikfb290df2013-12-16 11:27:55 -08001423 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001424 synchronized (mDataStore) {
1425 try {
RoboErikfb290df2013-12-16 11:27:55 -08001426 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1427 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1428 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1429 }
1430 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1431 if (!key.equals(identifier.getDescriptor())) {
1432 // We need to remove from both places to ensure it is gone
1433 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1434 keyboardLayoutDescriptor);
1435 }
1436 if (removed && !Objects.equal(oldLayout,
1437 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001438 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1439 }
1440 } finally {
1441 mDataStore.saveIfNeeded();
1442 }
1443 }
1444 }
1445
Yohei Yukawab097b822015-12-01 10:43:08 -08001446 // Must be called on handler.
1447 private void handleSwitchInputMethodSubtype(int userId,
1448 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1449 if (DEBUG) {
1450 Slog.i(TAG, "InputMethodSubtype changed: userId=" + userId
1451 + " ime=" + inputMethodInfo + " subtype=" + subtype);
1452 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001453 if (inputMethodInfo == null) {
1454 Slog.d(TAG, "No InputMethod is running, ignoring change");
1455 return;
1456 }
1457 if (subtype != null && !"keyboard".equals(subtype.getMode())) {
1458 Slog.d(TAG, "InputMethodSubtype changed to non-keyboard subtype, ignoring change");
1459 return;
1460 }
1461 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(inputMethodInfo, subtype);
1462 if (!handle.equals(mCurrentImeHandle)) {
1463 mCurrentImeHandle = handle;
1464 handleSwitchKeyboardLayout(null, handle);
1465 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001466 }
1467
1468 // Must be called on handler.
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001469 private void handleSwitchKeyboardLayout(@Nullable InputDeviceIdentifier identifier,
1470 InputMethodSubtypeHandle handle) {
1471 synchronized (mInputDevicesLock) {
1472 for (InputDevice device : mInputDevices) {
1473 if (identifier != null && !device.getIdentifier().equals(identifier) ||
1474 !device.isFullKeyboard()) {
1475 continue;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001476 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001477 String key = getLayoutDescriptor(device.getIdentifier());
1478 boolean changed = false;
1479 synchronized (mDataStore) {
1480 try {
1481 if (mDataStore.switchKeyboardLayout(key, handle)) {
1482 changed = true;
1483 }
1484 } finally {
1485 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001486 }
1487 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001488 if (changed) {
1489 reloadKeyboardLayouts();
1490 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001491 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001492 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001493 }
1494
Jeff Brown9302c872011-07-13 22:51:29 -07001495 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001496 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001497 }
RoboErikfb290df2013-12-16 11:27:55 -08001498
Jeff Brown9302c872011-07-13 22:51:29 -07001499 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001500 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001501 }
RoboErikfb290df2013-12-16 11:27:55 -08001502
Jun Mukai347e5d42015-12-03 01:13:31 -08001503 @Override
1504 public void setPointerIconDetached(boolean detached) {
1505 nativeSetPointerIconDetached(mPtr, detached);
1506 }
1507
Jeff Brown349703e2010-06-22 01:27:15 -07001508 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001509 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001510 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001511
1512 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001513 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001514 }
1515
Jeff Browne6504122010-09-27 14:52:15 -07001516 /**
1517 * Atomically transfers touch focus from one window to another as identified by
1518 * their input channels. It is possible for multiple windows to have
1519 * touch focus if they support split touch dispatch
1520 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1521 * method only transfers touch focus of the specified window without affecting
1522 * other windows that may also have touch focus at the same time.
1523 * @param fromChannel The channel of a window that currently has touch focus.
1524 * @param toChannel The channel of the window that should receive touch focus in
1525 * place of the first.
1526 * @return True if the transfer was successful. False if the window with the
1527 * specified channel did not actually have touch focus at the time of the request.
1528 */
1529 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1530 if (fromChannel == null) {
1531 throw new IllegalArgumentException("fromChannel must not be null.");
1532 }
1533 if (toChannel == null) {
1534 throw new IllegalArgumentException("toChannel must not be null.");
1535 }
Jeff Brown4532e612012-04-05 14:27:12 -07001536 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001537 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001538
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001539 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001540 public void tryPointerSpeed(int speed) {
1541 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1542 "tryPointerSpeed()")) {
1543 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1544 }
1545
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001546 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1547 throw new IllegalArgumentException("speed out of range");
1548 }
1549
Jeff Brownac143512012-04-05 18:57:33 -07001550 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001551 }
1552
1553 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001554 int speed = getPointerSpeedSetting();
1555 setPointerSpeedUnchecked(speed);
1556 }
1557
1558 private void setPointerSpeedUnchecked(int speed) {
1559 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1560 InputManager.MAX_POINTER_SPEED);
1561 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001562 }
1563
1564 private void registerPointerSpeedSettingObserver() {
1565 mContext.getContentResolver().registerContentObserver(
1566 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001567 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001568 @Override
1569 public void onChange(boolean selfChange) {
1570 updatePointerSpeedFromSettings();
1571 }
Jeff Brownd4935962012-09-25 13:27:20 -07001572 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001573 }
1574
Jeff Brownac143512012-04-05 18:57:33 -07001575 private int getPointerSpeedSetting() {
1576 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001577 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001578 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1579 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001580 } catch (SettingNotFoundException snfe) {
1581 }
1582 return speed;
1583 }
1584
Jeff Browndaf4a122011-08-26 17:14:14 -07001585 public void updateShowTouchesFromSettings() {
1586 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001587 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001588 }
1589
1590 private void registerShowTouchesSettingObserver() {
1591 mContext.getContentResolver().registerContentObserver(
1592 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001593 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001594 @Override
1595 public void onChange(boolean selfChange) {
1596 updateShowTouchesFromSettings();
1597 }
Jeff Brownd4935962012-09-25 13:27:20 -07001598 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001599 }
1600
Jun Mukaie4e75da2015-12-15 16:19:20 -08001601 public void updateAccessibilityLargePointerFromSettings() {
1602 final int accessibilityConfig = Settings.Secure.getIntForUser(
1603 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1604 0, UserHandle.USER_CURRENT);
1605 PointerIcon.sUseLargeIcons = (accessibilityConfig == 1);
1606 nativeReloadPointerIcons(mPtr);
1607 }
1608
Jun Mukai19a56012015-11-24 11:25:52 -08001609 private void registerAccessibilityLargePointerSettingObserver() {
1610 mContext.getContentResolver().registerContentObserver(
1611 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1612 new ContentObserver(mHandler) {
1613 @Override
1614 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001615 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001616 }
1617 }, UserHandle.USER_ALL);
1618 }
1619
Jeff Browndaf4a122011-08-26 17:14:14 -07001620 private int getShowTouchesSetting(int defaultValue) {
1621 int result = defaultValue;
1622 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001623 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1624 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001625 } catch (SettingNotFoundException snfe) {
1626 }
1627 return result;
1628 }
1629
Jeff Browna47425a2012-04-13 04:09:27 -07001630 // Binder call
1631 @Override
1632 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1633 if (repeat >= pattern.length) {
1634 throw new ArrayIndexOutOfBoundsException();
1635 }
1636
1637 VibratorToken v;
1638 synchronized (mVibratorLock) {
1639 v = mVibratorTokens.get(token);
1640 if (v == null) {
1641 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1642 try {
1643 token.linkToDeath(v, 0);
1644 } catch (RemoteException ex) {
1645 // give up
1646 throw new RuntimeException(ex);
1647 }
1648 mVibratorTokens.put(token, v);
1649 }
1650 }
1651
1652 synchronized (v) {
1653 v.mVibrating = true;
1654 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1655 }
1656 }
1657
1658 // Binder call
1659 @Override
1660 public void cancelVibrate(int deviceId, IBinder token) {
1661 VibratorToken v;
1662 synchronized (mVibratorLock) {
1663 v = mVibratorTokens.get(token);
1664 if (v == null || v.mDeviceId != deviceId) {
1665 return; // nothing to cancel
1666 }
1667 }
1668
1669 cancelVibrateIfNeeded(v);
1670 }
1671
1672 void onVibratorTokenDied(VibratorToken v) {
1673 synchronized (mVibratorLock) {
1674 mVibratorTokens.remove(v.mToken);
1675 }
1676
1677 cancelVibrateIfNeeded(v);
1678 }
1679
1680 private void cancelVibrateIfNeeded(VibratorToken v) {
1681 synchronized (v) {
1682 if (v.mVibrating) {
1683 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1684 v.mVibrating = false;
1685 }
1686 }
1687 }
1688
Jun Mukai19a56012015-11-24 11:25:52 -08001689 // Binder call
1690 @Override
1691 public void setPointerIconShape(int iconId) {
1692 nativeSetPointerIconShape(mPtr, iconId);
1693 }
Jun Mukai1db53972015-09-11 18:08:31 -07001694
Jun Mukaid4eaef72015-10-30 15:54:33 -07001695 // Binder call
1696 @Override
1697 public void setCustomPointerIcon(PointerIcon icon) {
1698 nativeSetCustomPointerIcon(mPtr, icon);
1699 }
1700
Jeff Brown4532e612012-04-05 14:27:12 -07001701 @Override
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001702 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001703 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001704 != PackageManager.PERMISSION_GRANTED) {
1705 pw.println("Permission Denial: can't dump InputManager from from pid="
1706 + Binder.getCallingPid()
1707 + ", uid=" + Binder.getCallingUid());
1708 return;
1709 }
1710
1711 pw.println("INPUT MANAGER (dumpsys input)\n");
1712 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001713 if (dumpStr != null) {
1714 pw.println(dumpStr);
1715 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001716 pw.println(" Keyboard Layouts:");
1717 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1718 @Override
1719 public void visitKeyboardLayout(Resources resources,
1720 int keyboardLayoutResId, KeyboardLayout layout) {
1721 pw.println(" \"" + layout + "\": " + layout.getDescriptor());
1722 }
1723 });
1724 pw.println();
1725 synchronized(mDataStore) {
1726 mDataStore.dump(pw, " ");
1727 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001728 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001729
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001730 @Override
1731 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1732 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1733 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1734 }
1735
1736 public int onShellCommand(Shell shell, String cmd) {
1737 if (TextUtils.isEmpty(cmd)) {
1738 shell.onHelp();
1739 return 1;
1740 }
1741 if (cmd.equals("setlayout")) {
1742 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1743 "onShellCommand()")) {
1744 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1745 }
1746 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(
1747 shell.getNextArgRequired(), Integer.parseInt(shell.getNextArgRequired()));
1748 String descriptor = shell.getNextArgRequired();
1749 int vid = Integer.decode(shell.getNextArgRequired());
1750 int pid = Integer.decode(shell.getNextArgRequired());
1751 InputDeviceIdentifier id = new InputDeviceIdentifier(descriptor, vid, pid);
1752 setKeyboardLayoutForInputDeviceInner(id, handle, shell.getNextArgRequired());
1753 }
1754 return 0;
1755 }
1756
1757
Jeff Brownac143512012-04-05 18:57:33 -07001758 private boolean checkCallingPermission(String permission, String func) {
1759 // Quick check: if the calling permission is me, it's all okay.
1760 if (Binder.getCallingPid() == Process.myPid()) {
1761 return true;
1762 }
1763
1764 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1765 return true;
1766 }
1767 String msg = "Permission Denial: " + func + " from pid="
1768 + Binder.getCallingPid()
1769 + ", uid=" + Binder.getCallingUid()
1770 + " requires " + permission;
1771 Slog.w(TAG, msg);
1772 return false;
1773 }
1774
Jeff Brown4532e612012-04-05 14:27:12 -07001775 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001776 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001777 public void monitor() {
1778 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001779 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001780 }
1781
Jeff Brown4532e612012-04-05 14:27:12 -07001782 // Native callback.
1783 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001784 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001785 }
1786
1787 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001788 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1789 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001790 if (!mInputDevicesChangedPending) {
1791 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001792 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1793 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001794 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001795
1796 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001797 }
1798 }
1799
1800 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001801 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1802 if (DEBUG) {
1803 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1804 + ", mask=" + Integer.toHexString(switchMask));
1805 }
1806
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001807 if ((switchMask & SW_LID_BIT) != 0) {
1808 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001809 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001810 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001811
Michael Wright3818c922014-09-02 13:59:07 -07001812 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001813 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001814 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1815 }
1816
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001817 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1818 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1819 switchMask);
1820 }
Michael Wright39e5e942015-08-19 22:52:47 +01001821
Michael Wright9209c9c2015-09-03 17:57:01 +01001822 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001823 SomeArgs args = SomeArgs.obtain();
1824 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1825 args.argi2 = (int) (whenNanos >> 32);
1826 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1827 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1828 args).sendToTarget();
1829 }
Jeff Brown4532e612012-04-05 14:27:12 -07001830 }
1831
1832 // Native callback.
1833 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001834 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001835 }
1836
1837 // Native callback.
1838 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001839 InputWindowHandle inputWindowHandle, String reason) {
1840 return mWindowManagerCallbacks.notifyANR(
1841 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001842 }
1843
1844 // Native callback.
1845 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1846 synchronized (mInputFilterLock) {
1847 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001848 try {
1849 mInputFilter.filterInputEvent(event, policyFlags);
1850 } catch (RemoteException e) {
1851 /* ignore */
1852 }
Jeff Brown4532e612012-04-05 14:27:12 -07001853 return false;
1854 }
1855 }
1856 event.recycle();
1857 return true;
1858 }
1859
1860 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001861 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1862 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001863 }
1864
1865 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001866 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1867 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001868 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001869 }
1870
1871 // Native callback.
1872 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1873 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001874 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001875 }
1876
1877 // Native callback.
1878 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1879 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001880 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001881 }
1882
1883 // Native callback.
1884 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1885 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1886 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1887 }
1888
1889 // Native callback.
1890 private int getVirtualKeyQuietTimeMillis() {
1891 return mContext.getResources().getInteger(
1892 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1893 }
1894
1895 // Native callback.
1896 private String[] getExcludedDeviceNames() {
1897 ArrayList<String> names = new ArrayList<String>();
1898
1899 // Read partner-provided list of excluded input devices
1900 XmlPullParser parser = null;
1901 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1902 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1903 FileReader confreader = null;
1904 try {
1905 confreader = new FileReader(confFile);
1906 parser = Xml.newPullParser();
1907 parser.setInput(confreader);
1908 XmlUtils.beginDocument(parser, "devices");
1909
1910 while (true) {
1911 XmlUtils.nextElement(parser);
1912 if (!"device".equals(parser.getName())) {
1913 break;
1914 }
1915 String name = parser.getAttributeValue(null, "name");
1916 if (name != null) {
1917 names.add(name);
1918 }
1919 }
1920 } catch (FileNotFoundException e) {
1921 // It's ok if the file does not exist.
1922 } catch (Exception e) {
1923 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1924 } finally {
1925 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1926 }
1927
1928 return names.toArray(new String[names.size()]);
1929 }
1930
1931 // Native callback.
1932 private int getKeyRepeatTimeout() {
1933 return ViewConfiguration.getKeyRepeatTimeout();
1934 }
1935
1936 // Native callback.
1937 private int getKeyRepeatDelay() {
1938 return ViewConfiguration.getKeyRepeatDelay();
1939 }
1940
1941 // Native callback.
1942 private int getHoverTapTimeout() {
1943 return ViewConfiguration.getHoverTapTimeout();
1944 }
1945
1946 // Native callback.
1947 private int getHoverTapSlop() {
1948 return ViewConfiguration.getHoverTapSlop();
1949 }
1950
1951 // Native callback.
1952 private int getDoubleTapTimeout() {
1953 return ViewConfiguration.getDoubleTapTimeout();
1954 }
1955
1956 // Native callback.
1957 private int getLongPressTimeout() {
1958 return ViewConfiguration.getLongPressTimeout();
1959 }
1960
1961 // Native callback.
1962 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001963 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001964 }
1965
1966 // Native callback.
1967 private PointerIcon getPointerIcon() {
1968 return PointerIcon.getDefaultIcon(mContext);
1969 }
1970
Jeff Brown6ec6f792012-04-17 16:52:41 -07001971 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001972 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001973 if (!mSystemReady) {
1974 return null;
1975 }
1976
RoboErikfb290df2013-12-16 11:27:55 -08001977 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001978 if (keyboardLayoutDescriptor == null) {
1979 return null;
1980 }
1981
1982 final String[] result = new String[2];
1983 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1984 @Override
Michael Wright07483422015-10-30 16:20:13 +00001985 public void visitKeyboardLayout(Resources resources,
1986 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001987 try {
Michael Wright07483422015-10-30 16:20:13 +00001988 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001989 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001990 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001991 } catch (IOException ex) {
1992 } catch (NotFoundException ex) {
1993 }
1994 }
1995 });
1996 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001997 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001998 + keyboardLayoutDescriptor + "'.");
1999 return null;
2000 }
2001 return result;
2002 }
2003
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002004 // Native callback.
2005 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07002006 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2007 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2008 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002009 }
2010 return null;
2011 }
2012
Jeff Brown4532e612012-04-05 14:27:12 -07002013 /**
2014 * Callback interface implemented by the Window Manager.
2015 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002016 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002017 public void notifyConfigurationChanged();
2018
2019 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2020
Michael Wright3818c922014-09-02 13:59:07 -07002021 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2022
Jeff Brown4532e612012-04-05 14:27:12 -07002023 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
2024
2025 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07002026 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002027
Jeff Brown037c33e2014-04-09 00:31:55 -07002028 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002029
Michael Wright70af00a2014-09-03 19:30:20 -07002030 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002031
2032 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2033 KeyEvent event, int policyFlags);
2034
2035 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2036 KeyEvent event, int policyFlags);
2037
2038 public int getPointerLayer();
2039 }
2040
2041 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002042 * Callback interface implemented by WiredAccessoryObserver.
2043 */
2044 public interface WiredAccessoryCallbacks {
2045 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002046 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002047 }
2048
2049 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002050 * Private handler for the input manager.
2051 */
2052 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002053 public InputManagerHandler(Looper looper) {
2054 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002055 }
2056
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002057 @Override
2058 public void handleMessage(Message msg) {
2059 switch (msg.what) {
2060 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002061 deliverInputDevicesChanged((InputDevice[])msg.obj);
2062 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002063 case MSG_SWITCH_KEYBOARD_LAYOUT: {
2064 SomeArgs args = (SomeArgs)msg.obj;
2065 handleSwitchKeyboardLayout((InputDeviceIdentifier)args.arg1,
2066 (InputMethodSubtypeHandle)args.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002067 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002068 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07002069 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2070 reloadKeyboardLayouts();
2071 break;
2072 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2073 updateKeyboardLayouts();
2074 break;
2075 case MSG_RELOAD_DEVICE_ALIASES:
2076 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002077 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002078 case MSG_DELIVER_TABLET_MODE_CHANGED: {
Michael Wright39e5e942015-08-19 22:52:47 +01002079 SomeArgs args = (SomeArgs) msg.obj;
2080 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2081 boolean inTabletMode = (boolean) args.arg1;
2082 deliverTabletModeChanged(whenNanos, inTabletMode);
2083 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002084 }
2085 case MSG_INPUT_METHOD_SUBTYPE_CHANGED: {
2086 final int userId = msg.arg1;
2087 final SomeArgs args = (SomeArgs) msg.obj;
2088 final InputMethodInfo inputMethodInfo = (InputMethodInfo) args.arg1;
2089 final InputMethodSubtype subtype = (InputMethodSubtype) args.arg2;
2090 args.recycle();
2091 handleSwitchInputMethodSubtype(userId, inputMethodInfo, subtype);
2092 break;
2093 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002094 }
2095 }
2096 }
2097
2098 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002099 * Hosting interface for input filters to call back into the input manager.
2100 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002101 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002102 private boolean mDisconnected;
2103
2104 public void disconnectLocked() {
2105 mDisconnected = true;
2106 }
2107
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002108 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002109 public void sendInputEvent(InputEvent event, int policyFlags) {
2110 if (event == null) {
2111 throw new IllegalArgumentException("event must not be null");
2112 }
2113
2114 synchronized (mInputFilterLock) {
2115 if (!mDisconnected) {
Jeff Brownca9bc702014-02-11 14:32:56 -08002116 nativeInjectInputEvent(mPtr, event, Display.DEFAULT_DISPLAY, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002117 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002118 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2119 }
2120 }
2121 }
2122 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002123
2124 private static final class KeyboardLayoutDescriptor {
2125 public String packageName;
2126 public String receiverName;
2127 public String keyboardLayoutName;
2128
2129 public static String format(String packageName,
2130 String receiverName, String keyboardName) {
2131 return packageName + "/" + receiverName + "/" + keyboardName;
2132 }
2133
2134 public static KeyboardLayoutDescriptor parse(String descriptor) {
2135 int pos = descriptor.indexOf('/');
2136 if (pos < 0 || pos + 1 == descriptor.length()) {
2137 return null;
2138 }
2139 int pos2 = descriptor.indexOf('/', pos + 1);
2140 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2141 return null;
2142 }
2143
2144 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2145 result.packageName = descriptor.substring(0, pos);
2146 result.receiverName = descriptor.substring(pos + 1, pos2);
2147 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2148 return result;
2149 }
2150 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002151
Jeff Brown6ec6f792012-04-17 16:52:41 -07002152 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002153 void visitKeyboardLayout(Resources resources,
2154 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002155 }
2156
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002157 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2158 private final int mPid;
2159 private final IInputDevicesChangedListener mListener;
2160
2161 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2162 mPid = pid;
2163 mListener = listener;
2164 }
2165
2166 @Override
2167 public void binderDied() {
2168 if (DEBUG) {
2169 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2170 }
2171 onInputDevicesChangedListenerDied(mPid);
2172 }
2173
2174 public void notifyInputDevicesChanged(int[] info) {
2175 try {
2176 mListener.onInputDevicesChanged(info);
2177 } catch (RemoteException ex) {
2178 Slog.w(TAG, "Failed to notify process "
2179 + mPid + " that input devices changed, assuming it died.", ex);
2180 binderDied();
2181 }
2182 }
2183 }
Jeff Browna47425a2012-04-13 04:09:27 -07002184
Michael Wright39e5e942015-08-19 22:52:47 +01002185 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2186 private final int mPid;
2187 private final ITabletModeChangedListener mListener;
2188
2189 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2190 mPid = pid;
2191 mListener = listener;
2192 }
2193
2194 @Override
2195 public void binderDied() {
2196 if (DEBUG) {
2197 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2198 }
2199 onTabletModeChangedListenerDied(mPid);
2200 }
2201
2202 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2203 try {
2204 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2205 } catch (RemoteException ex) {
2206 Slog.w(TAG, "Failed to notify process " + mPid +
2207 " that tablet mode changed, assuming it died.", ex);
2208 binderDied();
2209 }
2210 }
2211 }
2212
Jeff Browna47425a2012-04-13 04:09:27 -07002213 private final class VibratorToken implements DeathRecipient {
2214 public final int mDeviceId;
2215 public final IBinder mToken;
2216 public final int mTokenValue;
2217
2218 public boolean mVibrating;
2219
2220 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2221 mDeviceId = deviceId;
2222 mToken = token;
2223 mTokenValue = tokenValue;
2224 }
2225
2226 @Override
2227 public void binderDied() {
2228 if (DEBUG) {
2229 Slog.d(TAG, "Vibrator token died.");
2230 }
2231 onVibratorTokenDied(this);
2232 }
2233 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002234
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002235 private class Shell extends ShellCommand {
2236 @Override
2237 public int onCommand(String cmd) {
2238 return onShellCommand(this, cmd);
2239 }
2240
2241 @Override
2242 public void onHelp() {
2243 final PrintWriter pw = getOutPrintWriter();
2244 pw.println("Input manager commands:");
2245 pw.println(" help");
2246 pw.println(" Print this help text.");
2247 pw.println("");
2248 pw.println(" setlayout IME_ID IME_SUPTYPE_HASH_CODE"
2249 + " DEVICE_DESCRIPTOR VENDOR_ID PRODUCT_ID KEYBOARD_DESCRIPTOR");
2250 pw.println(" Sets a keyboard layout for a given IME subtype and input device pair");
2251 }
2252 }
2253
Jeff Brown4ccb8232014-01-16 22:16:42 -08002254 private final class LocalService extends InputManagerInternal {
2255 @Override
2256 public void setDisplayViewports(
2257 DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
2258 setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
2259 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002260
2261 @Override
2262 public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
2263 return injectInputEventInternal(event, displayId, mode);
2264 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002265
2266 @Override
2267 public void setInteractive(boolean interactive) {
2268 nativeSetInteractive(mPtr, interactive);
2269 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002270
2271 @Override
2272 public void onInputMethodSubtypeChanged(int userId,
2273 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
2274 final SomeArgs someArgs = SomeArgs.obtain();
2275 someArgs.arg1 = inputMethodInfo;
2276 someArgs.arg2 = subtype;
2277 mHandler.obtainMessage(MSG_INPUT_METHOD_SUBTYPE_CHANGED, userId, 0, someArgs)
2278 .sendToTarget();
2279 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002280 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002281}