blob: 3793b911a0386bb1b56c1e5bdd8d1f11b99b04c7 [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 Yukawa23cbe852016-05-17 16:42:58 -070021import android.os.LocaleList;
Dianne Hackborn354736e2016-08-22 17:00:05 -070022import android.os.ShellCallback;
Adrian Roos99182342016-06-15 15:30:46 -070023import android.util.Log;
Jeff Brownca9bc702014-02-11 14:32:56 -080024import android.view.Display;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080025import com.android.internal.inputmethod.InputMethodSubtypeHandle;
Michael Wright39e5e942015-08-19 22:52:47 +010026import com.android.internal.os.SomeArgs;
Jeff Browncf39bdf2012-05-18 14:41:19 -070027import com.android.internal.R;
Michael Wrightb004b512017-01-18 18:09:29 +000028import com.android.internal.util.Preconditions;
Jeff Brown46b9ac02010-04-22 18:58:52 -070029import com.android.internal.util.XmlUtils;
Jeff Brown4ccb8232014-01-16 22:16:42 -080030import com.android.server.DisplayThread;
31import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070032import com.android.server.Watchdog;
Jeff Brown46b9ac02010-04-22 18:58:52 -070033
34import org.xmlpull.v1.XmlPullParser;
35
Jeff Browna3bc5652012-04-17 11:42:25 -070036import android.Manifest;
Jeff Browncf39bdf2012-05-18 14:41:19 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070040import android.bluetooth.BluetoothAdapter;
41import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070042import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070043import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070044import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070045import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070046import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070047import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070048import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070049import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070050import android.content.pm.ResolveInfo;
51import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070053import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070054import android.content.res.TypedArray;
55import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070056import android.database.ContentObserver;
Jeff Brown4ccb8232014-01-16 22:16:42 -080057import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070059import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080060import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070061import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080062import android.hardware.input.InputManagerInternal;
Michael Wright39e5e942015-08-19 22:52:47 +010063import android.hardware.input.ITabletModeChangedListener;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070064import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080065import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070066import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070067import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070069import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070070import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070071import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070072import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080073import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070074import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070075import android.os.RemoteException;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080076import android.os.ResultReceiver;
77import android.os.ShellCommand;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070078import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070079import android.provider.Settings;
80import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000081import android.text.TextUtils;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070083import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070084import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070085import android.view.IInputFilter;
86import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080087import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070088import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070089import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070090import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080091import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070092import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070093import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080094import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070095import android.view.WindowManagerPolicy;
Yohei Yukawab097b822015-12-01 10:43:08 -080096import android.view.inputmethod.InputMethodInfo;
97import android.view.inputmethod.InputMethodSubtype;
Jeff Brown46b9ac02010-04-22 18:58:52 -070098
Jeff Brown46b9ac02010-04-22 18:58:52 -070099import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700100import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700101import java.io.FileNotFoundException;
102import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700103import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700104import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700105import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700106import java.io.PrintWriter;
107import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000108import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700109import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700110import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100111import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000112import java.util.Locale;
Jeff Browna3bc5652012-04-17 11:42:25 -0700113
Adrian Roos99182342016-06-15 15:30:46 -0700114import libcore.io.IoUtils;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700115import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -0700116import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700117
118/*
119 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700120 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700121public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800122 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700123 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700124 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700125
Jeff Brown4532e612012-04-05 14:27:12 -0700126 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
127
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700128 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700129 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
130 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
131 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
132 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100133 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Yohei Yukawab097b822015-12-01 10:43:08 -0800134 private static final int MSG_INPUT_METHOD_SUBTYPE_CHANGED = 7;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700135
Jeff Brown4532e612012-04-05 14:27:12 -0700136 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000137 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700138
Jeff Brown46b9ac02010-04-22 18:58:52 -0700139 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700140 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700141
Adrian Roos99182342016-06-15 15:30:46 -0700142 private final File mDoubleTouchGestureEnableFile;
143
Jeff Browna9d131c2012-09-20 16:48:17 -0700144 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700145 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700146 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700147 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700148
Michael Wright39e5e942015-08-19 22:52:47 +0100149 private final Object mTabletModeLock = new Object();
150 // List of currently registered tablet mode changed listeners by process id
151 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
152 new SparseArray<>(); // guarded by mTabletModeLock
153 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
154 new ArrayList<>();
155
Jeff Browna3bc5652012-04-17 11:42:25 -0700156 // Persistent data store. Must be locked each time during use.
157 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700158
159 // List of currently registered input devices changed listeners by process id.
160 private Object mInputDevicesLock = new Object();
161 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
162 private InputDevice[] mInputDevices = new InputDevice[0];
163 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
164 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
165 private final ArrayList<InputDevicesChangedListenerRecord>
166 mTempInputDevicesChangedListenersToNotify =
167 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700168 private final ArrayList<InputDevice>
169 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
170 private boolean mKeyboardLayoutNotificationShown;
Michael Wrightd5f7ed92016-01-19 11:23:51 -0800171 private InputMethodSubtypeHandle mCurrentImeHandle;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700172
Jeff Browna47425a2012-04-13 04:09:27 -0700173 // State for vibrator tokens.
174 private Object mVibratorLock = new Object();
175 private HashMap<IBinder, VibratorToken> mVibratorTokens =
176 new HashMap<IBinder, VibratorToken>();
177 private int mNextVibratorTokenValue;
178
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700179 // State for the currently installed input filter.
180 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700181 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700182 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700183
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800184 private IWindow mFocusedWindow;
185 private boolean mFocusedWindowHasCapture;
186
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700188 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000189 private static native void nativeStart(long ptr);
190 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700191 int displayId, int rotation,
192 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700193 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
194 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700195
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700197 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700199 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000200 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700201 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000202 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700203 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000204 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800205 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000206 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
207 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Jeff Brownca9bc702014-02-11 14:32:56 -0800208 private static native int nativeInjectInputEvent(long ptr, InputEvent event, int displayId,
Jeff Brown0029c662011-03-30 02:25:18 -0700209 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
210 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800211 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000212 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
213 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
214 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
215 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700216 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000217 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700218 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeSetPointerSpeed(long ptr, int speed);
220 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700221 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800222 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000223 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700224 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000225 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
226 private static native void nativeReloadKeyboardLayouts(long ptr);
227 private static native void nativeReloadDeviceAliases(long ptr);
228 private static native String nativeDump(long ptr);
229 private static native void nativeMonitor(long ptr);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100230 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800231 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700232 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800233 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700234
Jeff Brownac143512012-04-05 18:57:33 -0700235 // Input event injection constants defined in InputDispatcher.h.
236 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
237 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
238 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
239 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
240
241 // Maximum number of milliseconds to wait for input event injection.
242 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
243
Jeff Brown6d0fec22010-07-23 21:28:06 -0700244 // Key states (may be returned by queries about the current state of a
245 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700246
Jeff Brown6d0fec22010-07-23 21:28:06 -0700247 /** The key state is unknown or the requested key itself is not supported. */
248 public static final int KEY_STATE_UNKNOWN = -1;
249
250 /** The key is up. /*/
251 public static final int KEY_STATE_UP = 0;
252
253 /** The key is down. */
254 public static final int KEY_STATE_DOWN = 1;
255
256 /** The key is down but is a virtual key press that is being emulated by the system. */
257 public static final int KEY_STATE_VIRTUAL = 2;
258
Jeff Brownc458ce92012-04-30 14:58:40 -0700259 /** Scan code: Mouse / trackball button. */
260 public static final int BTN_MOUSE = 0x110;
261
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700262 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700263 /** Switch code: Lid switch. When set, lid is shut. */
264 public static final int SW_LID = 0x00;
265
Michael Wright39e5e942015-08-19 22:52:47 +0100266 /** Switch code: Tablet mode switch.
267 * When set, the device is in tablet mode (i.e. no keyboard is connected).
268 */
269 public static final int SW_TABLET_MODE = 0x01;
270
Jeff Brownc458ce92012-04-30 14:58:40 -0700271 /** Switch code: Keypad slide. When set, keyboard is exposed. */
272 public static final int SW_KEYPAD_SLIDE = 0x0a;
273
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700274 /** Switch code: Headphone. When set, headphone is inserted. */
275 public static final int SW_HEADPHONE_INSERT = 0x02;
276
277 /** Switch code: Microphone. When set, microphone is inserted. */
278 public static final int SW_MICROPHONE_INSERT = 0x04;
279
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500280 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
281 public static final int SW_LINEOUT_INSERT = 0x06;
282
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700283 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
284 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
285
Michael Wright3818c922014-09-02 13:59:07 -0700286 /** Switch code: Camera lens cover. When set the lens is covered. */
287 public static final int SW_CAMERA_LENS_COVER = 0x09;
288
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700289 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100290 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700291 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
292 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
293 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500294 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700295 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
296 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500297 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700298 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700299
300 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
301 final boolean mUseDevInputEventForAudioJack;
302
Jeff Brown4ccb8232014-01-16 22:16:42 -0800303 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700304 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800305 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800306
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700307 mUseDevInputEventForAudioJack =
308 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
309 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
310 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700311 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800312
Adrian Roos99182342016-06-15 15:30:46 -0700313 String doubleTouchGestureEnablePath = context.getResources().getString(
314 R.string.config_doubleTouchGestureEnableFile);
315 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
316 new File(doubleTouchGestureEnablePath);
317
Jeff Brown4ccb8232014-01-16 22:16:42 -0800318 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700319 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700320
Jeff Browna9d131c2012-09-20 16:48:17 -0700321 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
322 mWindowManagerCallbacks = callbacks;
323 }
324
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700325 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
326 mWiredAccessoryCallbacks = callbacks;
327 }
328
Jeff Brown46b9ac02010-04-22 18:58:52 -0700329 public void start() {
330 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700331 nativeStart(mPtr);
332
333 // Add ourself to the Watchdog monitors.
334 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700335
336 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700337 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800338 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700339
Jeff Brownd4935962012-09-25 13:27:20 -0700340 mContext.registerReceiver(new BroadcastReceiver() {
341 @Override
342 public void onReceive(Context context, Intent intent) {
343 updatePointerSpeedFromSettings();
344 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800345 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700346 }
347 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
348
Jeff Brown1a84fd12011-06-02 01:26:32 -0700349 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700350 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800351 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700352 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700353
Matthew Xie96313142012-06-29 16:57:31 -0700354 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700355 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700356 if (DEBUG) {
357 Slog.d(TAG, "System ready.");
358 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700359 mNotificationManager = (NotificationManager)mContext.getSystemService(
360 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700361 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700362
363 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
364 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
365 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800366 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700367 filter.addDataScheme("package");
368 mContext.registerReceiver(new BroadcastReceiver() {
369 @Override
370 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700371 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700372 }
373 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700374
375 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
376 mContext.registerReceiver(new BroadcastReceiver() {
377 @Override
378 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700379 reloadDeviceAliases();
380 }
381 }, filter, null, mHandler);
382
Jeff Browncf39bdf2012-05-18 14:41:19 -0700383 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
384 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700385
386 if (mWiredAccessoryCallbacks != null) {
387 mWiredAccessoryCallbacks.systemReady();
388 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700389 }
390
391 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700392 if (DEBUG) {
393 Slog.d(TAG, "Reloading keyboard layouts.");
394 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700395 nativeReloadKeyboardLayouts(mPtr);
396 }
397
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700398 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700399 if (DEBUG) {
400 Slog.d(TAG, "Reloading device names.");
401 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700402 nativeReloadDeviceAliases(mPtr);
403 }
404
Jeff Brown4ccb8232014-01-16 22:16:42 -0800405 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Jeff Brownd728bf52012-09-08 18:05:28 -0700406 DisplayViewport externalTouchViewport) {
407 if (defaultViewport.valid) {
408 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700409 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700410
411 if (externalTouchViewport.valid) {
412 setDisplayViewport(true, externalTouchViewport);
413 } else if (defaultViewport.valid) {
414 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700415 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700416 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700417
Jeff Brownd728bf52012-09-08 18:05:28 -0700418 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
419 nativeSetDisplayViewport(mPtr, external,
420 viewport.displayId, viewport.orientation,
421 viewport.logicalFrame.left, viewport.logicalFrame.top,
422 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
423 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700424 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
425 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700426 }
Jeff Brownac143512012-04-05 18:57:33 -0700427
Jeff Brown6d0fec22010-07-23 21:28:06 -0700428 /**
429 * Gets the current state of a key or button by key code.
430 * @param deviceId The input device id, or -1 to consult all devices.
431 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
432 * consider all input sources. An input device is consulted if at least one of its
433 * non-class input source bits matches the specified source mask.
434 * @param keyCode The key code to check.
435 * @return The key state.
436 */
437 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700438 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700439 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700440
Jeff Brown6d0fec22010-07-23 21:28:06 -0700441 /**
442 * Gets the current state of a key or button by scan code.
443 * @param deviceId The input device id, or -1 to consult all devices.
444 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
445 * consider all input sources. An input device is consulted if at least one of its
446 * non-class input source bits matches the specified source mask.
447 * @param scanCode The scan code to check.
448 * @return The key state.
449 */
450 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700451 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700452 }
RoboErikfb290df2013-12-16 11:27:55 -0800453
Jeff Brown6d0fec22010-07-23 21:28:06 -0700454 /**
455 * Gets the current state of a switch by switch code.
456 * @param deviceId The input device id, or -1 to consult all devices.
457 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
458 * consider all input sources. An input device is consulted if at least one of its
459 * non-class input source bits matches the specified source mask.
460 * @param switchCode The switch code to check.
461 * @return The switch state.
462 */
463 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700464 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700465 }
466
Jeff Brown6d0fec22010-07-23 21:28:06 -0700467 /**
468 * Determines whether the specified key codes are supported by a particular device.
469 * @param deviceId The input device id, or -1 to consult all devices.
470 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
471 * consider all input sources. An input device is consulted if at least one of its
472 * non-class input source bits matches the specified source mask.
473 * @param keyCodes The array of key codes to check.
474 * @param keyExists An array at least as large as keyCodes whose entries will be set
475 * to true or false based on the presence or absence of support for the corresponding
476 * key codes.
477 * @return True if the lookup was successful, false otherwise.
478 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700479 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700480 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700481 if (keyCodes == null) {
482 throw new IllegalArgumentException("keyCodes must not be null.");
483 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700484 if (keyExists == null || keyExists.length < keyCodes.length) {
485 throw new IllegalArgumentException("keyExists must not be null and must be at "
486 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700487 }
RoboErikfb290df2013-12-16 11:27:55 -0800488
Jeff Brown4532e612012-04-05 14:27:12 -0700489 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700490 }
RoboErikfb290df2013-12-16 11:27:55 -0800491
Jeff Browna41ca772010-08-11 14:46:32 -0700492 /**
493 * Creates an input channel that will receive all input from the input dispatcher.
494 * @param inputChannelName The input channel name.
495 * @return The input channel.
496 */
497 public InputChannel monitorInput(String inputChannelName) {
498 if (inputChannelName == null) {
499 throw new IllegalArgumentException("inputChannelName must not be null.");
500 }
RoboErikfb290df2013-12-16 11:27:55 -0800501
Jeff Browna41ca772010-08-11 14:46:32 -0700502 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700503 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700504 inputChannels[0].dispose(); // don't need to retain the Java object reference
505 return inputChannels[1];
506 }
507
508 /**
509 * Registers an input channel so that it can be used as an input event target.
510 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800511 * @param inputWindowHandle The handle of the input window associated with the
512 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700513 */
Jeff Brown928e0542011-01-10 11:17:36 -0800514 public void registerInputChannel(InputChannel inputChannel,
515 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700516 if (inputChannel == null) {
517 throw new IllegalArgumentException("inputChannel must not be null.");
518 }
RoboErikfb290df2013-12-16 11:27:55 -0800519
Jeff Brown4532e612012-04-05 14:27:12 -0700520 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700521 }
RoboErikfb290df2013-12-16 11:27:55 -0800522
Jeff Browna41ca772010-08-11 14:46:32 -0700523 /**
524 * Unregisters an input channel.
525 * @param inputChannel The input channel to unregister.
526 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700527 public void unregisterInputChannel(InputChannel inputChannel) {
528 if (inputChannel == null) {
529 throw new IllegalArgumentException("inputChannel must not be null.");
530 }
RoboErikfb290df2013-12-16 11:27:55 -0800531
Jeff Brown4532e612012-04-05 14:27:12 -0700532 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700533 }
Jeff Brown0029c662011-03-30 02:25:18 -0700534
535 /**
536 * Sets an input filter that will receive all input events before they are dispatched.
537 * The input filter may then reinterpret input events or inject new ones.
538 *
539 * To ensure consistency, the input dispatcher automatically drops all events
540 * in progress whenever an input filter is installed or uninstalled. After an input
541 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
542 * Any events it attempts to send after it has been uninstalled will be dropped.
543 *
544 * @param filter The input filter, or null to remove the current filter.
545 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700546 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700547 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700548 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700549 if (oldFilter == filter) {
550 return; // nothing to do
551 }
552
553 if (oldFilter != null) {
554 mInputFilter = null;
555 mInputFilterHost.disconnectLocked();
556 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700557 try {
558 oldFilter.uninstall();
559 } catch (RemoteException re) {
560 /* ignore */
561 }
Jeff Brown0029c662011-03-30 02:25:18 -0700562 }
563
564 if (filter != null) {
565 mInputFilter = filter;
566 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700567 try {
568 filter.install(mInputFilterHost);
569 } catch (RemoteException re) {
570 /* ignore */
571 }
Jeff Brown0029c662011-03-30 02:25:18 -0700572 }
573
Jeff Brown4532e612012-04-05 14:27:12 -0700574 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700575 }
576 }
577
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700578 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700579 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brownca9bc702014-02-11 14:32:56 -0800580 return injectInputEventInternal(event, Display.DEFAULT_DISPLAY, mode);
581 }
582
583 private boolean injectInputEventInternal(InputEvent event, int displayId, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700584 if (event == null) {
585 throw new IllegalArgumentException("event must not be null");
586 }
Jeff Brownac143512012-04-05 18:57:33 -0700587 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
588 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
589 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
590 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700591 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700592
Jeff Brownac143512012-04-05 18:57:33 -0700593 final int pid = Binder.getCallingPid();
594 final int uid = Binder.getCallingUid();
595 final long ident = Binder.clearCallingIdentity();
596 final int result;
597 try {
Jeff Brownca9bc702014-02-11 14:32:56 -0800598 result = nativeInjectInputEvent(mPtr, event, displayId, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700599 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
600 } finally {
601 Binder.restoreCallingIdentity(ident);
602 }
603 switch (result) {
604 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
605 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
606 throw new SecurityException(
607 "Injecting to another application requires INJECT_EVENTS permission");
608 case INPUT_EVENT_INJECTION_SUCCEEDED:
609 return true;
610 case INPUT_EVENT_INJECTION_TIMED_OUT:
611 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
612 return false;
613 case INPUT_EVENT_INJECTION_FAILED:
614 default:
615 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
616 return false;
617 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700618 }
Jeff Brown0029c662011-03-30 02:25:18 -0700619
Jeff Brown8d608662010-08-30 03:02:23 -0700620 /**
621 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700622 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700623 * @return The input device or null if not found.
624 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700625 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700626 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700627 synchronized (mInputDevicesLock) {
628 final int count = mInputDevices.length;
629 for (int i = 0; i < count; i++) {
630 final InputDevice inputDevice = mInputDevices[i];
631 if (inputDevice.getId() == deviceId) {
632 return inputDevice;
633 }
634 }
635 }
636 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700637 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700638
Jeff Brown8d608662010-08-30 03:02:23 -0700639 /**
640 * Gets the ids of all input devices in the system.
641 * @return The input device ids.
642 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700643 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700644 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700645 synchronized (mInputDevicesLock) {
646 final int count = mInputDevices.length;
647 int[] ids = new int[count];
648 for (int i = 0; i < count; i++) {
649 ids[i] = mInputDevices[i].getId();
650 }
651 return ids;
652 }
653 }
654
Jeff Browndaa37532012-05-01 15:54:03 -0700655 /**
656 * Gets all input devices in the system.
657 * @return The array of input devices.
658 */
659 public InputDevice[] getInputDevices() {
660 synchronized (mInputDevicesLock) {
661 return mInputDevices;
662 }
663 }
664
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700665 @Override // Binder call
666 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
667 if (listener == null) {
668 throw new IllegalArgumentException("listener must not be null");
669 }
670
671 synchronized (mInputDevicesLock) {
672 int callingPid = Binder.getCallingPid();
673 if (mInputDevicesChangedListeners.get(callingPid) != null) {
674 throw new SecurityException("The calling process has already "
675 + "registered an InputDevicesChangedListener.");
676 }
677
678 InputDevicesChangedListenerRecord record =
679 new InputDevicesChangedListenerRecord(callingPid, listener);
680 try {
681 IBinder binder = listener.asBinder();
682 binder.linkToDeath(record, 0);
683 } catch (RemoteException ex) {
684 // give up
685 throw new RuntimeException(ex);
686 }
687
688 mInputDevicesChangedListeners.put(callingPid, record);
689 }
690 }
691
692 private void onInputDevicesChangedListenerDied(int pid) {
693 synchronized (mInputDevicesLock) {
694 mInputDevicesChangedListeners.remove(pid);
695 }
696 }
697
698 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700699 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
700 // Scan for changes.
701 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700702 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700703 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700704 final int numListeners;
705 final int[] deviceIdAndGeneration;
706 synchronized (mInputDevicesLock) {
707 if (!mInputDevicesChangedPending) {
708 return;
709 }
710 mInputDevicesChangedPending = false;
711
712 numListeners = mInputDevicesChangedListeners.size();
713 for (int i = 0; i < numListeners; i++) {
714 mTempInputDevicesChangedListenersToNotify.add(
715 mInputDevicesChangedListeners.valueAt(i));
716 }
717
718 final int numDevices = mInputDevices.length;
719 deviceIdAndGeneration = new int[numDevices * 2];
720 for (int i = 0; i < numDevices; i++) {
721 final InputDevice inputDevice = mInputDevices[i];
722 deviceIdAndGeneration[i * 2] = inputDevice.getId();
723 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700724
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700725 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700726 if (!containsInputDeviceWithDescriptor(oldInputDevices,
727 inputDevice.getDescriptor())) {
728 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
729 } else {
730 mTempFullKeyboards.add(inputDevice);
731 }
732 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700733 }
734 }
735
Jeff Browncf39bdf2012-05-18 14:41:19 -0700736 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700737 for (int i = 0; i < numListeners; i++) {
738 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
739 deviceIdAndGeneration);
740 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700741 mTempInputDevicesChangedListenersToNotify.clear();
742
743 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000744 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
745 final int numFullKeyboards = mTempFullKeyboards.size();
746 synchronized (mDataStore) {
747 for (int i = 0; i < numFullKeyboards; i++) {
748 final InputDevice inputDevice = mTempFullKeyboards.get(i);
749 String layout =
750 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
751 if (layout == null) {
752 layout = getDefaultKeyboardLayout(inputDevice);
753 if (layout != null) {
754 setCurrentKeyboardLayoutForInputDevice(
755 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700756 }
757 }
Michael Wright07483422015-10-30 16:20:13 +0000758 if (layout == null) {
759 keyboardsMissingLayout.add(inputDevice);
760 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700761 }
Michael Wright07483422015-10-30 16:20:13 +0000762 }
763
764 if (mNotificationManager != null) {
765 if (!keyboardsMissingLayout.isEmpty()) {
766 if (keyboardsMissingLayout.size() > 1) {
767 // We have more than one keyboard missing a layout, so drop the
768 // user at the generic input methods page so they can pick which
769 // one to set.
770 showMissingKeyboardLayoutNotification(null);
771 } else {
772 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700773 }
774 } else if (mKeyboardLayoutNotificationShown) {
775 hideMissingKeyboardLayoutNotification();
776 }
777 }
778 mTempFullKeyboards.clear();
779 }
780
Michael Wright07483422015-10-30 16:20:13 +0000781 private String getDefaultKeyboardLayout(final InputDevice d) {
782 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
783 // If our locale doesn't have a language for some reason, then we don't really have a
784 // reasonable default.
785 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
786 return null;
787 }
788 final List<KeyboardLayout> layouts = new ArrayList<>();
789 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
790 @Override
791 public void visitKeyboardLayout(Resources resources,
792 int keyboardLayoutResId, KeyboardLayout layout) {
793 // Only select a default when we know the layout is appropriate. For now, this
794 // means its a custom layout for a specific keyboard.
795 if (layout.getVendorId() != d.getVendorId()
796 || layout.getProductId() != d.getProductId()) {
797 return;
798 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800799 final LocaleList locales = layout.getLocales();
800 final int numLocales = locales.size();
801 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
802 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000803 layouts.add(layout);
804 break;
805 }
806 }
807 }
808 });
809
810 if (layouts.isEmpty()) {
811 return null;
812 }
813
814 // First sort so that ones with higher priority are listed at the top
815 Collections.sort(layouts);
816 // Next we want to try to find an exact match of language, country and variant.
817 final int N = layouts.size();
818 for (int i = 0; i < N; i++) {
819 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800820 final LocaleList locales = layout.getLocales();
821 final int numLocales = locales.size();
822 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
823 final Locale locale = locales.get(localeIndex);
824 if (locale.getCountry().equals(systemLocale.getCountry())
825 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000826 return layout.getDescriptor();
827 }
828 }
829 }
830 // Then try an exact match of language and country
831 for (int i = 0; i < N; i++) {
832 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800833 final LocaleList locales = layout.getLocales();
834 final int numLocales = locales.size();
835 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
836 final Locale locale = locales.get(localeIndex);
837 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000838 return layout.getDescriptor();
839 }
840 }
841 }
842
843 // Give up and just use the highest priority layout with matching language
844 return layouts.get(0).getDescriptor();
845 }
846
847 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
848 // Different languages are never compatible
849 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
850 return false;
851 }
852 // If both the system and the keyboard layout have a country specifier, they must be equal.
853 if (!TextUtils.isEmpty(systemLocale.getCountry())
854 && !TextUtils.isEmpty(keyboardLocale.getCountry())
855 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
856 return false;
857 }
858 return true;
859 }
860
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800861 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700862 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
863 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800864 if (inputDeviceDescriptor == null) {
865 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
866 }
867
868 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700869 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800870 }
871 }
872
873 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700874 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800875 TouchCalibration calibration) {
876 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
877 "setTouchCalibrationForInputDevice()")) {
878 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
879 }
880 if (inputDeviceDescriptor == null) {
881 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
882 }
883 if (calibration == null) {
884 throw new IllegalArgumentException("calibration must not be null");
885 }
Jason Gerecked5220742014-03-10 09:47:59 -0700886 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
887 throw new IllegalArgumentException("surfaceRotation value out of bounds");
888 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800889
890 synchronized (mDataStore) {
891 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700892 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
893 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800894 nativeReloadCalibration(mPtr);
895 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800896 } finally {
897 mDataStore.saveIfNeeded();
898 }
899 }
900 }
901
Michael Wright39e5e942015-08-19 22:52:47 +0100902 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100903 public int isInTabletMode() {
904 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
905 "isInTabletMode()")) {
906 throw new SecurityException("Requires TABLET_MODE permission");
907 }
908 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
909 }
910
911 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100912 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100913 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100914 "registerTabletModeChangedListener()")) {
915 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
916 }
917 if (listener == null) {
918 throw new IllegalArgumentException("listener must not be null");
919 }
920
921 synchronized (mTabletModeLock) {
922 final int callingPid = Binder.getCallingPid();
923 if (mTabletModeChangedListeners.get(callingPid) != null) {
924 throw new IllegalStateException("The calling process has already registered "
925 + "a TabletModeChangedListener.");
926 }
927 TabletModeChangedListenerRecord record =
928 new TabletModeChangedListenerRecord(callingPid, listener);
929 try {
930 IBinder binder = listener.asBinder();
931 binder.linkToDeath(record, 0);
932 } catch (RemoteException ex) {
933 throw new RuntimeException(ex);
934 }
935 mTabletModeChangedListeners.put(callingPid, record);
936 }
937 }
938
939 private void onTabletModeChangedListenerDied(int pid) {
940 synchronized (mTabletModeLock) {
941 mTabletModeChangedListeners.remove(pid);
942 }
943 }
944
945 // Must be called on handler
946 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
947 mTempTabletModeChangedListenersToNotify.clear();
948 final int numListeners;
949 synchronized (mTabletModeLock) {
950 numListeners = mTabletModeChangedListeners.size();
951 for (int i = 0; i < numListeners; i++) {
952 mTempTabletModeChangedListenersToNotify.add(
953 mTabletModeChangedListeners.valueAt(i));
954 }
955 }
956 for (int i = 0; i < numListeners; i++) {
957 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
958 whenNanos, inTabletMode);
959 }
960 }
961
Jeff Browncf39bdf2012-05-18 14:41:19 -0700962 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700963 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700964 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700965 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700966 if (device != null) {
967 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700968 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700969 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
970 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
971 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
972 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
973 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700974
975 Resources r = mContext.getResources();
976 Notification notification = new Notification.Builder(mContext)
977 .setContentTitle(r.getString(
978 R.string.select_keyboard_layout_notification_title))
979 .setContentText(r.getString(
980 R.string.select_keyboard_layout_notification_message))
Michael Wrightc93fbd12014-09-22 20:07:59 -0700981 .setContentIntent(keyboardLayoutIntent)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700982 .setSmallIcon(R.drawable.ic_settings_language)
983 .setPriority(Notification.PRIORITY_LOW)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700984 .setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200985 com.android.internal.R.color.system_notification_accent_color))
Jeff Browncf39bdf2012-05-18 14:41:19 -0700986 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700987 mNotificationManager.notifyAsUser(null,
988 R.string.select_keyboard_layout_notification_title,
989 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700990 mKeyboardLayoutNotificationShown = true;
991 }
992 }
993
994 // Must be called on handler.
995 private void hideMissingKeyboardLayoutNotification() {
996 if (mKeyboardLayoutNotificationShown) {
997 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700998 mNotificationManager.cancelAsUser(null,
999 R.string.select_keyboard_layout_notification_title,
1000 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001001 }
1002 }
1003
1004 // Must be called on handler.
1005 private void updateKeyboardLayouts() {
1006 // Scan all input devices state for keyboard layouts that have been uninstalled.
1007 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1008 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1009 @Override
Michael Wright07483422015-10-30 16:20:13 +00001010 public void visitKeyboardLayout(Resources resources,
1011 int keyboardLayoutResId, KeyboardLayout layout) {
1012 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001013 }
1014 });
1015 synchronized (mDataStore) {
1016 try {
1017 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1018 } finally {
1019 mDataStore.saveIfNeeded();
1020 }
1021 }
1022
1023 // Reload keyboard layouts.
1024 reloadKeyboardLayouts();
1025 }
1026
Jeff Browncf39bdf2012-05-18 14:41:19 -07001027 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1028 String descriptor) {
1029 final int numDevices = inputDevices.length;
1030 for (int i = 0; i < numDevices; i++) {
1031 final InputDevice inputDevice = inputDevices[i];
1032 if (inputDevice.getDescriptor().equals(descriptor)) {
1033 return true;
1034 }
1035 }
1036 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001037 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001038
1039 @Override // Binder call
1040 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001041 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1042 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1043 @Override
Michael Wright07483422015-10-30 16:20:13 +00001044 public void visitKeyboardLayout(Resources resources,
1045 int keyboardLayoutResId, KeyboardLayout layout) {
1046 list.add(layout);
1047 }
1048 });
1049 return list.toArray(new KeyboardLayout[list.size()]);
1050 }
1051
Michael Wrightb0e804a2016-01-04 16:48:53 -05001052 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001053 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1054 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001055 final String[] enabledLayoutDescriptors =
1056 getEnabledKeyboardLayoutsForInputDevice(identifier);
1057 final ArrayList<KeyboardLayout> enabledLayouts =
1058 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1059 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001060 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1061 boolean mHasSeenDeviceSpecificLayout;
1062
1063 @Override
1064 public void visitKeyboardLayout(Resources resources,
1065 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001066 // First check if it's enabled. If the keyboard layout is enabled then we always
1067 // want to return it as a possible layout for the device.
1068 for (String s : enabledLayoutDescriptors) {
1069 if (s != null && s.equals(layout.getDescriptor())) {
1070 enabledLayouts.add(layout);
1071 return;
1072 }
1073 }
1074 // Next find any potential layouts that aren't yet enabled for the device. For
1075 // devices that have special layouts we assume there's a reason that the generic
1076 // layouts don't work for them so we don't want to return them since it's likely
1077 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001078 if (layout.getVendorId() == identifier.getVendorId()
1079 && layout.getProductId() == identifier.getProductId()) {
1080 if (!mHasSeenDeviceSpecificLayout) {
1081 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001082 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001083 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001084 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001085 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1086 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001087 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001088 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001089 }
1090 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001091 final int enabledLayoutSize = enabledLayouts.size();
1092 final int potentialLayoutSize = potentialLayouts.size();
1093 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1094 enabledLayouts.toArray(layouts);
1095 for (int i = 0; i < potentialLayoutSize; i++) {
1096 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1097 }
1098 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001099 }
1100
1101 @Override // Binder call
1102 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1103 if (keyboardLayoutDescriptor == null) {
1104 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1105 }
1106
Jeff Brown6ec6f792012-04-17 16:52:41 -07001107 final KeyboardLayout[] result = new KeyboardLayout[1];
1108 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1109 @Override
Michael Wright07483422015-10-30 16:20:13 +00001110 public void visitKeyboardLayout(Resources resources,
1111 int keyboardLayoutResId, KeyboardLayout layout) {
1112 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001113 }
1114 });
1115 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001116 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001117 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001118 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001119 return result[0];
1120 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001121
Jeff Brown6ec6f792012-04-17 16:52:41 -07001122 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001123 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001124 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1125 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001126 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1127 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001128 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1129 final int priority = resolveInfo.priority;
1130 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001131 }
1132 }
1133
Jeff Brown6ec6f792012-04-17 16:52:41 -07001134 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1135 KeyboardLayoutVisitor visitor) {
1136 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1137 if (d != null) {
1138 final PackageManager pm = mContext.getPackageManager();
1139 try {
1140 ActivityInfo receiver = pm.getReceiverInfo(
1141 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001142 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001143 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1144 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001145 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001146 } catch (NameNotFoundException ex) {
1147 }
1148 }
1149 }
1150
1151 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001152 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001153 Bundle metaData = receiver.metaData;
1154 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001155 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001156 }
1157
1158 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1159 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001160 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001161 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001162 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001163 }
1164
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001165 CharSequence receiverLabel = receiver.loadLabel(pm);
1166 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001167 int priority;
1168 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1169 priority = requestedPriority;
1170 } else {
1171 priority = 0;
1172 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001173
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001174 try {
1175 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1176 XmlResourceParser parser = resources.getXml(configResId);
1177 try {
1178 XmlUtils.beginDocument(parser, "keyboard-layouts");
1179
1180 for (;;) {
1181 XmlUtils.nextElement(parser);
1182 String element = parser.getName();
1183 if (element == null) {
1184 break;
1185 }
1186 if (element.equals("keyboard-layout")) {
1187 TypedArray a = resources.obtainAttributes(
1188 parser, com.android.internal.R.styleable.KeyboardLayout);
1189 try {
1190 String name = a.getString(
1191 com.android.internal.R.styleable.KeyboardLayout_name);
1192 String label = a.getString(
1193 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001194 int keyboardLayoutResId = a.getResourceId(
1195 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1196 0);
Michael Wright07483422015-10-30 16:20:13 +00001197 String languageTags = a.getString(
1198 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001199 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001200 int vid = a.getInt(
1201 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1202 int pid = a.getInt(
1203 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1204
Jeff Brown2f095762012-05-10 21:29:33 -07001205 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001206 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001207 + "attributes in keyboard layout "
1208 + "resource from receiver "
1209 + receiver.packageName + "/" + receiver.name);
1210 } else {
1211 String descriptor = KeyboardLayoutDescriptor.format(
1212 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001213 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001214 KeyboardLayout layout = new KeyboardLayout(
1215 descriptor, label, collection, priority,
1216 locales, vid, pid);
1217 visitor.visitKeyboardLayout(
1218 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001219 }
1220 }
1221 } finally {
1222 a.recycle();
1223 }
1224 } else {
Michael Wright07483422015-10-30 16:20:13 +00001225 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001226 + "' in keyboard layout resource from receiver "
1227 + receiver.packageName + "/" + receiver.name);
1228 }
1229 }
1230 } finally {
1231 parser.close();
1232 }
1233 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001234 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001235 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001236 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001237 }
1238
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001239 @NonNull
1240 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001241 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001242 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001243 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001244 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001245 }
1246
RoboErikfb290df2013-12-16 11:27:55 -08001247 /**
1248 * Builds a layout descriptor for the vendor/product. This returns the
1249 * descriptor for ids that aren't useful (such as the default 0, 0).
1250 */
1251 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1252 if (identifier == null || identifier.getDescriptor() == null) {
1253 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001254 }
1255
RoboErikfb290df2013-12-16 11:27:55 -08001256 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1257 return identifier.getDescriptor();
1258 }
1259 StringBuilder bob = new StringBuilder();
1260 bob.append("vendor:").append(identifier.getVendorId());
1261 bob.append(",product:").append(identifier.getProductId());
1262 return bob.toString();
1263 }
1264
1265 @Override // Binder call
1266 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1267
1268 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001269 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001270 String layout = null;
1271 // try loading it using the layout descriptor if we have it
1272 layout = mDataStore.getCurrentKeyboardLayout(key);
1273 if (layout == null && !key.equals(identifier.getDescriptor())) {
1274 // if it doesn't exist fall back to the device descriptor
1275 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1276 }
1277 if (DEBUG) {
1278 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1279 + layout);
1280 }
1281 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001282 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001283 }
1284
1285 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001286 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001287 String keyboardLayoutDescriptor) {
1288 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001289 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001290 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1291 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001292 if (keyboardLayoutDescriptor == null) {
1293 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1294 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001295
RoboErikfb290df2013-12-16 11:27:55 -08001296 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001297 synchronized (mDataStore) {
1298 try {
RoboErikfb290df2013-12-16 11:27:55 -08001299 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1300 if (DEBUG) {
1301 Slog.d(TAG, "Saved keyboard layout using " + key);
1302 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001303 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1304 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001305 } finally {
1306 mDataStore.saveIfNeeded();
1307 }
1308 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001309 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001310
Jeff Browncf39bdf2012-05-18 14:41:19 -07001311 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001312 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001313 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001314 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001315 String[] layouts = mDataStore.getKeyboardLayouts(key);
1316 if ((layouts == null || layouts.length == 0)
1317 && !key.equals(identifier.getDescriptor())) {
1318 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1319 }
1320 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001321 }
1322 }
1323
1324 @Override // Binder call
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001325 @Nullable
1326 public KeyboardLayout getKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1327 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype) {
1328 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1329 String key = getLayoutDescriptor(identifier);
1330 final String keyboardLayoutDescriptor;
1331 synchronized (mDataStore) {
1332 keyboardLayoutDescriptor = mDataStore.getKeyboardLayout(key, handle);
1333 }
1334
1335 if (keyboardLayoutDescriptor == null) {
1336 return null;
1337 }
1338
1339 final KeyboardLayout[] result = new KeyboardLayout[1];
1340 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1341 @Override
1342 public void visitKeyboardLayout(Resources resources,
1343 int keyboardLayoutResId, KeyboardLayout layout) {
1344 result[0] = layout;
1345 }
1346 });
1347 if (result[0] == null) {
1348 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
1349 + keyboardLayoutDescriptor + "'.");
1350 }
1351 return result[0];
1352 }
1353
1354 @Override
1355 public void setKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1356 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype,
1357 String keyboardLayoutDescriptor) {
1358 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1359 "setKeyboardLayoutForInputDevice()")) {
1360 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1361 }
1362 if (keyboardLayoutDescriptor == null) {
1363 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1364 }
Yohei Yukawa46ac35d2016-04-20 16:59:45 -07001365 if (imeInfo == null) {
1366 throw new IllegalArgumentException("imeInfo must not be null");
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001367 }
1368 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1369 setKeyboardLayoutForInputDeviceInner(identifier, handle, keyboardLayoutDescriptor);
1370 }
1371
1372 private void setKeyboardLayoutForInputDeviceInner(InputDeviceIdentifier identifier,
1373 InputMethodSubtypeHandle imeHandle, String keyboardLayoutDescriptor) {
1374 String key = getLayoutDescriptor(identifier);
1375 synchronized (mDataStore) {
1376 try {
1377 if (mDataStore.setKeyboardLayout(key, imeHandle, keyboardLayoutDescriptor)) {
1378 if (DEBUG) {
1379 Slog.d(TAG, "Set keyboard layout " + keyboardLayoutDescriptor +
1380 " for subtype " + imeHandle + " and device " + identifier +
1381 " using key " + key);
1382 }
1383 if (imeHandle.equals(mCurrentImeHandle)) {
1384 if (DEBUG) {
1385 Slog.d(TAG, "Layout for current subtype changed, switching layout");
1386 }
1387 SomeArgs args = SomeArgs.obtain();
1388 args.arg1 = identifier;
1389 args.arg2 = imeHandle;
1390 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, args).sendToTarget();
1391 }
1392 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1393 }
1394 } finally {
1395 mDataStore.saveIfNeeded();
1396 }
1397 }
1398 }
1399
1400 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001401 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001402 String keyboardLayoutDescriptor) {
1403 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1404 "addKeyboardLayoutForInputDevice()")) {
1405 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1406 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001407 if (keyboardLayoutDescriptor == null) {
1408 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1409 }
1410
RoboErikfb290df2013-12-16 11:27:55 -08001411 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001412 synchronized (mDataStore) {
1413 try {
RoboErikfb290df2013-12-16 11:27:55 -08001414 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1415 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1416 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1417 }
1418 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001419 && !Objects.equal(oldLayout, mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001420 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1421 }
1422 } finally {
1423 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001424 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001425 }
1426 }
1427
1428 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001429 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001430 String keyboardLayoutDescriptor) {
1431 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1432 "removeKeyboardLayoutForInputDevice()")) {
1433 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1434 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001435 if (keyboardLayoutDescriptor == null) {
1436 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1437 }
1438
RoboErikfb290df2013-12-16 11:27:55 -08001439 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001440 synchronized (mDataStore) {
1441 try {
RoboErikfb290df2013-12-16 11:27:55 -08001442 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1443 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1444 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1445 }
1446 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1447 if (!key.equals(identifier.getDescriptor())) {
1448 // We need to remove from both places to ensure it is gone
1449 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1450 keyboardLayoutDescriptor);
1451 }
1452 if (removed && !Objects.equal(oldLayout,
1453 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001454 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1455 }
1456 } finally {
1457 mDataStore.saveIfNeeded();
1458 }
1459 }
1460 }
1461
Yohei Yukawab097b822015-12-01 10:43:08 -08001462 // Must be called on handler.
1463 private void handleSwitchInputMethodSubtype(int userId,
1464 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1465 if (DEBUG) {
1466 Slog.i(TAG, "InputMethodSubtype changed: userId=" + userId
1467 + " ime=" + inputMethodInfo + " subtype=" + subtype);
1468 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001469 if (inputMethodInfo == null) {
1470 Slog.d(TAG, "No InputMethod is running, ignoring change");
1471 return;
1472 }
1473 if (subtype != null && !"keyboard".equals(subtype.getMode())) {
1474 Slog.d(TAG, "InputMethodSubtype changed to non-keyboard subtype, ignoring change");
1475 return;
1476 }
1477 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(inputMethodInfo, subtype);
1478 if (!handle.equals(mCurrentImeHandle)) {
1479 mCurrentImeHandle = handle;
1480 handleSwitchKeyboardLayout(null, handle);
1481 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001482 }
1483
1484 // Must be called on handler.
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001485 private void handleSwitchKeyboardLayout(@Nullable InputDeviceIdentifier identifier,
1486 InputMethodSubtypeHandle handle) {
1487 synchronized (mInputDevicesLock) {
1488 for (InputDevice device : mInputDevices) {
1489 if (identifier != null && !device.getIdentifier().equals(identifier) ||
1490 !device.isFullKeyboard()) {
1491 continue;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001492 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001493 String key = getLayoutDescriptor(device.getIdentifier());
1494 boolean changed = false;
1495 synchronized (mDataStore) {
1496 try {
1497 if (mDataStore.switchKeyboardLayout(key, handle)) {
1498 changed = true;
1499 }
1500 } finally {
1501 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001502 }
1503 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001504 if (changed) {
1505 reloadKeyboardLayouts();
1506 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001507 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001508 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001509 }
1510
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001511 public void setInputWindows(InputWindowHandle[] windowHandles,
1512 InputWindowHandle focusedWindowHandle) {
1513 final IWindow newFocusedWindow =
1514 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1515 if (mFocusedWindow != newFocusedWindow) {
1516 mFocusedWindow = newFocusedWindow;
1517 if (mFocusedWindowHasCapture) {
1518 setPointerCapture(false);
1519 }
1520 }
Jeff Brown4532e612012-04-05 14:27:12 -07001521 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001522 }
RoboErikfb290df2013-12-16 11:27:55 -08001523
Jeff Brown9302c872011-07-13 22:51:29 -07001524 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001525 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001526 }
RoboErikfb290df2013-12-16 11:27:55 -08001527
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001528 @Override
1529 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1530 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1531 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1532 + windowToken);
1533 return;
1534 }
1535 if (mFocusedWindowHasCapture == enabled) {
1536 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1537 return;
1538 }
1539 setPointerCapture(enabled);
1540 try {
1541 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1542 } catch (RemoteException ex) {
1543 /* ignore */
1544 }
1545 }
1546
1547 private void setPointerCapture(boolean enabled) {
1548 mFocusedWindowHasCapture = enabled;
1549 nativeSetPointerCapture(mPtr, enabled);
1550 }
1551
Jeff Brown349703e2010-06-22 01:27:15 -07001552 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001553 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001554 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001555
1556 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001557 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001558 }
1559
Jeff Browne6504122010-09-27 14:52:15 -07001560 /**
1561 * Atomically transfers touch focus from one window to another as identified by
1562 * their input channels. It is possible for multiple windows to have
1563 * touch focus if they support split touch dispatch
1564 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1565 * method only transfers touch focus of the specified window without affecting
1566 * other windows that may also have touch focus at the same time.
1567 * @param fromChannel The channel of a window that currently has touch focus.
1568 * @param toChannel The channel of the window that should receive touch focus in
1569 * place of the first.
1570 * @return True if the transfer was successful. False if the window with the
1571 * specified channel did not actually have touch focus at the time of the request.
1572 */
1573 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1574 if (fromChannel == null) {
1575 throw new IllegalArgumentException("fromChannel must not be null.");
1576 }
1577 if (toChannel == null) {
1578 throw new IllegalArgumentException("toChannel must not be null.");
1579 }
Jeff Brown4532e612012-04-05 14:27:12 -07001580 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001581 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001582
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001583 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001584 public void tryPointerSpeed(int speed) {
1585 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1586 "tryPointerSpeed()")) {
1587 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1588 }
1589
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001590 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1591 throw new IllegalArgumentException("speed out of range");
1592 }
1593
Jeff Brownac143512012-04-05 18:57:33 -07001594 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001595 }
1596
1597 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001598 int speed = getPointerSpeedSetting();
1599 setPointerSpeedUnchecked(speed);
1600 }
1601
1602 private void setPointerSpeedUnchecked(int speed) {
1603 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1604 InputManager.MAX_POINTER_SPEED);
1605 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001606 }
1607
1608 private void registerPointerSpeedSettingObserver() {
1609 mContext.getContentResolver().registerContentObserver(
1610 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001611 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001612 @Override
1613 public void onChange(boolean selfChange) {
1614 updatePointerSpeedFromSettings();
1615 }
Jeff Brownd4935962012-09-25 13:27:20 -07001616 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001617 }
1618
Jeff Brownac143512012-04-05 18:57:33 -07001619 private int getPointerSpeedSetting() {
1620 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001621 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001622 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1623 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001624 } catch (SettingNotFoundException snfe) {
1625 }
1626 return speed;
1627 }
1628
Jeff Browndaf4a122011-08-26 17:14:14 -07001629 public void updateShowTouchesFromSettings() {
1630 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001631 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001632 }
1633
1634 private void registerShowTouchesSettingObserver() {
1635 mContext.getContentResolver().registerContentObserver(
1636 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001637 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001638 @Override
1639 public void onChange(boolean selfChange) {
1640 updateShowTouchesFromSettings();
1641 }
Jeff Brownd4935962012-09-25 13:27:20 -07001642 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001643 }
1644
Jun Mukaie4e75da2015-12-15 16:19:20 -08001645 public void updateAccessibilityLargePointerFromSettings() {
1646 final int accessibilityConfig = Settings.Secure.getIntForUser(
1647 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1648 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001649 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001650 nativeReloadPointerIcons(mPtr);
1651 }
1652
Jun Mukai19a56012015-11-24 11:25:52 -08001653 private void registerAccessibilityLargePointerSettingObserver() {
1654 mContext.getContentResolver().registerContentObserver(
1655 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1656 new ContentObserver(mHandler) {
1657 @Override
1658 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001659 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001660 }
1661 }, UserHandle.USER_ALL);
1662 }
1663
Jeff Browndaf4a122011-08-26 17:14:14 -07001664 private int getShowTouchesSetting(int defaultValue) {
1665 int result = defaultValue;
1666 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001667 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1668 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001669 } catch (SettingNotFoundException snfe) {
1670 }
1671 return result;
1672 }
1673
Jeff Browna47425a2012-04-13 04:09:27 -07001674 // Binder call
1675 @Override
1676 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1677 if (repeat >= pattern.length) {
1678 throw new ArrayIndexOutOfBoundsException();
1679 }
1680
1681 VibratorToken v;
1682 synchronized (mVibratorLock) {
1683 v = mVibratorTokens.get(token);
1684 if (v == null) {
1685 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1686 try {
1687 token.linkToDeath(v, 0);
1688 } catch (RemoteException ex) {
1689 // give up
1690 throw new RuntimeException(ex);
1691 }
1692 mVibratorTokens.put(token, v);
1693 }
1694 }
1695
1696 synchronized (v) {
1697 v.mVibrating = true;
1698 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1699 }
1700 }
1701
1702 // Binder call
1703 @Override
1704 public void cancelVibrate(int deviceId, IBinder token) {
1705 VibratorToken v;
1706 synchronized (mVibratorLock) {
1707 v = mVibratorTokens.get(token);
1708 if (v == null || v.mDeviceId != deviceId) {
1709 return; // nothing to cancel
1710 }
1711 }
1712
1713 cancelVibrateIfNeeded(v);
1714 }
1715
1716 void onVibratorTokenDied(VibratorToken v) {
1717 synchronized (mVibratorLock) {
1718 mVibratorTokens.remove(v.mToken);
1719 }
1720
1721 cancelVibrateIfNeeded(v);
1722 }
1723
1724 private void cancelVibrateIfNeeded(VibratorToken v) {
1725 synchronized (v) {
1726 if (v.mVibrating) {
1727 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1728 v.mVibrating = false;
1729 }
1730 }
1731 }
1732
Jun Mukai19a56012015-11-24 11:25:52 -08001733 // Binder call
1734 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001735 public void setPointerIconType(int iconId) {
1736 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001737 }
Jun Mukai1db53972015-09-11 18:08:31 -07001738
Jun Mukaid4eaef72015-10-30 15:54:33 -07001739 // Binder call
1740 @Override
1741 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001742 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001743 nativeSetCustomPointerIcon(mPtr, icon);
1744 }
1745
Jeff Brown4532e612012-04-05 14:27:12 -07001746 @Override
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001747 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001748 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001749 != PackageManager.PERMISSION_GRANTED) {
1750 pw.println("Permission Denial: can't dump InputManager from from pid="
1751 + Binder.getCallingPid()
1752 + ", uid=" + Binder.getCallingUid());
1753 return;
1754 }
1755
1756 pw.println("INPUT MANAGER (dumpsys input)\n");
1757 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001758 if (dumpStr != null) {
1759 pw.println(dumpStr);
1760 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001761 pw.println(" Keyboard Layouts:");
1762 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1763 @Override
1764 public void visitKeyboardLayout(Resources resources,
1765 int keyboardLayoutResId, KeyboardLayout layout) {
1766 pw.println(" \"" + layout + "\": " + layout.getDescriptor());
1767 }
1768 });
1769 pw.println();
1770 synchronized(mDataStore) {
1771 mDataStore.dump(pw, " ");
1772 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001773 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001774
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001775 @Override
1776 public void onShellCommand(FileDescriptor in, FileDescriptor out,
Dianne Hackborn354736e2016-08-22 17:00:05 -07001777 FileDescriptor err, String[] args, ShellCallback callback,
1778 ResultReceiver resultReceiver) {
1779 (new Shell()).exec(this, in, out, err, args, callback, resultReceiver);
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001780 }
1781
1782 public int onShellCommand(Shell shell, String cmd) {
1783 if (TextUtils.isEmpty(cmd)) {
1784 shell.onHelp();
1785 return 1;
1786 }
1787 if (cmd.equals("setlayout")) {
1788 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1789 "onShellCommand()")) {
1790 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1791 }
1792 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(
1793 shell.getNextArgRequired(), Integer.parseInt(shell.getNextArgRequired()));
1794 String descriptor = shell.getNextArgRequired();
1795 int vid = Integer.decode(shell.getNextArgRequired());
1796 int pid = Integer.decode(shell.getNextArgRequired());
1797 InputDeviceIdentifier id = new InputDeviceIdentifier(descriptor, vid, pid);
1798 setKeyboardLayoutForInputDeviceInner(id, handle, shell.getNextArgRequired());
1799 }
1800 return 0;
1801 }
1802
1803
Jeff Brownac143512012-04-05 18:57:33 -07001804 private boolean checkCallingPermission(String permission, String func) {
1805 // Quick check: if the calling permission is me, it's all okay.
1806 if (Binder.getCallingPid() == Process.myPid()) {
1807 return true;
1808 }
1809
1810 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1811 return true;
1812 }
1813 String msg = "Permission Denial: " + func + " from pid="
1814 + Binder.getCallingPid()
1815 + ", uid=" + Binder.getCallingUid()
1816 + " requires " + permission;
1817 Slog.w(TAG, msg);
1818 return false;
1819 }
1820
Jeff Brown4532e612012-04-05 14:27:12 -07001821 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001822 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001823 public void monitor() {
1824 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001825 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001826 }
1827
Jeff Brown4532e612012-04-05 14:27:12 -07001828 // Native callback.
1829 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001830 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001831 }
1832
1833 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001834 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1835 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001836 if (!mInputDevicesChangedPending) {
1837 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001838 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1839 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001840 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001841
1842 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001843 }
1844 }
1845
1846 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001847 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1848 if (DEBUG) {
1849 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1850 + ", mask=" + Integer.toHexString(switchMask));
1851 }
1852
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001853 if ((switchMask & SW_LID_BIT) != 0) {
1854 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001855 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001856 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001857
Michael Wright3818c922014-09-02 13:59:07 -07001858 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001859 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001860 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1861 }
1862
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001863 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1864 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1865 switchMask);
1866 }
Michael Wright39e5e942015-08-19 22:52:47 +01001867
Michael Wright9209c9c2015-09-03 17:57:01 +01001868 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001869 SomeArgs args = SomeArgs.obtain();
1870 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1871 args.argi2 = (int) (whenNanos >> 32);
1872 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1873 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1874 args).sendToTarget();
1875 }
Jeff Brown4532e612012-04-05 14:27:12 -07001876 }
1877
1878 // Native callback.
1879 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001880 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001881 }
1882
1883 // Native callback.
1884 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001885 InputWindowHandle inputWindowHandle, String reason) {
1886 return mWindowManagerCallbacks.notifyANR(
1887 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001888 }
1889
1890 // Native callback.
1891 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1892 synchronized (mInputFilterLock) {
1893 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001894 try {
1895 mInputFilter.filterInputEvent(event, policyFlags);
1896 } catch (RemoteException e) {
1897 /* ignore */
1898 }
Jeff Brown4532e612012-04-05 14:27:12 -07001899 return false;
1900 }
1901 }
1902 event.recycle();
1903 return true;
1904 }
1905
1906 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001907 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1908 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001909 }
1910
1911 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001912 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1913 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001914 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001915 }
1916
1917 // Native callback.
1918 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1919 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001920 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001921 }
1922
1923 // Native callback.
1924 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1925 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001926 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001927 }
1928
1929 // Native callback.
1930 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1931 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1932 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1933 }
1934
1935 // Native callback.
1936 private int getVirtualKeyQuietTimeMillis() {
1937 return mContext.getResources().getInteger(
1938 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1939 }
1940
1941 // Native callback.
1942 private String[] getExcludedDeviceNames() {
1943 ArrayList<String> names = new ArrayList<String>();
1944
1945 // Read partner-provided list of excluded input devices
1946 XmlPullParser parser = null;
1947 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1948 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1949 FileReader confreader = null;
1950 try {
1951 confreader = new FileReader(confFile);
1952 parser = Xml.newPullParser();
1953 parser.setInput(confreader);
1954 XmlUtils.beginDocument(parser, "devices");
1955
1956 while (true) {
1957 XmlUtils.nextElement(parser);
1958 if (!"device".equals(parser.getName())) {
1959 break;
1960 }
1961 String name = parser.getAttributeValue(null, "name");
1962 if (name != null) {
1963 names.add(name);
1964 }
1965 }
1966 } catch (FileNotFoundException e) {
1967 // It's ok if the file does not exist.
1968 } catch (Exception e) {
1969 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1970 } finally {
1971 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1972 }
1973
1974 return names.toArray(new String[names.size()]);
1975 }
1976
1977 // Native callback.
1978 private int getKeyRepeatTimeout() {
1979 return ViewConfiguration.getKeyRepeatTimeout();
1980 }
1981
1982 // Native callback.
1983 private int getKeyRepeatDelay() {
1984 return ViewConfiguration.getKeyRepeatDelay();
1985 }
1986
1987 // Native callback.
1988 private int getHoverTapTimeout() {
1989 return ViewConfiguration.getHoverTapTimeout();
1990 }
1991
1992 // Native callback.
1993 private int getHoverTapSlop() {
1994 return ViewConfiguration.getHoverTapSlop();
1995 }
1996
1997 // Native callback.
1998 private int getDoubleTapTimeout() {
1999 return ViewConfiguration.getDoubleTapTimeout();
2000 }
2001
2002 // Native callback.
2003 private int getLongPressTimeout() {
2004 return ViewConfiguration.getLongPressTimeout();
2005 }
2006
2007 // Native callback.
2008 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07002009 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07002010 }
2011
2012 // Native callback.
2013 private PointerIcon getPointerIcon() {
2014 return PointerIcon.getDefaultIcon(mContext);
2015 }
2016
Jeff Brown6ec6f792012-04-17 16:52:41 -07002017 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08002018 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07002019 if (!mSystemReady) {
2020 return null;
2021 }
2022
RoboErikfb290df2013-12-16 11:27:55 -08002023 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002024 if (keyboardLayoutDescriptor == null) {
2025 return null;
2026 }
2027
2028 final String[] result = new String[2];
2029 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
2030 @Override
Michael Wright07483422015-10-30 16:20:13 +00002031 public void visitKeyboardLayout(Resources resources,
2032 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07002033 try {
Michael Wright07483422015-10-30 16:20:13 +00002034 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07002035 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07002036 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07002037 } catch (IOException ex) {
2038 } catch (NotFoundException ex) {
2039 }
2040 }
2041 });
2042 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00002043 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07002044 + keyboardLayoutDescriptor + "'.");
2045 return null;
2046 }
2047 return result;
2048 }
2049
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002050 // Native callback.
2051 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07002052 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2053 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2054 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002055 }
2056 return null;
2057 }
2058
Jeff Brown4532e612012-04-05 14:27:12 -07002059 /**
2060 * Callback interface implemented by the Window Manager.
2061 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002062 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002063 public void notifyConfigurationChanged();
2064
2065 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2066
Michael Wright3818c922014-09-02 13:59:07 -07002067 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2068
Jeff Brown4532e612012-04-05 14:27:12 -07002069 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
2070
2071 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07002072 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002073
Jeff Brown037c33e2014-04-09 00:31:55 -07002074 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002075
Michael Wright70af00a2014-09-03 19:30:20 -07002076 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002077
2078 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2079 KeyEvent event, int policyFlags);
2080
2081 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2082 KeyEvent event, int policyFlags);
2083
2084 public int getPointerLayer();
2085 }
2086
2087 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002088 * Callback interface implemented by WiredAccessoryObserver.
2089 */
2090 public interface WiredAccessoryCallbacks {
2091 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002092 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002093 }
2094
2095 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002096 * Private handler for the input manager.
2097 */
2098 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002099 public InputManagerHandler(Looper looper) {
2100 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002101 }
2102
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002103 @Override
2104 public void handleMessage(Message msg) {
2105 switch (msg.what) {
2106 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002107 deliverInputDevicesChanged((InputDevice[])msg.obj);
2108 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002109 case MSG_SWITCH_KEYBOARD_LAYOUT: {
2110 SomeArgs args = (SomeArgs)msg.obj;
2111 handleSwitchKeyboardLayout((InputDeviceIdentifier)args.arg1,
2112 (InputMethodSubtypeHandle)args.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002113 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002114 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07002115 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2116 reloadKeyboardLayouts();
2117 break;
2118 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2119 updateKeyboardLayouts();
2120 break;
2121 case MSG_RELOAD_DEVICE_ALIASES:
2122 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002123 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002124 case MSG_DELIVER_TABLET_MODE_CHANGED: {
Michael Wright39e5e942015-08-19 22:52:47 +01002125 SomeArgs args = (SomeArgs) msg.obj;
2126 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2127 boolean inTabletMode = (boolean) args.arg1;
2128 deliverTabletModeChanged(whenNanos, inTabletMode);
2129 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002130 }
2131 case MSG_INPUT_METHOD_SUBTYPE_CHANGED: {
2132 final int userId = msg.arg1;
2133 final SomeArgs args = (SomeArgs) msg.obj;
2134 final InputMethodInfo inputMethodInfo = (InputMethodInfo) args.arg1;
2135 final InputMethodSubtype subtype = (InputMethodSubtype) args.arg2;
2136 args.recycle();
2137 handleSwitchInputMethodSubtype(userId, inputMethodInfo, subtype);
2138 break;
2139 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002140 }
2141 }
2142 }
2143
2144 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002145 * Hosting interface for input filters to call back into the input manager.
2146 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002147 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002148 private boolean mDisconnected;
2149
2150 public void disconnectLocked() {
2151 mDisconnected = true;
2152 }
2153
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002154 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002155 public void sendInputEvent(InputEvent event, int policyFlags) {
2156 if (event == null) {
2157 throw new IllegalArgumentException("event must not be null");
2158 }
2159
2160 synchronized (mInputFilterLock) {
2161 if (!mDisconnected) {
Jeff Brownca9bc702014-02-11 14:32:56 -08002162 nativeInjectInputEvent(mPtr, event, Display.DEFAULT_DISPLAY, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002163 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002164 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2165 }
2166 }
2167 }
2168 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002169
2170 private static final class KeyboardLayoutDescriptor {
2171 public String packageName;
2172 public String receiverName;
2173 public String keyboardLayoutName;
2174
2175 public static String format(String packageName,
2176 String receiverName, String keyboardName) {
2177 return packageName + "/" + receiverName + "/" + keyboardName;
2178 }
2179
2180 public static KeyboardLayoutDescriptor parse(String descriptor) {
2181 int pos = descriptor.indexOf('/');
2182 if (pos < 0 || pos + 1 == descriptor.length()) {
2183 return null;
2184 }
2185 int pos2 = descriptor.indexOf('/', pos + 1);
2186 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2187 return null;
2188 }
2189
2190 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2191 result.packageName = descriptor.substring(0, pos);
2192 result.receiverName = descriptor.substring(pos + 1, pos2);
2193 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2194 return result;
2195 }
2196 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002197
Jeff Brown6ec6f792012-04-17 16:52:41 -07002198 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002199 void visitKeyboardLayout(Resources resources,
2200 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002201 }
2202
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002203 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2204 private final int mPid;
2205 private final IInputDevicesChangedListener mListener;
2206
2207 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2208 mPid = pid;
2209 mListener = listener;
2210 }
2211
2212 @Override
2213 public void binderDied() {
2214 if (DEBUG) {
2215 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2216 }
2217 onInputDevicesChangedListenerDied(mPid);
2218 }
2219
2220 public void notifyInputDevicesChanged(int[] info) {
2221 try {
2222 mListener.onInputDevicesChanged(info);
2223 } catch (RemoteException ex) {
2224 Slog.w(TAG, "Failed to notify process "
2225 + mPid + " that input devices changed, assuming it died.", ex);
2226 binderDied();
2227 }
2228 }
2229 }
Jeff Browna47425a2012-04-13 04:09:27 -07002230
Michael Wright39e5e942015-08-19 22:52:47 +01002231 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2232 private final int mPid;
2233 private final ITabletModeChangedListener mListener;
2234
2235 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2236 mPid = pid;
2237 mListener = listener;
2238 }
2239
2240 @Override
2241 public void binderDied() {
2242 if (DEBUG) {
2243 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2244 }
2245 onTabletModeChangedListenerDied(mPid);
2246 }
2247
2248 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2249 try {
2250 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2251 } catch (RemoteException ex) {
2252 Slog.w(TAG, "Failed to notify process " + mPid +
2253 " that tablet mode changed, assuming it died.", ex);
2254 binderDied();
2255 }
2256 }
2257 }
2258
Jeff Browna47425a2012-04-13 04:09:27 -07002259 private final class VibratorToken implements DeathRecipient {
2260 public final int mDeviceId;
2261 public final IBinder mToken;
2262 public final int mTokenValue;
2263
2264 public boolean mVibrating;
2265
2266 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2267 mDeviceId = deviceId;
2268 mToken = token;
2269 mTokenValue = tokenValue;
2270 }
2271
2272 @Override
2273 public void binderDied() {
2274 if (DEBUG) {
2275 Slog.d(TAG, "Vibrator token died.");
2276 }
2277 onVibratorTokenDied(this);
2278 }
2279 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002280
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002281 private class Shell extends ShellCommand {
2282 @Override
2283 public int onCommand(String cmd) {
2284 return onShellCommand(this, cmd);
2285 }
2286
2287 @Override
2288 public void onHelp() {
2289 final PrintWriter pw = getOutPrintWriter();
2290 pw.println("Input manager commands:");
2291 pw.println(" help");
2292 pw.println(" Print this help text.");
2293 pw.println("");
2294 pw.println(" setlayout IME_ID IME_SUPTYPE_HASH_CODE"
2295 + " DEVICE_DESCRIPTOR VENDOR_ID PRODUCT_ID KEYBOARD_DESCRIPTOR");
2296 pw.println(" Sets a keyboard layout for a given IME subtype and input device pair");
2297 }
2298 }
2299
Jeff Brown4ccb8232014-01-16 22:16:42 -08002300 private final class LocalService extends InputManagerInternal {
2301 @Override
2302 public void setDisplayViewports(
2303 DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
2304 setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
2305 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002306
2307 @Override
2308 public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
2309 return injectInputEventInternal(event, displayId, mode);
2310 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002311
2312 @Override
2313 public void setInteractive(boolean interactive) {
2314 nativeSetInteractive(mPtr, interactive);
2315 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002316
2317 @Override
2318 public void onInputMethodSubtypeChanged(int userId,
2319 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
2320 final SomeArgs someArgs = SomeArgs.obtain();
2321 someArgs.arg1 = inputMethodInfo;
2322 someArgs.arg2 = subtype;
2323 mHandler.obtainMessage(MSG_INPUT_METHOD_SUBTYPE_CHANGED, userId, 0, someArgs)
2324 .sendToTarget();
2325 }
Andrii Kulian112d0562016-03-08 10:44:22 -08002326
2327 @Override
2328 public void toggleCapsLock(int deviceId) {
2329 nativeToggleCapsLock(mPtr, deviceId);
2330 }
Adrian Roos99182342016-06-15 15:30:46 -07002331
2332 @Override
2333 public void setPulseGestureEnabled(boolean enabled) {
2334 if (mDoubleTouchGestureEnableFile != null) {
2335 FileWriter writer = null;
2336 try {
2337 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2338 writer.write(enabled ? "1" : "0");
2339 } catch (IOException e) {
2340 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2341 } finally {
2342 IoUtils.closeQuietly(writer);
2343 }
2344 }
2345 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002346 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002347}