blob: 4913e8bda6ad920f8c1225cd73a60fe908ad849d [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;
Andrii Kulianed76e742017-06-26 14:57:02 -070020import android.app.IInputForwarder;
Jeff Browncf39bdf2012-05-18 14:41:19 -070021import android.app.Notification;
22import android.app.NotificationManager;
23import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070024import android.bluetooth.BluetoothAdapter;
25import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070026import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070027import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070028import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070029import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070030import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070031import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070032import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070033import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.pm.PackageManager.NameNotFoundException;
Arthur Hung39134b22018-08-14 11:58:28 +080035import android.content.pm.ResolveInfo;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070037import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.res.TypedArray;
39import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070040import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070041import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080042import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070043import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070044import android.hardware.input.IInputManager;
Arthur Hung39134b22018-08-14 11:58:28 +080045import android.hardware.input.ITabletModeChangedListener;
RoboErikfb290df2013-12-16 11:27:55 -080046import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070047import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080048import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080050import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070053import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.os.IBinder;
Arthur Hung39134b22018-08-14 11:58:28 +080056import android.os.LocaleList;
Jeff Browna9d131c2012-09-20 16:48:17 -070057import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080059import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070063import android.provider.Settings;
64import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000065import android.text.TextUtils;
Arthur Hung39134b22018-08-14 11:58:28 +080066import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070068import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070069import android.util.Xml;
Andrii Kulianed76e742017-06-26 14:57:02 -070070import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080073import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070075import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070076import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080077import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070078import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070079import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080080import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080081import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082
Arthur Hung39134b22018-08-14 11:58:28 +080083import com.android.internal.R;
84import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
85import com.android.internal.notification.SystemNotificationChannels;
86import com.android.internal.os.SomeArgs;
87import com.android.internal.util.DumpUtils;
88import com.android.internal.util.Preconditions;
89import com.android.internal.util.XmlUtils;
90import com.android.server.DisplayThread;
91import com.android.server.LocalServices;
92import com.android.server.Watchdog;
93import com.android.server.policy.WindowManagerPolicy;
94
95import libcore.io.IoUtils;
96import libcore.io.Streams;
97
98import org.xmlpull.v1.XmlPullParser;
99
Jeff Brown46b9ac02010-04-22 18:58:52 -0700100import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700101import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102import java.io.FileNotFoundException;
103import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700104import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700106import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700107import java.io.PrintWriter;
108import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000109import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700110import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700111import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100112import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000113import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000114import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700115
Jeff Brown46b9ac02010-04-22 18:58:52 -0700116/*
117 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700118 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700119public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800120 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700122 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700123
Jeff Brown4532e612012-04-05 14:27:12 -0700124 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
125
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700126 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700127 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
128 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
129 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
130 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100131 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132
Jeff Brown4532e612012-04-05 14:27:12 -0700133 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000134 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700135
Jeff Brown46b9ac02010-04-22 18:58:52 -0700136 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700138
Adrian Roos99182342016-06-15 15:30:46 -0700139 private final File mDoubleTouchGestureEnableFile;
140
Jeff Browna9d131c2012-09-20 16:48:17 -0700141 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700142 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700143 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700144 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145
Michael Wright39e5e942015-08-19 22:52:47 +0100146 private final Object mTabletModeLock = new Object();
147 // List of currently registered tablet mode changed listeners by process id
148 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
149 new SparseArray<>(); // guarded by mTabletModeLock
150 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
151 new ArrayList<>();
152
Jeff Browna3bc5652012-04-17 11:42:25 -0700153 // Persistent data store. Must be locked each time during use.
154 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700155
156 // List of currently registered input devices changed listeners by process id.
157 private Object mInputDevicesLock = new Object();
158 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
159 private InputDevice[] mInputDevices = new InputDevice[0];
160 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
161 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
162 private final ArrayList<InputDevicesChangedListenerRecord>
163 mTempInputDevicesChangedListenersToNotify =
164 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700165 private final ArrayList<InputDevice>
166 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
167 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800168 private PendingIntent mKeyboardLayoutIntent;
169 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700170
Jeff Browna47425a2012-04-13 04:09:27 -0700171 // State for vibrator tokens.
172 private Object mVibratorLock = new Object();
173 private HashMap<IBinder, VibratorToken> mVibratorTokens =
174 new HashMap<IBinder, VibratorToken>();
175 private int mNextVibratorTokenValue;
176
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177 // State for the currently installed input filter.
178 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700179 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700180 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700181
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800182 private IWindow mFocusedWindow;
183 private boolean mFocusedWindowHasCapture;
184
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000185 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700186 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100188 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700189 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700190
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000191 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700192 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000193 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700194 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000195 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700196 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000197 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700198 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000199 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800200 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000201 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
202 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800203 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700204 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
205 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800206 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800207 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
208 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000209 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
210 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
211 private static native void nativeSetFocusedApplication(long ptr,
Tiger Huang1e5b10a2018-07-30 20:19:51 +0800212 int displayId, InputApplicationHandle application);
213 private static native void nativeSetFocusedDisplay(long ptr, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000214 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700215 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000216 private static native void nativeSetPointerSpeed(long ptr, int speed);
217 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700218 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800219 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000220 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700221 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000222 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
223 private static native void nativeReloadKeyboardLayouts(long ptr);
224 private static native void nativeReloadDeviceAliases(long ptr);
225 private static native String nativeDump(long ptr);
226 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700227 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
228 private static native void nativeEnableInputDevice(long ptr, int deviceId);
229 private static native void nativeDisableInputDevice(long ptr, int deviceId);
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
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100354 // TODO(BT) Pass in parameter 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
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100405 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
406 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700407 }
Jeff Brownac143512012-04-05 18:57:33 -0700408
Jeff Brown6d0fec22010-07-23 21:28:06 -0700409 /**
410 * Gets the current state of a key or button by key code.
411 * @param deviceId The input device id, or -1 to consult all devices.
412 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
413 * consider all input sources. An input device is consulted if at least one of its
414 * non-class input source bits matches the specified source mask.
415 * @param keyCode The key code to check.
416 * @return The key state.
417 */
418 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700419 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700421
Jeff Brown6d0fec22010-07-23 21:28:06 -0700422 /**
423 * Gets the current state of a key or button by scan code.
424 * @param deviceId The input device id, or -1 to consult all devices.
425 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
426 * consider all input sources. An input device is consulted if at least one of its
427 * non-class input source bits matches the specified source mask.
428 * @param scanCode The scan code to check.
429 * @return The key state.
430 */
431 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700432 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700433 }
RoboErikfb290df2013-12-16 11:27:55 -0800434
Jeff Brown6d0fec22010-07-23 21:28:06 -0700435 /**
436 * Gets the current state of a switch by switch code.
437 * @param deviceId The input device id, or -1 to consult all devices.
438 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
439 * consider all input sources. An input device is consulted if at least one of its
440 * non-class input source bits matches the specified source mask.
441 * @param switchCode The switch code to check.
442 * @return The switch state.
443 */
444 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700445 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700446 }
447
Jeff Brown6d0fec22010-07-23 21:28:06 -0700448 /**
449 * Determines whether the specified key codes are supported by a particular device.
450 * @param deviceId The input device id, or -1 to consult all devices.
451 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
452 * consider all input sources. An input device is consulted if at least one of its
453 * non-class input source bits matches the specified source mask.
454 * @param keyCodes The array of key codes to check.
455 * @param keyExists An array at least as large as keyCodes whose entries will be set
456 * to true or false based on the presence or absence of support for the corresponding
457 * key codes.
458 * @return True if the lookup was successful, false otherwise.
459 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700460 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700461 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700462 if (keyCodes == null) {
463 throw new IllegalArgumentException("keyCodes must not be null.");
464 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700465 if (keyExists == null || keyExists.length < keyCodes.length) {
466 throw new IllegalArgumentException("keyExists must not be null and must be at "
467 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700468 }
RoboErikfb290df2013-12-16 11:27:55 -0800469
Jeff Brown4532e612012-04-05 14:27:12 -0700470 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700471 }
RoboErikfb290df2013-12-16 11:27:55 -0800472
Jeff Browna41ca772010-08-11 14:46:32 -0700473 /**
474 * Creates an input channel that will receive all input from the input dispatcher.
475 * @param inputChannelName The input channel name.
476 * @return The input channel.
477 */
478 public InputChannel monitorInput(String inputChannelName) {
479 if (inputChannelName == null) {
480 throw new IllegalArgumentException("inputChannelName must not be null.");
481 }
RoboErikfb290df2013-12-16 11:27:55 -0800482
Jeff Browna41ca772010-08-11 14:46:32 -0700483 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700484 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700485 inputChannels[0].dispose(); // don't need to retain the Java object reference
486 return inputChannels[1];
487 }
488
489 /**
490 * Registers an input channel so that it can be used as an input event target.
491 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800492 * @param inputWindowHandle The handle of the input window associated with the
493 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700494 */
Jeff Brown928e0542011-01-10 11:17:36 -0800495 public void registerInputChannel(InputChannel inputChannel,
496 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700497 if (inputChannel == null) {
498 throw new IllegalArgumentException("inputChannel must not be null.");
499 }
RoboErikfb290df2013-12-16 11:27:55 -0800500
Jeff Brown4532e612012-04-05 14:27:12 -0700501 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700502 }
RoboErikfb290df2013-12-16 11:27:55 -0800503
Jeff Browna41ca772010-08-11 14:46:32 -0700504 /**
505 * Unregisters an input channel.
506 * @param inputChannel The input channel to unregister.
507 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700508 public void unregisterInputChannel(InputChannel inputChannel) {
509 if (inputChannel == null) {
510 throw new IllegalArgumentException("inputChannel must not be null.");
511 }
RoboErikfb290df2013-12-16 11:27:55 -0800512
Jeff Brown4532e612012-04-05 14:27:12 -0700513 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700514 }
Jeff Brown0029c662011-03-30 02:25:18 -0700515
516 /**
517 * Sets an input filter that will receive all input events before they are dispatched.
518 * The input filter may then reinterpret input events or inject new ones.
519 *
520 * To ensure consistency, the input dispatcher automatically drops all events
521 * in progress whenever an input filter is installed or uninstalled. After an input
522 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
523 * Any events it attempts to send after it has been uninstalled will be dropped.
524 *
525 * @param filter The input filter, or null to remove the current filter.
526 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700527 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700528 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700529 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700530 if (oldFilter == filter) {
531 return; // nothing to do
532 }
533
534 if (oldFilter != null) {
535 mInputFilter = null;
536 mInputFilterHost.disconnectLocked();
537 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700538 try {
539 oldFilter.uninstall();
540 } catch (RemoteException re) {
541 /* ignore */
542 }
Jeff Brown0029c662011-03-30 02:25:18 -0700543 }
544
545 if (filter != null) {
546 mInputFilter = filter;
547 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700548 try {
549 filter.install(mInputFilterHost);
550 } catch (RemoteException re) {
551 /* ignore */
552 }
Jeff Brown0029c662011-03-30 02:25:18 -0700553 }
554
Jeff Brown4532e612012-04-05 14:27:12 -0700555 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700556 }
557 }
558
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700559 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700560 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800561 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800562 }
563
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800564 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700565 if (event == null) {
566 throw new IllegalArgumentException("event must not be null");
567 }
Jeff Brownac143512012-04-05 18:57:33 -0700568 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
569 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
570 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
571 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700572 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700573
Jeff Brownac143512012-04-05 18:57:33 -0700574 final int pid = Binder.getCallingPid();
575 final int uid = Binder.getCallingUid();
576 final long ident = Binder.clearCallingIdentity();
577 final int result;
578 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800579 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700580 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
581 } finally {
582 Binder.restoreCallingIdentity(ident);
583 }
584 switch (result) {
585 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
586 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
587 throw new SecurityException(
588 "Injecting to another application requires INJECT_EVENTS permission");
589 case INPUT_EVENT_INJECTION_SUCCEEDED:
590 return true;
591 case INPUT_EVENT_INJECTION_TIMED_OUT:
592 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
593 return false;
594 case INPUT_EVENT_INJECTION_FAILED:
595 default:
596 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
597 return false;
598 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700599 }
Jeff Brown0029c662011-03-30 02:25:18 -0700600
Jeff Brown8d608662010-08-30 03:02:23 -0700601 /**
602 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700603 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700604 * @return The input device or null if not found.
605 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700606 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700607 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700608 synchronized (mInputDevicesLock) {
609 final int count = mInputDevices.length;
610 for (int i = 0; i < count; i++) {
611 final InputDevice inputDevice = mInputDevices[i];
612 if (inputDevice.getId() == deviceId) {
613 return inputDevice;
614 }
615 }
616 }
617 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700618 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700619
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700620 // Binder call
621 @Override
622 public boolean isInputDeviceEnabled(int deviceId) {
623 return nativeIsInputDeviceEnabled(mPtr, deviceId);
624 }
625
626 // Binder call
627 @Override
628 public void enableInputDevice(int deviceId) {
629 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
630 "enableInputDevice()")) {
631 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
632 }
633 nativeEnableInputDevice(mPtr, deviceId);
634 }
635
636 // Binder call
637 @Override
638 public void disableInputDevice(int deviceId) {
639 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
640 "disableInputDevice()")) {
641 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
642 }
643 nativeDisableInputDevice(mPtr, deviceId);
644 }
645
Jeff Brown8d608662010-08-30 03:02:23 -0700646 /**
647 * Gets the ids of all input devices in the system.
648 * @return The input device ids.
649 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700650 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700651 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700652 synchronized (mInputDevicesLock) {
653 final int count = mInputDevices.length;
654 int[] ids = new int[count];
655 for (int i = 0; i < count; i++) {
656 ids[i] = mInputDevices[i].getId();
657 }
658 return ids;
659 }
660 }
661
Jeff Browndaa37532012-05-01 15:54:03 -0700662 /**
663 * Gets all input devices in the system.
664 * @return The array of input devices.
665 */
666 public InputDevice[] getInputDevices() {
667 synchronized (mInputDevicesLock) {
668 return mInputDevices;
669 }
670 }
671
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700672 @Override // Binder call
673 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
674 if (listener == null) {
675 throw new IllegalArgumentException("listener must not be null");
676 }
677
678 synchronized (mInputDevicesLock) {
679 int callingPid = Binder.getCallingPid();
680 if (mInputDevicesChangedListeners.get(callingPid) != null) {
681 throw new SecurityException("The calling process has already "
682 + "registered an InputDevicesChangedListener.");
683 }
684
685 InputDevicesChangedListenerRecord record =
686 new InputDevicesChangedListenerRecord(callingPid, listener);
687 try {
688 IBinder binder = listener.asBinder();
689 binder.linkToDeath(record, 0);
690 } catch (RemoteException ex) {
691 // give up
692 throw new RuntimeException(ex);
693 }
694
695 mInputDevicesChangedListeners.put(callingPid, record);
696 }
697 }
698
699 private void onInputDevicesChangedListenerDied(int pid) {
700 synchronized (mInputDevicesLock) {
701 mInputDevicesChangedListeners.remove(pid);
702 }
703 }
704
705 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700706 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
707 // Scan for changes.
708 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700709 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700710 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700711 final int numListeners;
712 final int[] deviceIdAndGeneration;
713 synchronized (mInputDevicesLock) {
714 if (!mInputDevicesChangedPending) {
715 return;
716 }
717 mInputDevicesChangedPending = false;
718
719 numListeners = mInputDevicesChangedListeners.size();
720 for (int i = 0; i < numListeners; i++) {
721 mTempInputDevicesChangedListenersToNotify.add(
722 mInputDevicesChangedListeners.valueAt(i));
723 }
724
725 final int numDevices = mInputDevices.length;
726 deviceIdAndGeneration = new int[numDevices * 2];
727 for (int i = 0; i < numDevices; i++) {
728 final InputDevice inputDevice = mInputDevices[i];
729 deviceIdAndGeneration[i * 2] = inputDevice.getId();
730 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700731
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700732 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700733 if (!containsInputDeviceWithDescriptor(oldInputDevices,
734 inputDevice.getDescriptor())) {
735 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
736 } else {
737 mTempFullKeyboards.add(inputDevice);
738 }
739 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700740 }
741 }
742
Jeff Browncf39bdf2012-05-18 14:41:19 -0700743 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700744 for (int i = 0; i < numListeners; i++) {
745 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
746 deviceIdAndGeneration);
747 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700748 mTempInputDevicesChangedListenersToNotify.clear();
749
750 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000751 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
752 final int numFullKeyboards = mTempFullKeyboards.size();
753 synchronized (mDataStore) {
754 for (int i = 0; i < numFullKeyboards; i++) {
755 final InputDevice inputDevice = mTempFullKeyboards.get(i);
756 String layout =
757 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
758 if (layout == null) {
759 layout = getDefaultKeyboardLayout(inputDevice);
760 if (layout != null) {
761 setCurrentKeyboardLayoutForInputDevice(
762 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700763 }
764 }
Michael Wright07483422015-10-30 16:20:13 +0000765 if (layout == null) {
766 keyboardsMissingLayout.add(inputDevice);
767 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700768 }
Michael Wright07483422015-10-30 16:20:13 +0000769 }
770
771 if (mNotificationManager != null) {
772 if (!keyboardsMissingLayout.isEmpty()) {
773 if (keyboardsMissingLayout.size() > 1) {
774 // We have more than one keyboard missing a layout, so drop the
775 // user at the generic input methods page so they can pick which
776 // one to set.
777 showMissingKeyboardLayoutNotification(null);
778 } else {
779 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700780 }
781 } else if (mKeyboardLayoutNotificationShown) {
782 hideMissingKeyboardLayoutNotification();
783 }
784 }
785 mTempFullKeyboards.clear();
786 }
787
Michael Wright07483422015-10-30 16:20:13 +0000788 private String getDefaultKeyboardLayout(final InputDevice d) {
789 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
790 // If our locale doesn't have a language for some reason, then we don't really have a
791 // reasonable default.
792 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
793 return null;
794 }
795 final List<KeyboardLayout> layouts = new ArrayList<>();
796 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
797 @Override
798 public void visitKeyboardLayout(Resources resources,
799 int keyboardLayoutResId, KeyboardLayout layout) {
800 // Only select a default when we know the layout is appropriate. For now, this
801 // means its a custom layout for a specific keyboard.
802 if (layout.getVendorId() != d.getVendorId()
803 || layout.getProductId() != d.getProductId()) {
804 return;
805 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800806 final LocaleList locales = layout.getLocales();
807 final int numLocales = locales.size();
808 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
809 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000810 layouts.add(layout);
811 break;
812 }
813 }
814 }
815 });
816
817 if (layouts.isEmpty()) {
818 return null;
819 }
820
821 // First sort so that ones with higher priority are listed at the top
822 Collections.sort(layouts);
823 // Next we want to try to find an exact match of language, country and variant.
824 final int N = layouts.size();
825 for (int i = 0; i < N; i++) {
826 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800827 final LocaleList locales = layout.getLocales();
828 final int numLocales = locales.size();
829 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
830 final Locale locale = locales.get(localeIndex);
831 if (locale.getCountry().equals(systemLocale.getCountry())
832 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000833 return layout.getDescriptor();
834 }
835 }
836 }
837 // Then try an exact match of language and country
838 for (int i = 0; i < N; i++) {
839 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800840 final LocaleList locales = layout.getLocales();
841 final int numLocales = locales.size();
842 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
843 final Locale locale = locales.get(localeIndex);
844 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000845 return layout.getDescriptor();
846 }
847 }
848 }
849
850 // Give up and just use the highest priority layout with matching language
851 return layouts.get(0).getDescriptor();
852 }
853
854 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
855 // Different languages are never compatible
856 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
857 return false;
858 }
859 // If both the system and the keyboard layout have a country specifier, they must be equal.
860 if (!TextUtils.isEmpty(systemLocale.getCountry())
861 && !TextUtils.isEmpty(keyboardLocale.getCountry())
862 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
863 return false;
864 }
865 return true;
866 }
867
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800868 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700869 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
870 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800871 if (inputDeviceDescriptor == null) {
872 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
873 }
874
875 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700876 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800877 }
878 }
879
880 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700881 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800882 TouchCalibration calibration) {
883 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
884 "setTouchCalibrationForInputDevice()")) {
885 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
886 }
887 if (inputDeviceDescriptor == null) {
888 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
889 }
890 if (calibration == null) {
891 throw new IllegalArgumentException("calibration must not be null");
892 }
Jason Gerecked5220742014-03-10 09:47:59 -0700893 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
894 throw new IllegalArgumentException("surfaceRotation value out of bounds");
895 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800896
897 synchronized (mDataStore) {
898 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700899 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
900 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800901 nativeReloadCalibration(mPtr);
902 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800903 } finally {
904 mDataStore.saveIfNeeded();
905 }
906 }
907 }
908
Michael Wright39e5e942015-08-19 22:52:47 +0100909 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100910 public int isInTabletMode() {
911 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
912 "isInTabletMode()")) {
913 throw new SecurityException("Requires TABLET_MODE permission");
914 }
915 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
916 }
917
918 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100919 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100920 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100921 "registerTabletModeChangedListener()")) {
922 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
923 }
924 if (listener == null) {
925 throw new IllegalArgumentException("listener must not be null");
926 }
927
928 synchronized (mTabletModeLock) {
929 final int callingPid = Binder.getCallingPid();
930 if (mTabletModeChangedListeners.get(callingPid) != null) {
931 throw new IllegalStateException("The calling process has already registered "
932 + "a TabletModeChangedListener.");
933 }
934 TabletModeChangedListenerRecord record =
935 new TabletModeChangedListenerRecord(callingPid, listener);
936 try {
937 IBinder binder = listener.asBinder();
938 binder.linkToDeath(record, 0);
939 } catch (RemoteException ex) {
940 throw new RuntimeException(ex);
941 }
942 mTabletModeChangedListeners.put(callingPid, record);
943 }
944 }
945
946 private void onTabletModeChangedListenerDied(int pid) {
947 synchronized (mTabletModeLock) {
948 mTabletModeChangedListeners.remove(pid);
949 }
950 }
951
952 // Must be called on handler
953 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
954 mTempTabletModeChangedListenersToNotify.clear();
955 final int numListeners;
956 synchronized (mTabletModeLock) {
957 numListeners = mTabletModeChangedListeners.size();
958 for (int i = 0; i < numListeners; i++) {
959 mTempTabletModeChangedListenersToNotify.add(
960 mTabletModeChangedListeners.valueAt(i));
961 }
962 }
963 for (int i = 0; i < numListeners; i++) {
964 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
965 whenNanos, inTabletMode);
966 }
967 }
968
Jeff Browncf39bdf2012-05-18 14:41:19 -0700969 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700970 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700971 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700972 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700973 if (device != null) {
974 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700975 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700976 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
977 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
978 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
979 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
980 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700981
982 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500983 Notification notification =
984 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
985 .setContentTitle(r.getString(
986 R.string.select_keyboard_layout_notification_title))
987 .setContentText(r.getString(
988 R.string.select_keyboard_layout_notification_message))
989 .setContentIntent(keyboardLayoutIntent)
990 .setSmallIcon(R.drawable.ic_settings_language)
991 .setColor(mContext.getColor(
992 com.android.internal.R.color.system_notification_accent_color))
993 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700994 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -0400995 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700996 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700997 mKeyboardLayoutNotificationShown = true;
998 }
999 }
1000
1001 // Must be called on handler.
1002 private void hideMissingKeyboardLayoutNotification() {
1003 if (mKeyboardLayoutNotificationShown) {
1004 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001005 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001006 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001007 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001008 }
1009 }
1010
1011 // Must be called on handler.
1012 private void updateKeyboardLayouts() {
1013 // Scan all input devices state for keyboard layouts that have been uninstalled.
1014 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1015 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1016 @Override
Michael Wright07483422015-10-30 16:20:13 +00001017 public void visitKeyboardLayout(Resources resources,
1018 int keyboardLayoutResId, KeyboardLayout layout) {
1019 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001020 }
1021 });
1022 synchronized (mDataStore) {
1023 try {
1024 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1025 } finally {
1026 mDataStore.saveIfNeeded();
1027 }
1028 }
1029
1030 // Reload keyboard layouts.
1031 reloadKeyboardLayouts();
1032 }
1033
Jeff Browncf39bdf2012-05-18 14:41:19 -07001034 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1035 String descriptor) {
1036 final int numDevices = inputDevices.length;
1037 for (int i = 0; i < numDevices; i++) {
1038 final InputDevice inputDevice = inputDevices[i];
1039 if (inputDevice.getDescriptor().equals(descriptor)) {
1040 return true;
1041 }
1042 }
1043 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001044 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001045
1046 @Override // Binder call
1047 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001048 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1049 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1050 @Override
Michael Wright07483422015-10-30 16:20:13 +00001051 public void visitKeyboardLayout(Resources resources,
1052 int keyboardLayoutResId, KeyboardLayout layout) {
1053 list.add(layout);
1054 }
1055 });
1056 return list.toArray(new KeyboardLayout[list.size()]);
1057 }
1058
Michael Wrightb0e804a2016-01-04 16:48:53 -05001059 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001060 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1061 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001062 final String[] enabledLayoutDescriptors =
1063 getEnabledKeyboardLayoutsForInputDevice(identifier);
1064 final ArrayList<KeyboardLayout> enabledLayouts =
1065 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1066 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001067 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1068 boolean mHasSeenDeviceSpecificLayout;
1069
1070 @Override
1071 public void visitKeyboardLayout(Resources resources,
1072 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001073 // First check if it's enabled. If the keyboard layout is enabled then we always
1074 // want to return it as a possible layout for the device.
1075 for (String s : enabledLayoutDescriptors) {
1076 if (s != null && s.equals(layout.getDescriptor())) {
1077 enabledLayouts.add(layout);
1078 return;
1079 }
1080 }
1081 // Next find any potential layouts that aren't yet enabled for the device. For
1082 // devices that have special layouts we assume there's a reason that the generic
1083 // layouts don't work for them so we don't want to return them since it's likely
1084 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001085 if (layout.getVendorId() == identifier.getVendorId()
1086 && layout.getProductId() == identifier.getProductId()) {
1087 if (!mHasSeenDeviceSpecificLayout) {
1088 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001089 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001090 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001091 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001092 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1093 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001094 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001095 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001096 }
1097 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001098 final int enabledLayoutSize = enabledLayouts.size();
1099 final int potentialLayoutSize = potentialLayouts.size();
1100 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1101 enabledLayouts.toArray(layouts);
1102 for (int i = 0; i < potentialLayoutSize; i++) {
1103 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1104 }
1105 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001106 }
1107
1108 @Override // Binder call
1109 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1110 if (keyboardLayoutDescriptor == null) {
1111 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1112 }
1113
Jeff Brown6ec6f792012-04-17 16:52:41 -07001114 final KeyboardLayout[] result = new KeyboardLayout[1];
1115 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1116 @Override
Michael Wright07483422015-10-30 16:20:13 +00001117 public void visitKeyboardLayout(Resources resources,
1118 int keyboardLayoutResId, KeyboardLayout layout) {
1119 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001120 }
1121 });
1122 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001123 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001124 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001125 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001126 return result[0];
1127 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001128
Jeff Brown6ec6f792012-04-17 16:52:41 -07001129 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001130 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001131 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1132 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001133 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1134 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001135 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1136 final int priority = resolveInfo.priority;
1137 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001138 }
1139 }
1140
Jeff Brown6ec6f792012-04-17 16:52:41 -07001141 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1142 KeyboardLayoutVisitor visitor) {
1143 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1144 if (d != null) {
1145 final PackageManager pm = mContext.getPackageManager();
1146 try {
1147 ActivityInfo receiver = pm.getReceiverInfo(
1148 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001149 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001150 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1151 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001152 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001153 } catch (NameNotFoundException ex) {
1154 }
1155 }
1156 }
1157
1158 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001159 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001160 Bundle metaData = receiver.metaData;
1161 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001162 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001163 }
1164
1165 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1166 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001167 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001168 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001169 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001170 }
1171
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001172 CharSequence receiverLabel = receiver.loadLabel(pm);
1173 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001174 int priority;
1175 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1176 priority = requestedPriority;
1177 } else {
1178 priority = 0;
1179 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001180
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001181 try {
1182 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1183 XmlResourceParser parser = resources.getXml(configResId);
1184 try {
1185 XmlUtils.beginDocument(parser, "keyboard-layouts");
1186
1187 for (;;) {
1188 XmlUtils.nextElement(parser);
1189 String element = parser.getName();
1190 if (element == null) {
1191 break;
1192 }
1193 if (element.equals("keyboard-layout")) {
1194 TypedArray a = resources.obtainAttributes(
1195 parser, com.android.internal.R.styleable.KeyboardLayout);
1196 try {
1197 String name = a.getString(
1198 com.android.internal.R.styleable.KeyboardLayout_name);
1199 String label = a.getString(
1200 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001201 int keyboardLayoutResId = a.getResourceId(
1202 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1203 0);
Michael Wright07483422015-10-30 16:20:13 +00001204 String languageTags = a.getString(
1205 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001206 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001207 int vid = a.getInt(
1208 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1209 int pid = a.getInt(
1210 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1211
Jeff Brown2f095762012-05-10 21:29:33 -07001212 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001213 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001214 + "attributes in keyboard layout "
1215 + "resource from receiver "
1216 + receiver.packageName + "/" + receiver.name);
1217 } else {
1218 String descriptor = KeyboardLayoutDescriptor.format(
1219 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001220 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001221 KeyboardLayout layout = new KeyboardLayout(
1222 descriptor, label, collection, priority,
1223 locales, vid, pid);
1224 visitor.visitKeyboardLayout(
1225 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001226 }
1227 }
1228 } finally {
1229 a.recycle();
1230 }
1231 } else {
Michael Wright07483422015-10-30 16:20:13 +00001232 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001233 + "' in keyboard layout resource from receiver "
1234 + receiver.packageName + "/" + receiver.name);
1235 }
1236 }
1237 } finally {
1238 parser.close();
1239 }
1240 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001241 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001242 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001243 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001244 }
1245
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001246 @NonNull
1247 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001248 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001249 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001250 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001251 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001252 }
1253
RoboErikfb290df2013-12-16 11:27:55 -08001254 /**
1255 * Builds a layout descriptor for the vendor/product. This returns the
1256 * descriptor for ids that aren't useful (such as the default 0, 0).
1257 */
1258 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1259 if (identifier == null || identifier.getDescriptor() == null) {
1260 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001261 }
1262
RoboErikfb290df2013-12-16 11:27:55 -08001263 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1264 return identifier.getDescriptor();
1265 }
1266 StringBuilder bob = new StringBuilder();
1267 bob.append("vendor:").append(identifier.getVendorId());
1268 bob.append(",product:").append(identifier.getProductId());
1269 return bob.toString();
1270 }
1271
1272 @Override // Binder call
1273 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1274
1275 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001276 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001277 String layout = null;
1278 // try loading it using the layout descriptor if we have it
1279 layout = mDataStore.getCurrentKeyboardLayout(key);
1280 if (layout == null && !key.equals(identifier.getDescriptor())) {
1281 // if it doesn't exist fall back to the device descriptor
1282 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1283 }
1284 if (DEBUG) {
1285 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1286 + layout);
1287 }
1288 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001289 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001290 }
1291
1292 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001293 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001294 String keyboardLayoutDescriptor) {
1295 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001296 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001297 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1298 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001299 if (keyboardLayoutDescriptor == null) {
1300 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1301 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001302
RoboErikfb290df2013-12-16 11:27:55 -08001303 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001304 synchronized (mDataStore) {
1305 try {
RoboErikfb290df2013-12-16 11:27:55 -08001306 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1307 if (DEBUG) {
1308 Slog.d(TAG, "Saved keyboard layout using " + key);
1309 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001310 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1311 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001312 } finally {
1313 mDataStore.saveIfNeeded();
1314 }
1315 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001316 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001317
Jeff Browncf39bdf2012-05-18 14:41:19 -07001318 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001319 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001320 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001321 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001322 String[] layouts = mDataStore.getKeyboardLayouts(key);
1323 if ((layouts == null || layouts.length == 0)
1324 && !key.equals(identifier.getDescriptor())) {
1325 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1326 }
1327 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001328 }
1329 }
1330
1331 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001332 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001333 String keyboardLayoutDescriptor) {
1334 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1335 "addKeyboardLayoutForInputDevice()")) {
1336 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1337 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001338 if (keyboardLayoutDescriptor == null) {
1339 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1340 }
1341
RoboErikfb290df2013-12-16 11:27:55 -08001342 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001343 synchronized (mDataStore) {
1344 try {
RoboErikfb290df2013-12-16 11:27:55 -08001345 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1346 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1347 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1348 }
1349 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001350 && !Objects.equals(oldLayout,
1351 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001352 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1353 }
1354 } finally {
1355 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001356 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001357 }
1358 }
1359
1360 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001361 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001362 String keyboardLayoutDescriptor) {
1363 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1364 "removeKeyboardLayoutForInputDevice()")) {
1365 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1366 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001367 if (keyboardLayoutDescriptor == null) {
1368 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1369 }
1370
RoboErikfb290df2013-12-16 11:27:55 -08001371 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001372 synchronized (mDataStore) {
1373 try {
RoboErikfb290df2013-12-16 11:27:55 -08001374 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1375 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1376 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1377 }
1378 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1379 if (!key.equals(identifier.getDescriptor())) {
1380 // We need to remove from both places to ensure it is gone
1381 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1382 keyboardLayoutDescriptor);
1383 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001384 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001385 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001386 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1387 }
1388 } finally {
1389 mDataStore.saveIfNeeded();
1390 }
1391 }
1392 }
1393
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001394 public void switchKeyboardLayout(int deviceId, int direction) {
1395 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001396 }
1397
1398 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001399 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1400 final InputDevice device = getInputDevice(deviceId);
1401 if (device != null) {
1402 final boolean changed;
1403 final String keyboardLayoutDescriptor;
1404
1405 String key = getLayoutDescriptor(device.getIdentifier());
1406 synchronized (mDataStore) {
1407 try {
1408 changed = mDataStore.switchKeyboardLayout(key, direction);
1409 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1410 key);
1411 } finally {
1412 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001413 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001414 }
1415
1416 if (changed) {
1417 if (mSwitchedKeyboardLayoutToast != null) {
1418 mSwitchedKeyboardLayoutToast.cancel();
1419 mSwitchedKeyboardLayoutToast = null;
1420 }
1421 if (keyboardLayoutDescriptor != null) {
1422 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1423 if (keyboardLayout != null) {
1424 mSwitchedKeyboardLayoutToast = Toast.makeText(
1425 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1426 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001427 }
1428 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001429
1430 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001431 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001432 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001433 }
1434
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001435 public void setInputWindows(InputWindowHandle[] windowHandles, int displayId) {
Arthur Hung39134b22018-08-14 11:58:28 +08001436 nativeSetInputWindows(mPtr, windowHandles, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001437 }
RoboErikfb290df2013-12-16 11:27:55 -08001438
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001439 public void setFocusedApplication(int displayId, InputApplicationHandle application) {
1440 nativeSetFocusedApplication(mPtr, displayId, application);
1441 }
1442
1443 public void setFocusedWindow(InputWindowHandle focusedWindowHandle) {
1444 final IWindow newFocusedWindow =
1445 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1446 if (mFocusedWindow != newFocusedWindow) {
1447 if (mFocusedWindowHasCapture) {
1448 setPointerCapture(false);
1449 }
1450 mFocusedWindow = newFocusedWindow;
1451 }
1452 }
1453
1454 public void setFocusedDisplay(int displayId) {
1455 nativeSetFocusedDisplay(mPtr, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001456 }
RoboErikfb290df2013-12-16 11:27:55 -08001457
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001458 @Override
1459 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1460 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1461 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1462 + windowToken);
1463 return;
1464 }
1465 if (mFocusedWindowHasCapture == enabled) {
1466 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1467 return;
1468 }
1469 setPointerCapture(enabled);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001470 }
1471
1472 private void setPointerCapture(boolean enabled) {
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001473 if (mFocusedWindowHasCapture != enabled) {
1474 mFocusedWindowHasCapture = enabled;
1475 try {
1476 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1477 } catch (RemoteException ex) {
1478 /* ignore */
1479 }
1480 nativeSetPointerCapture(mPtr, enabled);
1481 }
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001482 }
1483
Jeff Brown349703e2010-06-22 01:27:15 -07001484 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001485 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001486 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001487
1488 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001489 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001490 }
1491
Jeff Browne6504122010-09-27 14:52:15 -07001492 /**
1493 * Atomically transfers touch focus from one window to another as identified by
1494 * their input channels. It is possible for multiple windows to have
1495 * touch focus if they support split touch dispatch
1496 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1497 * method only transfers touch focus of the specified window without affecting
1498 * other windows that may also have touch focus at the same time.
1499 * @param fromChannel The channel of a window that currently has touch focus.
1500 * @param toChannel The channel of the window that should receive touch focus in
1501 * place of the first.
1502 * @return True if the transfer was successful. False if the window with the
1503 * specified channel did not actually have touch focus at the time of the request.
1504 */
1505 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1506 if (fromChannel == null) {
1507 throw new IllegalArgumentException("fromChannel must not be null.");
1508 }
1509 if (toChannel == null) {
1510 throw new IllegalArgumentException("toChannel must not be null.");
1511 }
Jeff Brown4532e612012-04-05 14:27:12 -07001512 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001513 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001514
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001515 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001516 public void tryPointerSpeed(int speed) {
1517 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1518 "tryPointerSpeed()")) {
1519 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1520 }
1521
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001522 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1523 throw new IllegalArgumentException("speed out of range");
1524 }
1525
Jeff Brownac143512012-04-05 18:57:33 -07001526 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001527 }
1528
1529 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001530 int speed = getPointerSpeedSetting();
1531 setPointerSpeedUnchecked(speed);
1532 }
1533
1534 private void setPointerSpeedUnchecked(int speed) {
1535 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1536 InputManager.MAX_POINTER_SPEED);
1537 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001538 }
1539
1540 private void registerPointerSpeedSettingObserver() {
1541 mContext.getContentResolver().registerContentObserver(
1542 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001543 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001544 @Override
1545 public void onChange(boolean selfChange) {
1546 updatePointerSpeedFromSettings();
1547 }
Jeff Brownd4935962012-09-25 13:27:20 -07001548 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001549 }
1550
Jeff Brownac143512012-04-05 18:57:33 -07001551 private int getPointerSpeedSetting() {
1552 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001553 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001554 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1555 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001556 } catch (SettingNotFoundException snfe) {
1557 }
1558 return speed;
1559 }
1560
Jeff Browndaf4a122011-08-26 17:14:14 -07001561 public void updateShowTouchesFromSettings() {
1562 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001563 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001564 }
1565
1566 private void registerShowTouchesSettingObserver() {
1567 mContext.getContentResolver().registerContentObserver(
1568 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001569 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001570 @Override
1571 public void onChange(boolean selfChange) {
1572 updateShowTouchesFromSettings();
1573 }
Jeff Brownd4935962012-09-25 13:27:20 -07001574 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001575 }
1576
Jun Mukaie4e75da2015-12-15 16:19:20 -08001577 public void updateAccessibilityLargePointerFromSettings() {
1578 final int accessibilityConfig = Settings.Secure.getIntForUser(
1579 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1580 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001581 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001582 nativeReloadPointerIcons(mPtr);
1583 }
1584
Jun Mukai19a56012015-11-24 11:25:52 -08001585 private void registerAccessibilityLargePointerSettingObserver() {
1586 mContext.getContentResolver().registerContentObserver(
1587 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1588 new ContentObserver(mHandler) {
1589 @Override
1590 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001591 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001592 }
1593 }, UserHandle.USER_ALL);
1594 }
1595
Jeff Browndaf4a122011-08-26 17:14:14 -07001596 private int getShowTouchesSetting(int defaultValue) {
1597 int result = defaultValue;
1598 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001599 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1600 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001601 } catch (SettingNotFoundException snfe) {
1602 }
1603 return result;
1604 }
1605
Jeff Browna47425a2012-04-13 04:09:27 -07001606 // Binder call
1607 @Override
1608 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1609 if (repeat >= pattern.length) {
1610 throw new ArrayIndexOutOfBoundsException();
1611 }
1612
1613 VibratorToken v;
1614 synchronized (mVibratorLock) {
1615 v = mVibratorTokens.get(token);
1616 if (v == null) {
1617 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1618 try {
1619 token.linkToDeath(v, 0);
1620 } catch (RemoteException ex) {
1621 // give up
1622 throw new RuntimeException(ex);
1623 }
1624 mVibratorTokens.put(token, v);
1625 }
1626 }
1627
1628 synchronized (v) {
1629 v.mVibrating = true;
1630 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1631 }
1632 }
1633
1634 // Binder call
1635 @Override
1636 public void cancelVibrate(int deviceId, IBinder token) {
1637 VibratorToken v;
1638 synchronized (mVibratorLock) {
1639 v = mVibratorTokens.get(token);
1640 if (v == null || v.mDeviceId != deviceId) {
1641 return; // nothing to cancel
1642 }
1643 }
1644
1645 cancelVibrateIfNeeded(v);
1646 }
1647
1648 void onVibratorTokenDied(VibratorToken v) {
1649 synchronized (mVibratorLock) {
1650 mVibratorTokens.remove(v.mToken);
1651 }
1652
1653 cancelVibrateIfNeeded(v);
1654 }
1655
1656 private void cancelVibrateIfNeeded(VibratorToken v) {
1657 synchronized (v) {
1658 if (v.mVibrating) {
1659 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1660 v.mVibrating = false;
1661 }
1662 }
1663 }
1664
Jun Mukai19a56012015-11-24 11:25:52 -08001665 // Binder call
1666 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001667 public void setPointerIconType(int iconId) {
1668 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001669 }
Jun Mukai1db53972015-09-11 18:08:31 -07001670
Jun Mukaid4eaef72015-10-30 15:54:33 -07001671 // Binder call
1672 @Override
1673 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001674 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001675 nativeSetCustomPointerIcon(mPtr, icon);
1676 }
1677
Jeff Brown4532e612012-04-05 14:27:12 -07001678 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001679 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001680 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001681
1682 pw.println("INPUT MANAGER (dumpsys input)\n");
1683 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001684 if (dumpStr != null) {
1685 pw.println(dumpStr);
1686 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001687 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001688
Jeff Brownac143512012-04-05 18:57:33 -07001689 private boolean checkCallingPermission(String permission, String func) {
1690 // Quick check: if the calling permission is me, it's all okay.
1691 if (Binder.getCallingPid() == Process.myPid()) {
1692 return true;
1693 }
1694
1695 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1696 return true;
1697 }
1698 String msg = "Permission Denial: " + func + " from pid="
1699 + Binder.getCallingPid()
1700 + ", uid=" + Binder.getCallingUid()
1701 + " requires " + permission;
1702 Slog.w(TAG, msg);
1703 return false;
1704 }
1705
Jeff Brown4532e612012-04-05 14:27:12 -07001706 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001707 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001708 public void monitor() {
1709 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001710 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001711 }
1712
Andrii Kulianed76e742017-06-26 14:57:02 -07001713 // Binder call
1714 @Override
1715 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1716 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1717 "createInputForwarder()")) {
1718 throw new SecurityException("Requires INJECT_EVENTS permission");
1719 }
1720 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1721 final Display display = displayManager.getDisplay(displayId);
1722 if (display == null) {
1723 throw new IllegalArgumentException(
1724 "Can't create input forwarder for non-existent displayId: " + displayId);
1725 }
1726 final int callingUid = Binder.getCallingUid();
1727 final int displayOwnerUid = display.getOwnerUid();
1728 if (callingUid != displayOwnerUid) {
1729 throw new SecurityException(
1730 "Only owner of the display can forward input events to it.");
1731 }
1732
1733 return new InputForwarder(displayId);
1734 }
1735
Jeff Brown4532e612012-04-05 14:27:12 -07001736 // Native callback.
1737 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001738 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001739 }
1740
1741 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001742 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1743 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001744 if (!mInputDevicesChangedPending) {
1745 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001746 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1747 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001748 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001749
1750 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001751 }
1752 }
1753
1754 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001755 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1756 if (DEBUG) {
1757 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1758 + ", mask=" + Integer.toHexString(switchMask));
1759 }
1760
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001761 if ((switchMask & SW_LID_BIT) != 0) {
1762 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001763 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001764 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001765
Michael Wright3818c922014-09-02 13:59:07 -07001766 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001767 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001768 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1769 }
1770
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001771 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1772 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1773 switchMask);
1774 }
Michael Wright39e5e942015-08-19 22:52:47 +01001775
Michael Wright9209c9c2015-09-03 17:57:01 +01001776 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001777 SomeArgs args = SomeArgs.obtain();
1778 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1779 args.argi2 = (int) (whenNanos >> 32);
1780 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1781 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1782 args).sendToTarget();
1783 }
Jeff Brown4532e612012-04-05 14:27:12 -07001784 }
1785
1786 // Native callback.
1787 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001788 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001789 }
1790
1791 // Native callback.
1792 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001793 InputWindowHandle inputWindowHandle, String reason) {
1794 return mWindowManagerCallbacks.notifyANR(
1795 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001796 }
1797
1798 // Native callback.
1799 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1800 synchronized (mInputFilterLock) {
1801 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001802 try {
1803 mInputFilter.filterInputEvent(event, policyFlags);
1804 } catch (RemoteException e) {
1805 /* ignore */
1806 }
Jeff Brown4532e612012-04-05 14:27:12 -07001807 return false;
1808 }
1809 }
1810 event.recycle();
1811 return true;
1812 }
1813
1814 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001815 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1816 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001817 }
1818
1819 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001820 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1821 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001822 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001823 }
1824
1825 // Native callback.
1826 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1827 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001828 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001829 }
1830
1831 // Native callback.
1832 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1833 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001834 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001835 }
1836
1837 // Native callback.
1838 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1839 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1840 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1841 }
1842
1843 // Native callback.
1844 private int getVirtualKeyQuietTimeMillis() {
1845 return mContext.getResources().getInteger(
1846 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1847 }
1848
1849 // Native callback.
1850 private String[] getExcludedDeviceNames() {
1851 ArrayList<String> names = new ArrayList<String>();
1852
1853 // Read partner-provided list of excluded input devices
1854 XmlPullParser parser = null;
1855 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001856 final File[] baseDirs = {
1857 Environment.getRootDirectory(),
1858 Environment.getVendorDirectory()
1859 };
1860 for (File baseDir: baseDirs) {
1861 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
1862 FileReader confreader = null;
1863 try {
1864 confreader = new FileReader(confFile);
1865 parser = Xml.newPullParser();
1866 parser.setInput(confreader);
1867 XmlUtils.beginDocument(parser, "devices");
Jeff Brown4532e612012-04-05 14:27:12 -07001868
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001869 while (true) {
1870 XmlUtils.nextElement(parser);
1871 if (!"device".equals(parser.getName())) {
1872 break;
1873 }
1874 String name = parser.getAttributeValue(null, "name");
1875 if (name != null) {
1876 names.add(name);
1877 }
Jeff Brown4532e612012-04-05 14:27:12 -07001878 }
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001879 } catch (FileNotFoundException e) {
1880 // It's ok if the file does not exist.
1881 } catch (Exception e) {
1882 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1883 } finally {
1884 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001885 }
Jeff Brown4532e612012-04-05 14:27:12 -07001886 }
1887
1888 return names.toArray(new String[names.size()]);
1889 }
1890
1891 // Native callback.
1892 private int getKeyRepeatTimeout() {
1893 return ViewConfiguration.getKeyRepeatTimeout();
1894 }
1895
1896 // Native callback.
1897 private int getKeyRepeatDelay() {
1898 return ViewConfiguration.getKeyRepeatDelay();
1899 }
1900
1901 // Native callback.
1902 private int getHoverTapTimeout() {
1903 return ViewConfiguration.getHoverTapTimeout();
1904 }
1905
1906 // Native callback.
1907 private int getHoverTapSlop() {
1908 return ViewConfiguration.getHoverTapSlop();
1909 }
1910
1911 // Native callback.
1912 private int getDoubleTapTimeout() {
1913 return ViewConfiguration.getDoubleTapTimeout();
1914 }
1915
1916 // Native callback.
1917 private int getLongPressTimeout() {
1918 return ViewConfiguration.getLongPressTimeout();
1919 }
1920
1921 // Native callback.
1922 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001923 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001924 }
1925
1926 // Native callback.
1927 private PointerIcon getPointerIcon() {
1928 return PointerIcon.getDefaultIcon(mContext);
1929 }
1930
Jeff Brown6ec6f792012-04-17 16:52:41 -07001931 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001932 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001933 if (!mSystemReady) {
1934 return null;
1935 }
1936
RoboErikfb290df2013-12-16 11:27:55 -08001937 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001938 if (keyboardLayoutDescriptor == null) {
1939 return null;
1940 }
1941
1942 final String[] result = new String[2];
1943 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1944 @Override
Michael Wright07483422015-10-30 16:20:13 +00001945 public void visitKeyboardLayout(Resources resources,
1946 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001947 try {
Michael Wright07483422015-10-30 16:20:13 +00001948 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001949 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001950 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001951 } catch (IOException ex) {
1952 } catch (NotFoundException ex) {
1953 }
1954 }
1955 });
1956 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001957 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001958 + keyboardLayoutDescriptor + "'.");
1959 return null;
1960 }
1961 return result;
1962 }
1963
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001964 // Native callback.
1965 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001966 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1967 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1968 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001969 }
1970 return null;
1971 }
1972
Jeff Brown4532e612012-04-05 14:27:12 -07001973 /**
1974 * Callback interface implemented by the Window Manager.
1975 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001976 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001977 public void notifyConfigurationChanged();
1978
1979 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1980
Michael Wright3818c922014-09-02 13:59:07 -07001981 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
1982
Jeff Brown4532e612012-04-05 14:27:12 -07001983 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1984
1985 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001986 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001987
Jeff Brown037c33e2014-04-09 00:31:55 -07001988 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001989
Michael Wright70af00a2014-09-03 19:30:20 -07001990 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001991
1992 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1993 KeyEvent event, int policyFlags);
1994
1995 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1996 KeyEvent event, int policyFlags);
1997
1998 public int getPointerLayer();
1999 }
2000
2001 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002002 * Callback interface implemented by WiredAccessoryObserver.
2003 */
2004 public interface WiredAccessoryCallbacks {
2005 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002006 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002007 }
2008
2009 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002010 * Private handler for the input manager.
2011 */
2012 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002013 public InputManagerHandler(Looper looper) {
2014 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002015 }
2016
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002017 @Override
2018 public void handleMessage(Message msg) {
2019 switch (msg.what) {
2020 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002021 deliverInputDevicesChanged((InputDevice[])msg.obj);
2022 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002023 case MSG_SWITCH_KEYBOARD_LAYOUT:
2024 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002025 break;
2026 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2027 reloadKeyboardLayouts();
2028 break;
2029 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2030 updateKeyboardLayouts();
2031 break;
2032 case MSG_RELOAD_DEVICE_ALIASES:
2033 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002034 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002035 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002036 SomeArgs args = (SomeArgs) msg.obj;
2037 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2038 boolean inTabletMode = (boolean) args.arg1;
2039 deliverTabletModeChanged(whenNanos, inTabletMode);
2040 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002041 }
2042 }
2043 }
2044
2045 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002046 * Hosting interface for input filters to call back into the input manager.
2047 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002048 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002049 private boolean mDisconnected;
2050
2051 public void disconnectLocked() {
2052 mDisconnected = true;
2053 }
2054
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002055 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002056 public void sendInputEvent(InputEvent event, int policyFlags) {
2057 if (event == null) {
2058 throw new IllegalArgumentException("event must not be null");
2059 }
2060
2061 synchronized (mInputFilterLock) {
2062 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002063 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002064 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002065 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2066 }
2067 }
2068 }
2069 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002070
2071 private static final class KeyboardLayoutDescriptor {
2072 public String packageName;
2073 public String receiverName;
2074 public String keyboardLayoutName;
2075
2076 public static String format(String packageName,
2077 String receiverName, String keyboardName) {
2078 return packageName + "/" + receiverName + "/" + keyboardName;
2079 }
2080
2081 public static KeyboardLayoutDescriptor parse(String descriptor) {
2082 int pos = descriptor.indexOf('/');
2083 if (pos < 0 || pos + 1 == descriptor.length()) {
2084 return null;
2085 }
2086 int pos2 = descriptor.indexOf('/', pos + 1);
2087 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2088 return null;
2089 }
2090
2091 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2092 result.packageName = descriptor.substring(0, pos);
2093 result.receiverName = descriptor.substring(pos + 1, pos2);
2094 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2095 return result;
2096 }
2097 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002098
Jeff Brown6ec6f792012-04-17 16:52:41 -07002099 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002100 void visitKeyboardLayout(Resources resources,
2101 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002102 }
2103
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002104 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2105 private final int mPid;
2106 private final IInputDevicesChangedListener mListener;
2107
2108 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2109 mPid = pid;
2110 mListener = listener;
2111 }
2112
2113 @Override
2114 public void binderDied() {
2115 if (DEBUG) {
2116 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2117 }
2118 onInputDevicesChangedListenerDied(mPid);
2119 }
2120
2121 public void notifyInputDevicesChanged(int[] info) {
2122 try {
2123 mListener.onInputDevicesChanged(info);
2124 } catch (RemoteException ex) {
2125 Slog.w(TAG, "Failed to notify process "
2126 + mPid + " that input devices changed, assuming it died.", ex);
2127 binderDied();
2128 }
2129 }
2130 }
Jeff Browna47425a2012-04-13 04:09:27 -07002131
Michael Wright39e5e942015-08-19 22:52:47 +01002132 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2133 private final int mPid;
2134 private final ITabletModeChangedListener mListener;
2135
2136 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2137 mPid = pid;
2138 mListener = listener;
2139 }
2140
2141 @Override
2142 public void binderDied() {
2143 if (DEBUG) {
2144 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2145 }
2146 onTabletModeChangedListenerDied(mPid);
2147 }
2148
2149 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2150 try {
2151 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2152 } catch (RemoteException ex) {
2153 Slog.w(TAG, "Failed to notify process " + mPid +
2154 " that tablet mode changed, assuming it died.", ex);
2155 binderDied();
2156 }
2157 }
2158 }
2159
Jeff Browna47425a2012-04-13 04:09:27 -07002160 private final class VibratorToken implements DeathRecipient {
2161 public final int mDeviceId;
2162 public final IBinder mToken;
2163 public final int mTokenValue;
2164
2165 public boolean mVibrating;
2166
2167 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2168 mDeviceId = deviceId;
2169 mToken = token;
2170 mTokenValue = tokenValue;
2171 }
2172
2173 @Override
2174 public void binderDied() {
2175 if (DEBUG) {
2176 Slog.d(TAG, "Vibrator token died.");
2177 }
2178 onVibratorTokenDied(this);
2179 }
2180 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002181
2182 private final class LocalService extends InputManagerInternal {
2183 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002184 public void setDisplayViewports(List<DisplayViewport> viewports) {
2185 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002186 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002187
2188 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002189 public boolean injectInputEvent(InputEvent event, int mode) {
2190 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002191 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002192
2193 @Override
2194 public void setInteractive(boolean interactive) {
2195 nativeSetInteractive(mPtr, interactive);
2196 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002197
2198 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002199 public void toggleCapsLock(int deviceId) {
2200 nativeToggleCapsLock(mPtr, deviceId);
2201 }
Adrian Roos99182342016-06-15 15:30:46 -07002202
2203 @Override
2204 public void setPulseGestureEnabled(boolean enabled) {
2205 if (mDoubleTouchGestureEnableFile != null) {
2206 FileWriter writer = null;
2207 try {
2208 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2209 writer.write(enabled ? "1" : "0");
2210 } catch (IOException e) {
2211 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2212 } finally {
2213 IoUtils.closeQuietly(writer);
2214 }
2215 }
2216 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002217 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002218}