blob: b33870559f597d44004eb069c1c6e56144925acd [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;
Jeff Browncf39bdf2012-05-18 14:41:19 -070020import android.app.Notification;
21import android.app.NotificationManager;
22import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070023import android.bluetooth.BluetoothAdapter;
24import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070025import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070026import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070027import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070028import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070029import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070030import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070031import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070032import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070033import android.content.pm.PackageManager.NameNotFoundException;
Arthur Hung39134b22018-08-14 11:58:28 +080034import android.content.pm.ResolveInfo;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070035import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070036import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070037import android.content.res.TypedArray;
38import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070039import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070040import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080041import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070042import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070043import android.hardware.input.IInputManager;
Arthur Hung39134b22018-08-14 11:58:28 +080044import android.hardware.input.ITabletModeChangedListener;
RoboErikfb290df2013-12-16 11:27:55 -080045import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070046import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080047import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070048import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080049import android.hardware.input.TouchCalibration;
Dmitry Shmidt38ab71c2019-09-19 15:28:30 -070050import android.media.AudioManager;
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;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070067import android.util.Pair;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.util.SparseArray;
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;
Michael Wrightc7995232019-02-14 12:33:46 +000073import android.view.IInputMonitorHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080074import android.view.IWindow;
Robert Carr788f5742018-07-30 17:46:45 -070075import android.view.InputApplicationHandle;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070076import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070077import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070078import android.view.InputEvent;
Michael Wrightc7995232019-02-14 12:33:46 +000079import android.view.InputMonitor;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070080import android.view.InputWindowHandle;
Jeff Brown1f245102010-11-18 20:53:46 -080081import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070082import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070083import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080084import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080085import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070086
Arthur Hung39134b22018-08-14 11:58:28 +080087import com.android.internal.R;
88import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
89import com.android.internal.notification.SystemNotificationChannels;
90import com.android.internal.os.SomeArgs;
91import com.android.internal.util.DumpUtils;
92import com.android.internal.util.Preconditions;
93import com.android.internal.util.XmlUtils;
94import com.android.server.DisplayThread;
95import com.android.server.LocalServices;
96import com.android.server.Watchdog;
97import com.android.server.policy.WindowManagerPolicy;
98
99import libcore.io.IoUtils;
100import libcore.io.Streams;
101
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700103import java.io.FileDescriptor;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700104import java.io.FileInputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.FileNotFoundException;
Adrian Roos99182342016-06-15 15:30:46 -0700106import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700107import java.io.IOException;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700108import java.io.InputStream;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700109import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700110import java.io.PrintWriter;
111import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000112import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700113import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700114import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100115import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000116import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000117import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700118
Jeff Brown46b9ac02010-04-22 18:58:52 -0700119/*
120 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700122public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800123 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700124 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700125 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700126
Jeff Brown4532e612012-04-05 14:27:12 -0700127 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700128 private static final String PORT_ASSOCIATIONS_PATH = "etc/input-port-associations.xml";
Jeff Brown4532e612012-04-05 14:27:12 -0700129
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700130 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700131 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
132 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
133 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
134 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100135 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700136
Jeff Brown4532e612012-04-05 14:27:12 -0700137 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000138 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700139
Jeff Brown46b9ac02010-04-22 18:58:52 -0700140 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700141 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700142
Andrii Kulianfd8666d2018-10-05 16:58:39 -0700143 // Context cache used for loading pointer resources.
144 private Context mDisplayContext;
145
Adrian Roos99182342016-06-15 15:30:46 -0700146 private final File mDoubleTouchGestureEnableFile;
147
Jeff Browna9d131c2012-09-20 16:48:17 -0700148 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700149 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700150 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700151 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700152
Michael Wright39e5e942015-08-19 22:52:47 +0100153 private final Object mTabletModeLock = new Object();
154 // List of currently registered tablet mode changed listeners by process id
155 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
156 new SparseArray<>(); // guarded by mTabletModeLock
157 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
158 new ArrayList<>();
159
Jeff Browna3bc5652012-04-17 11:42:25 -0700160 // Persistent data store. Must be locked each time during use.
161 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700162
163 // List of currently registered input devices changed listeners by process id.
164 private Object mInputDevicesLock = new Object();
165 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
166 private InputDevice[] mInputDevices = new InputDevice[0];
167 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
168 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
169 private final ArrayList<InputDevicesChangedListenerRecord>
170 mTempInputDevicesChangedListenersToNotify =
171 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700172 private final ArrayList<InputDevice>
173 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
174 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800175 private PendingIntent mKeyboardLayoutIntent;
176 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177
Jeff Browna47425a2012-04-13 04:09:27 -0700178 // State for vibrator tokens.
179 private Object mVibratorLock = new Object();
180 private HashMap<IBinder, VibratorToken> mVibratorTokens =
181 new HashMap<IBinder, VibratorToken>();
182 private int mNextVibratorTokenValue;
183
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700184 // State for the currently installed input filter.
185 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700186 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700187 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700188
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800189 private IWindow mFocusedWindow;
190 private boolean mFocusedWindowHasCapture;
191
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000192 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700193 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000194 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100195 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700196 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700197
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700199 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000200 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700201 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000202 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700203 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000204 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700205 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000206 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Robert Carre0a353c2018-08-02 16:38:04 -0700207 int displayId);
Michael Wrightc7995232019-02-14 12:33:46 +0000208 private static native void nativeRegisterInputMonitor(long ptr, InputChannel inputChannel,
209 int displayId, boolean isGestureMonitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000210 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
Michael Wrightc7995232019-02-14 12:33:46 +0000211 private static native void nativePilferPointers(long ptr, IBinder token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000212 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800213 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700214 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
215 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800216 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800217 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
218 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
220 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
221 private static native void nativeSetFocusedApplication(long ptr,
Tiger Huang1e5b10a2018-07-30 20:19:51 +0800222 int displayId, InputApplicationHandle application);
223 private static native void nativeSetFocusedDisplay(long ptr, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000224 private static native void nativeSetPointerSpeed(long ptr, int speed);
225 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700226 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800227 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000228 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700229 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000230 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
231 private static native void nativeReloadKeyboardLayouts(long ptr);
232 private static native void nativeReloadDeviceAliases(long ptr);
233 private static native String nativeDump(long ptr);
234 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700235 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
236 private static native void nativeEnableInputDevice(long ptr, int deviceId);
237 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100238 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800239 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700240 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800241 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Arthur Hung82bbfc32018-11-29 20:24:51 +0800242 private static native boolean nativeCanDispatchToDisplay(long ptr, int deviceId, int displayId);
Jeff Brown4532e612012-04-05 14:27:12 -0700243
Jeff Brownac143512012-04-05 18:57:33 -0700244 // Input event injection constants defined in InputDispatcher.h.
245 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
246 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
247 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
248 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
249
250 // Maximum number of milliseconds to wait for input event injection.
251 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
252
Jeff Brown6d0fec22010-07-23 21:28:06 -0700253 // Key states (may be returned by queries about the current state of a
254 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700255
Jeff Brown6d0fec22010-07-23 21:28:06 -0700256 /** The key state is unknown or the requested key itself is not supported. */
257 public static final int KEY_STATE_UNKNOWN = -1;
258
259 /** The key is up. /*/
260 public static final int KEY_STATE_UP = 0;
261
262 /** The key is down. */
263 public static final int KEY_STATE_DOWN = 1;
264
265 /** The key is down but is a virtual key press that is being emulated by the system. */
266 public static final int KEY_STATE_VIRTUAL = 2;
267
Jeff Brownc458ce92012-04-30 14:58:40 -0700268 /** Scan code: Mouse / trackball button. */
269 public static final int BTN_MOUSE = 0x110;
270
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700271 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700272 /** Switch code: Lid switch. When set, lid is shut. */
273 public static final int SW_LID = 0x00;
274
Michael Wright39e5e942015-08-19 22:52:47 +0100275 /** Switch code: Tablet mode switch.
276 * When set, the device is in tablet mode (i.e. no keyboard is connected).
277 */
278 public static final int SW_TABLET_MODE = 0x01;
279
Jeff Brownc458ce92012-04-30 14:58:40 -0700280 /** Switch code: Keypad slide. When set, keyboard is exposed. */
281 public static final int SW_KEYPAD_SLIDE = 0x0a;
282
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700283 /** Switch code: Headphone. When set, headphone is inserted. */
284 public static final int SW_HEADPHONE_INSERT = 0x02;
285
286 /** Switch code: Microphone. When set, microphone is inserted. */
287 public static final int SW_MICROPHONE_INSERT = 0x04;
288
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500289 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
290 public static final int SW_LINEOUT_INSERT = 0x06;
291
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700292 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
293 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
294
Michael Wright3818c922014-09-02 13:59:07 -0700295 /** Switch code: Camera lens cover. When set the lens is covered. */
296 public static final int SW_CAMERA_LENS_COVER = 0x09;
297
Dmitry Shmidtd6cf4d92019-09-20 15:50:36 -0700298 /** Switch code: Microphone. When set it is off. */
299 public static final int SW_MUTE_DEVICE = 0x0e;
300
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700301 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100302 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700303 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
304 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
305 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500306 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700307 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
308 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500309 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700310 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Dmitry Shmidtd6cf4d92019-09-20 15:50:36 -0700311 public static final int SW_MUTE_DEVICE_BIT = 1 << SW_MUTE_DEVICE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700312
313 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
314 final boolean mUseDevInputEventForAudioJack;
315
Jeff Brown4ccb8232014-01-16 22:16:42 -0800316 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700317 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800318 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800319
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700320 mUseDevInputEventForAudioJack =
321 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
322 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
323 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700324 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800325
Adrian Roos99182342016-06-15 15:30:46 -0700326 String doubleTouchGestureEnablePath = context.getResources().getString(
327 R.string.config_doubleTouchGestureEnableFile);
328 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
329 new File(doubleTouchGestureEnablePath);
330
Jeff Brown4ccb8232014-01-16 22:16:42 -0800331 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700332 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700333
Jeff Browna9d131c2012-09-20 16:48:17 -0700334 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
335 mWindowManagerCallbacks = callbacks;
336 }
337
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700338 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
339 mWiredAccessoryCallbacks = callbacks;
340 }
341
Jeff Brown46b9ac02010-04-22 18:58:52 -0700342 public void start() {
343 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700344 nativeStart(mPtr);
345
346 // Add ourself to the Watchdog monitors.
347 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700348
349 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700350 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800351 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700352
Jeff Brownd4935962012-09-25 13:27:20 -0700353 mContext.registerReceiver(new BroadcastReceiver() {
354 @Override
355 public void onReceive(Context context, Intent intent) {
356 updatePointerSpeedFromSettings();
357 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800358 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700359 }
360 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
361
Jeff Brown1a84fd12011-06-02 01:26:32 -0700362 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700363 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800364 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700365 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700366
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100367 // TODO(BT) Pass in parameter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700368 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700369 if (DEBUG) {
370 Slog.d(TAG, "System ready.");
371 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700372 mNotificationManager = (NotificationManager)mContext.getSystemService(
373 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700374 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700375
376 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
377 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
378 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800379 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700380 filter.addDataScheme("package");
381 mContext.registerReceiver(new BroadcastReceiver() {
382 @Override
383 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700384 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700385 }
386 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700387
388 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
389 mContext.registerReceiver(new BroadcastReceiver() {
390 @Override
391 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700392 reloadDeviceAliases();
393 }
394 }, filter, null, mHandler);
395
Jeff Browncf39bdf2012-05-18 14:41:19 -0700396 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
397 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700398
399 if (mWiredAccessoryCallbacks != null) {
400 mWiredAccessoryCallbacks.systemReady();
401 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700402 }
403
404 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700405 if (DEBUG) {
406 Slog.d(TAG, "Reloading keyboard layouts.");
407 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700408 nativeReloadKeyboardLayouts(mPtr);
409 }
410
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700411 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700412 if (DEBUG) {
413 Slog.d(TAG, "Reloading device names.");
414 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700415 nativeReloadDeviceAliases(mPtr);
416 }
417
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100418 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
419 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420 }
Jeff Brownac143512012-04-05 18:57:33 -0700421
Jeff Brown6d0fec22010-07-23 21:28:06 -0700422 /**
423 * Gets the current state of a key or button by key 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 keyCode The key code to check.
429 * @return The key state.
430 */
431 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700432 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700433 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700434
Jeff Brown6d0fec22010-07-23 21:28:06 -0700435 /**
436 * Gets the current state of a key or button by scan 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 scanCode The scan code to check.
442 * @return The key state.
443 */
444 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700445 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700446 }
RoboErikfb290df2013-12-16 11:27:55 -0800447
Jeff Brown6d0fec22010-07-23 21:28:06 -0700448 /**
449 * Gets the current state of a switch by switch code.
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 switchCode The switch code to check.
455 * @return The switch state.
456 */
457 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700458 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700459 }
460
Jeff Brown6d0fec22010-07-23 21:28:06 -0700461 /**
462 * Determines whether the specified key codes are supported by a particular device.
463 * @param deviceId The input device id, or -1 to consult all devices.
464 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
465 * consider all input sources. An input device is consulted if at least one of its
466 * non-class input source bits matches the specified source mask.
467 * @param keyCodes The array of key codes to check.
468 * @param keyExists An array at least as large as keyCodes whose entries will be set
469 * to true or false based on the presence or absence of support for the corresponding
470 * key codes.
471 * @return True if the lookup was successful, false otherwise.
472 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700473 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700474 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700475 if (keyCodes == null) {
476 throw new IllegalArgumentException("keyCodes must not be null.");
477 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700478 if (keyExists == null || keyExists.length < keyCodes.length) {
479 throw new IllegalArgumentException("keyExists must not be null and must be at "
480 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700481 }
RoboErikfb290df2013-12-16 11:27:55 -0800482
Jeff Brown4532e612012-04-05 14:27:12 -0700483 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700484 }
RoboErikfb290df2013-12-16 11:27:55 -0800485
Jeff Browna41ca772010-08-11 14:46:32 -0700486 /**
487 * Creates an input channel that will receive all input from the input dispatcher.
488 * @param inputChannelName The input channel name.
Arthur Hungbe5ce212018-09-13 18:41:56 +0800489 * @param displayId Target display id.
Jeff Browna41ca772010-08-11 14:46:32 -0700490 * @return The input channel.
491 */
Arthur Hungbe5ce212018-09-13 18:41:56 +0800492 public InputChannel monitorInput(String inputChannelName, int displayId) {
Jeff Browna41ca772010-08-11 14:46:32 -0700493 if (inputChannelName == null) {
494 throw new IllegalArgumentException("inputChannelName must not be null.");
495 }
RoboErikfb290df2013-12-16 11:27:55 -0800496
Arthur Hungbe5ce212018-09-13 18:41:56 +0800497 if (displayId < Display.DEFAULT_DISPLAY) {
498 throw new IllegalArgumentException("displayId must >= 0.");
499 }
500
Jeff Browna41ca772010-08-11 14:46:32 -0700501 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Michael Wrightc7995232019-02-14 12:33:46 +0000502 // Give the output channel a token just for identity purposes.
503 inputChannels[0].setToken(new Binder());
504 nativeRegisterInputMonitor(mPtr, inputChannels[0], displayId, false /*isGestureMonitor*/);
Jeff Browna41ca772010-08-11 14:46:32 -0700505 inputChannels[0].dispose(); // don't need to retain the Java object reference
506 return inputChannels[1];
507 }
508
509 /**
Michael Wrightc7995232019-02-14 12:33:46 +0000510 * Creates an input monitor that will receive pointer events for the purposes of system-wide
511 * gesture interpretation.
512 *
513 * @param inputChannelName The input channel name.
514 * @param displayId Target display id.
515 * @return The input channel.
516 */
517 @Override // Binder call
518 public InputMonitor monitorGestureInput(String inputChannelName, int displayId) {
519 if (!checkCallingPermission(android.Manifest.permission.MONITOR_INPUT,
520 "monitorInputRegion()")) {
521 throw new SecurityException("Requires MONITOR_INPUT permission");
522 }
523
524 Objects.requireNonNull(inputChannelName, "inputChannelName must not be null.");
525
526 if (displayId < Display.DEFAULT_DISPLAY) {
527 throw new IllegalArgumentException("displayId must >= 0.");
528 }
529
530
Michael Wrightad3a6bf2019-04-04 14:17:09 +0100531 final long ident = Binder.clearCallingIdentity();
532 try {
533 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
534 InputMonitorHost host = new InputMonitorHost(inputChannels[0]);
535 inputChannels[0].setToken(host.asBinder());
536 nativeRegisterInputMonitor(mPtr, inputChannels[0], displayId,
537 true /*isGestureMonitor*/);
538 return new InputMonitor(inputChannelName, inputChannels[1], host);
539 } finally {
540 Binder.restoreCallingIdentity(ident);
541 }
Michael Wrightc7995232019-02-14 12:33:46 +0000542 }
543
544 /**
Jeff Browna41ca772010-08-11 14:46:32 -0700545 * Registers an input channel so that it can be used as an input event target.
546 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800547 * @param inputWindowHandle The handle of the input window associated with the
548 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700549 */
Robert Carre0a353c2018-08-02 16:38:04 -0700550 public void registerInputChannel(InputChannel inputChannel, IBinder token) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700551 if (inputChannel == null) {
552 throw new IllegalArgumentException("inputChannel must not be null.");
553 }
RoboErikfb290df2013-12-16 11:27:55 -0800554
Robert Carre0a353c2018-08-02 16:38:04 -0700555 if (token == null) {
556 token = new Binder();
557 }
558 inputChannel.setToken(token);
559
560 nativeRegisterInputChannel(mPtr, inputChannel, Display.INVALID_DISPLAY);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700561 }
RoboErikfb290df2013-12-16 11:27:55 -0800562
Jeff Browna41ca772010-08-11 14:46:32 -0700563 /**
564 * Unregisters an input channel.
565 * @param inputChannel The input channel to unregister.
566 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700567 public void unregisterInputChannel(InputChannel inputChannel) {
568 if (inputChannel == null) {
569 throw new IllegalArgumentException("inputChannel must not be null.");
570 }
RoboErikfb290df2013-12-16 11:27:55 -0800571
Jeff Brown4532e612012-04-05 14:27:12 -0700572 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700573 }
Jeff Brown0029c662011-03-30 02:25:18 -0700574
575 /**
576 * Sets an input filter that will receive all input events before they are dispatched.
577 * The input filter may then reinterpret input events or inject new ones.
578 *
579 * To ensure consistency, the input dispatcher automatically drops all events
580 * in progress whenever an input filter is installed or uninstalled. After an input
581 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
582 * Any events it attempts to send after it has been uninstalled will be dropped.
583 *
584 * @param filter The input filter, or null to remove the current filter.
585 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700586 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700587 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700588 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700589 if (oldFilter == filter) {
590 return; // nothing to do
591 }
592
593 if (oldFilter != null) {
594 mInputFilter = null;
595 mInputFilterHost.disconnectLocked();
596 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700597 try {
598 oldFilter.uninstall();
599 } catch (RemoteException re) {
600 /* ignore */
601 }
Jeff Brown0029c662011-03-30 02:25:18 -0700602 }
603
604 if (filter != null) {
605 mInputFilter = filter;
606 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700607 try {
608 filter.install(mInputFilterHost);
609 } catch (RemoteException re) {
610 /* ignore */
611 }
Jeff Brown0029c662011-03-30 02:25:18 -0700612 }
613
Jeff Brown4532e612012-04-05 14:27:12 -0700614 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700615 }
616 }
617
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700618 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700619 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800620 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800621 }
622
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800623 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700624 if (event == null) {
625 throw new IllegalArgumentException("event must not be null");
626 }
Jeff Brownac143512012-04-05 18:57:33 -0700627 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
628 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
629 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
630 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700631 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700632
Jeff Brownac143512012-04-05 18:57:33 -0700633 final int pid = Binder.getCallingPid();
634 final int uid = Binder.getCallingUid();
635 final long ident = Binder.clearCallingIdentity();
636 final int result;
637 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800638 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700639 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
640 } finally {
641 Binder.restoreCallingIdentity(ident);
642 }
643 switch (result) {
644 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
645 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
646 throw new SecurityException(
647 "Injecting to another application requires INJECT_EVENTS permission");
648 case INPUT_EVENT_INJECTION_SUCCEEDED:
649 return true;
650 case INPUT_EVENT_INJECTION_TIMED_OUT:
651 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
652 return false;
653 case INPUT_EVENT_INJECTION_FAILED:
654 default:
655 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
656 return false;
657 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700658 }
Jeff Brown0029c662011-03-30 02:25:18 -0700659
Jeff Brown8d608662010-08-30 03:02:23 -0700660 /**
661 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700662 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700663 * @return The input device or null if not found.
664 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700665 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700666 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700667 synchronized (mInputDevicesLock) {
668 final int count = mInputDevices.length;
669 for (int i = 0; i < count; i++) {
670 final InputDevice inputDevice = mInputDevices[i];
671 if (inputDevice.getId() == deviceId) {
672 return inputDevice;
673 }
674 }
675 }
676 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700677 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700678
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700679 // Binder call
680 @Override
681 public boolean isInputDeviceEnabled(int deviceId) {
682 return nativeIsInputDeviceEnabled(mPtr, deviceId);
683 }
684
685 // Binder call
686 @Override
687 public void enableInputDevice(int deviceId) {
688 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
689 "enableInputDevice()")) {
690 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
691 }
692 nativeEnableInputDevice(mPtr, deviceId);
693 }
694
695 // Binder call
696 @Override
697 public void disableInputDevice(int deviceId) {
698 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
699 "disableInputDevice()")) {
700 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
701 }
702 nativeDisableInputDevice(mPtr, deviceId);
703 }
704
Jeff Brown8d608662010-08-30 03:02:23 -0700705 /**
706 * Gets the ids of all input devices in the system.
707 * @return The input device ids.
708 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700709 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700710 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700711 synchronized (mInputDevicesLock) {
712 final int count = mInputDevices.length;
713 int[] ids = new int[count];
714 for (int i = 0; i < count; i++) {
715 ids[i] = mInputDevices[i].getId();
716 }
717 return ids;
718 }
719 }
720
Jeff Browndaa37532012-05-01 15:54:03 -0700721 /**
722 * Gets all input devices in the system.
723 * @return The array of input devices.
724 */
725 public InputDevice[] getInputDevices() {
726 synchronized (mInputDevicesLock) {
727 return mInputDevices;
728 }
729 }
730
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700731 @Override // Binder call
732 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
733 if (listener == null) {
734 throw new IllegalArgumentException("listener must not be null");
735 }
736
737 synchronized (mInputDevicesLock) {
738 int callingPid = Binder.getCallingPid();
739 if (mInputDevicesChangedListeners.get(callingPid) != null) {
740 throw new SecurityException("The calling process has already "
741 + "registered an InputDevicesChangedListener.");
742 }
743
744 InputDevicesChangedListenerRecord record =
745 new InputDevicesChangedListenerRecord(callingPid, listener);
746 try {
747 IBinder binder = listener.asBinder();
748 binder.linkToDeath(record, 0);
749 } catch (RemoteException ex) {
750 // give up
751 throw new RuntimeException(ex);
752 }
753
754 mInputDevicesChangedListeners.put(callingPid, record);
755 }
756 }
757
758 private void onInputDevicesChangedListenerDied(int pid) {
759 synchronized (mInputDevicesLock) {
760 mInputDevicesChangedListeners.remove(pid);
761 }
762 }
763
764 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700765 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
766 // Scan for changes.
767 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700768 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700769 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700770 final int numListeners;
771 final int[] deviceIdAndGeneration;
772 synchronized (mInputDevicesLock) {
773 if (!mInputDevicesChangedPending) {
774 return;
775 }
776 mInputDevicesChangedPending = false;
777
778 numListeners = mInputDevicesChangedListeners.size();
779 for (int i = 0; i < numListeners; i++) {
780 mTempInputDevicesChangedListenersToNotify.add(
781 mInputDevicesChangedListeners.valueAt(i));
782 }
783
784 final int numDevices = mInputDevices.length;
785 deviceIdAndGeneration = new int[numDevices * 2];
786 for (int i = 0; i < numDevices; i++) {
787 final InputDevice inputDevice = mInputDevices[i];
788 deviceIdAndGeneration[i * 2] = inputDevice.getId();
789 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700790
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700791 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700792 if (!containsInputDeviceWithDescriptor(oldInputDevices,
793 inputDevice.getDescriptor())) {
794 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
795 } else {
796 mTempFullKeyboards.add(inputDevice);
797 }
798 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700799 }
800 }
801
Jeff Browncf39bdf2012-05-18 14:41:19 -0700802 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700803 for (int i = 0; i < numListeners; i++) {
804 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
805 deviceIdAndGeneration);
806 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700807 mTempInputDevicesChangedListenersToNotify.clear();
808
809 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000810 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
811 final int numFullKeyboards = mTempFullKeyboards.size();
812 synchronized (mDataStore) {
813 for (int i = 0; i < numFullKeyboards; i++) {
814 final InputDevice inputDevice = mTempFullKeyboards.get(i);
815 String layout =
816 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
817 if (layout == null) {
818 layout = getDefaultKeyboardLayout(inputDevice);
819 if (layout != null) {
820 setCurrentKeyboardLayoutForInputDevice(
821 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700822 }
823 }
Michael Wright07483422015-10-30 16:20:13 +0000824 if (layout == null) {
825 keyboardsMissingLayout.add(inputDevice);
826 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700827 }
Michael Wright07483422015-10-30 16:20:13 +0000828 }
829
830 if (mNotificationManager != null) {
831 if (!keyboardsMissingLayout.isEmpty()) {
832 if (keyboardsMissingLayout.size() > 1) {
833 // We have more than one keyboard missing a layout, so drop the
834 // user at the generic input methods page so they can pick which
835 // one to set.
836 showMissingKeyboardLayoutNotification(null);
837 } else {
838 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700839 }
840 } else if (mKeyboardLayoutNotificationShown) {
841 hideMissingKeyboardLayoutNotification();
842 }
843 }
844 mTempFullKeyboards.clear();
845 }
846
Michael Wright07483422015-10-30 16:20:13 +0000847 private String getDefaultKeyboardLayout(final InputDevice d) {
848 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
849 // If our locale doesn't have a language for some reason, then we don't really have a
850 // reasonable default.
851 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
852 return null;
853 }
854 final List<KeyboardLayout> layouts = new ArrayList<>();
855 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
856 @Override
857 public void visitKeyboardLayout(Resources resources,
858 int keyboardLayoutResId, KeyboardLayout layout) {
859 // Only select a default when we know the layout is appropriate. For now, this
860 // means its a custom layout for a specific keyboard.
861 if (layout.getVendorId() != d.getVendorId()
862 || layout.getProductId() != d.getProductId()) {
863 return;
864 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800865 final LocaleList locales = layout.getLocales();
866 final int numLocales = locales.size();
867 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
868 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000869 layouts.add(layout);
870 break;
871 }
872 }
873 }
874 });
875
876 if (layouts.isEmpty()) {
877 return null;
878 }
879
880 // First sort so that ones with higher priority are listed at the top
881 Collections.sort(layouts);
882 // Next we want to try to find an exact match of language, country and variant.
883 final int N = layouts.size();
884 for (int i = 0; i < N; i++) {
885 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800886 final LocaleList locales = layout.getLocales();
887 final int numLocales = locales.size();
888 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
889 final Locale locale = locales.get(localeIndex);
890 if (locale.getCountry().equals(systemLocale.getCountry())
891 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000892 return layout.getDescriptor();
893 }
894 }
895 }
896 // Then try an exact match of language and country
897 for (int i = 0; i < N; i++) {
898 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800899 final LocaleList locales = layout.getLocales();
900 final int numLocales = locales.size();
901 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
902 final Locale locale = locales.get(localeIndex);
903 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000904 return layout.getDescriptor();
905 }
906 }
907 }
908
909 // Give up and just use the highest priority layout with matching language
910 return layouts.get(0).getDescriptor();
911 }
912
913 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
914 // Different languages are never compatible
915 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
916 return false;
917 }
918 // If both the system and the keyboard layout have a country specifier, they must be equal.
919 if (!TextUtils.isEmpty(systemLocale.getCountry())
920 && !TextUtils.isEmpty(keyboardLocale.getCountry())
921 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
922 return false;
923 }
924 return true;
925 }
926
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800927 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700928 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
929 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800930 if (inputDeviceDescriptor == null) {
931 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
932 }
933
934 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700935 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800936 }
937 }
938
939 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700940 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800941 TouchCalibration calibration) {
942 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
943 "setTouchCalibrationForInputDevice()")) {
944 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
945 }
946 if (inputDeviceDescriptor == null) {
947 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
948 }
949 if (calibration == null) {
950 throw new IllegalArgumentException("calibration must not be null");
951 }
Jason Gerecked5220742014-03-10 09:47:59 -0700952 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
953 throw new IllegalArgumentException("surfaceRotation value out of bounds");
954 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800955
956 synchronized (mDataStore) {
957 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700958 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
959 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800960 nativeReloadCalibration(mPtr);
961 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800962 } finally {
963 mDataStore.saveIfNeeded();
964 }
965 }
966 }
967
Michael Wright39e5e942015-08-19 22:52:47 +0100968 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100969 public int isInTabletMode() {
970 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
971 "isInTabletMode()")) {
972 throw new SecurityException("Requires TABLET_MODE permission");
973 }
974 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
975 }
976
977 @Override // Binder call
Dmitry Shmidtd6cf4d92019-09-20 15:50:36 -0700978 public int isMicMuted() {
979 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_MUTE_DEVICE);
980 }
981
982 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100983 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100984 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100985 "registerTabletModeChangedListener()")) {
986 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
987 }
988 if (listener == null) {
989 throw new IllegalArgumentException("listener must not be null");
990 }
991
992 synchronized (mTabletModeLock) {
993 final int callingPid = Binder.getCallingPid();
994 if (mTabletModeChangedListeners.get(callingPid) != null) {
995 throw new IllegalStateException("The calling process has already registered "
996 + "a TabletModeChangedListener.");
997 }
998 TabletModeChangedListenerRecord record =
999 new TabletModeChangedListenerRecord(callingPid, listener);
1000 try {
1001 IBinder binder = listener.asBinder();
1002 binder.linkToDeath(record, 0);
1003 } catch (RemoteException ex) {
1004 throw new RuntimeException(ex);
1005 }
1006 mTabletModeChangedListeners.put(callingPid, record);
1007 }
1008 }
1009
1010 private void onTabletModeChangedListenerDied(int pid) {
1011 synchronized (mTabletModeLock) {
1012 mTabletModeChangedListeners.remove(pid);
1013 }
1014 }
1015
1016 // Must be called on handler
1017 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
1018 mTempTabletModeChangedListenersToNotify.clear();
1019 final int numListeners;
1020 synchronized (mTabletModeLock) {
1021 numListeners = mTabletModeChangedListeners.size();
1022 for (int i = 0; i < numListeners; i++) {
1023 mTempTabletModeChangedListenersToNotify.add(
1024 mTabletModeChangedListeners.valueAt(i));
1025 }
1026 }
1027 for (int i = 0; i < numListeners; i++) {
1028 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
1029 whenNanos, inTabletMode);
1030 }
1031 }
1032
Jeff Browncf39bdf2012-05-18 14:41:19 -07001033 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -07001034 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001035 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -07001036 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -07001037 if (device != null) {
1038 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001039 }
Michael Wrightc93fbd12014-09-22 20:07:59 -07001040 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1041 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1042 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1043 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
1044 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001045
1046 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001047 Notification notification =
1048 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
1049 .setContentTitle(r.getString(
1050 R.string.select_keyboard_layout_notification_title))
1051 .setContentText(r.getString(
1052 R.string.select_keyboard_layout_notification_message))
1053 .setContentIntent(keyboardLayoutIntent)
1054 .setSmallIcon(R.drawable.ic_settings_language)
1055 .setColor(mContext.getColor(
1056 com.android.internal.R.color.system_notification_accent_color))
1057 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001058 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001059 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001060 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001061 mKeyboardLayoutNotificationShown = true;
1062 }
1063 }
1064
1065 // Must be called on handler.
1066 private void hideMissingKeyboardLayoutNotification() {
1067 if (mKeyboardLayoutNotificationShown) {
1068 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001069 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001070 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001071 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001072 }
1073 }
1074
1075 // Must be called on handler.
1076 private void updateKeyboardLayouts() {
1077 // Scan all input devices state for keyboard layouts that have been uninstalled.
1078 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1079 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1080 @Override
Michael Wright07483422015-10-30 16:20:13 +00001081 public void visitKeyboardLayout(Resources resources,
1082 int keyboardLayoutResId, KeyboardLayout layout) {
1083 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001084 }
1085 });
1086 synchronized (mDataStore) {
1087 try {
1088 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1089 } finally {
1090 mDataStore.saveIfNeeded();
1091 }
1092 }
1093
1094 // Reload keyboard layouts.
1095 reloadKeyboardLayouts();
1096 }
1097
Jeff Browncf39bdf2012-05-18 14:41:19 -07001098 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1099 String descriptor) {
1100 final int numDevices = inputDevices.length;
1101 for (int i = 0; i < numDevices; i++) {
1102 final InputDevice inputDevice = inputDevices[i];
1103 if (inputDevice.getDescriptor().equals(descriptor)) {
1104 return true;
1105 }
1106 }
1107 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001108 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001109
1110 @Override // Binder call
1111 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001112 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1113 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1114 @Override
Michael Wright07483422015-10-30 16:20:13 +00001115 public void visitKeyboardLayout(Resources resources,
1116 int keyboardLayoutResId, KeyboardLayout layout) {
1117 list.add(layout);
1118 }
1119 });
1120 return list.toArray(new KeyboardLayout[list.size()]);
1121 }
1122
Michael Wrightb0e804a2016-01-04 16:48:53 -05001123 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001124 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1125 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001126 final String[] enabledLayoutDescriptors =
1127 getEnabledKeyboardLayoutsForInputDevice(identifier);
1128 final ArrayList<KeyboardLayout> enabledLayouts =
1129 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1130 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001131 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1132 boolean mHasSeenDeviceSpecificLayout;
1133
1134 @Override
1135 public void visitKeyboardLayout(Resources resources,
1136 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001137 // First check if it's enabled. If the keyboard layout is enabled then we always
1138 // want to return it as a possible layout for the device.
1139 for (String s : enabledLayoutDescriptors) {
1140 if (s != null && s.equals(layout.getDescriptor())) {
1141 enabledLayouts.add(layout);
1142 return;
1143 }
1144 }
1145 // Next find any potential layouts that aren't yet enabled for the device. For
1146 // devices that have special layouts we assume there's a reason that the generic
1147 // layouts don't work for them so we don't want to return them since it's likely
1148 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001149 if (layout.getVendorId() == identifier.getVendorId()
1150 && layout.getProductId() == identifier.getProductId()) {
1151 if (!mHasSeenDeviceSpecificLayout) {
1152 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001153 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001154 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001155 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001156 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1157 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001158 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001159 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001160 }
1161 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001162 final int enabledLayoutSize = enabledLayouts.size();
1163 final int potentialLayoutSize = potentialLayouts.size();
1164 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1165 enabledLayouts.toArray(layouts);
1166 for (int i = 0; i < potentialLayoutSize; i++) {
1167 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1168 }
1169 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001170 }
1171
1172 @Override // Binder call
1173 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1174 if (keyboardLayoutDescriptor == null) {
1175 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1176 }
1177
Jeff Brown6ec6f792012-04-17 16:52:41 -07001178 final KeyboardLayout[] result = new KeyboardLayout[1];
1179 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1180 @Override
Michael Wright07483422015-10-30 16:20:13 +00001181 public void visitKeyboardLayout(Resources resources,
1182 int keyboardLayoutResId, KeyboardLayout layout) {
1183 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001184 }
1185 });
1186 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001187 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001188 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001189 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001190 return result[0];
1191 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001192
Jeff Brown6ec6f792012-04-17 16:52:41 -07001193 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001194 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001195 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1196 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001197 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1198 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001199 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1200 final int priority = resolveInfo.priority;
1201 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001202 }
1203 }
1204
Jeff Brown6ec6f792012-04-17 16:52:41 -07001205 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1206 KeyboardLayoutVisitor visitor) {
1207 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1208 if (d != null) {
1209 final PackageManager pm = mContext.getPackageManager();
1210 try {
1211 ActivityInfo receiver = pm.getReceiverInfo(
1212 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001213 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001214 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1215 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001216 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001217 } catch (NameNotFoundException ex) {
1218 }
1219 }
1220 }
1221
1222 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001223 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001224 Bundle metaData = receiver.metaData;
1225 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001226 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001227 }
1228
1229 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1230 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001231 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001232 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001233 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001234 }
1235
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001236 CharSequence receiverLabel = receiver.loadLabel(pm);
1237 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001238 int priority;
1239 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1240 priority = requestedPriority;
1241 } else {
1242 priority = 0;
1243 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001244
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001245 try {
1246 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1247 XmlResourceParser parser = resources.getXml(configResId);
1248 try {
1249 XmlUtils.beginDocument(parser, "keyboard-layouts");
1250
1251 for (;;) {
1252 XmlUtils.nextElement(parser);
1253 String element = parser.getName();
1254 if (element == null) {
1255 break;
1256 }
1257 if (element.equals("keyboard-layout")) {
1258 TypedArray a = resources.obtainAttributes(
1259 parser, com.android.internal.R.styleable.KeyboardLayout);
1260 try {
1261 String name = a.getString(
1262 com.android.internal.R.styleable.KeyboardLayout_name);
1263 String label = a.getString(
1264 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001265 int keyboardLayoutResId = a.getResourceId(
1266 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1267 0);
Michael Wright07483422015-10-30 16:20:13 +00001268 String languageTags = a.getString(
1269 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001270 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001271 int vid = a.getInt(
1272 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1273 int pid = a.getInt(
1274 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1275
Jeff Brown2f095762012-05-10 21:29:33 -07001276 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001277 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001278 + "attributes in keyboard layout "
1279 + "resource from receiver "
1280 + receiver.packageName + "/" + receiver.name);
1281 } else {
1282 String descriptor = KeyboardLayoutDescriptor.format(
1283 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001284 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001285 KeyboardLayout layout = new KeyboardLayout(
1286 descriptor, label, collection, priority,
1287 locales, vid, pid);
1288 visitor.visitKeyboardLayout(
1289 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001290 }
1291 }
1292 } finally {
1293 a.recycle();
1294 }
1295 } else {
Michael Wright07483422015-10-30 16:20:13 +00001296 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001297 + "' in keyboard layout resource from receiver "
1298 + receiver.packageName + "/" + receiver.name);
1299 }
1300 }
1301 } finally {
1302 parser.close();
1303 }
1304 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001305 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001306 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001307 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001308 }
1309
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001310 @NonNull
1311 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001312 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001313 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001314 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001315 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001316 }
1317
RoboErikfb290df2013-12-16 11:27:55 -08001318 /**
1319 * Builds a layout descriptor for the vendor/product. This returns the
1320 * descriptor for ids that aren't useful (such as the default 0, 0).
1321 */
1322 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1323 if (identifier == null || identifier.getDescriptor() == null) {
1324 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001325 }
1326
RoboErikfb290df2013-12-16 11:27:55 -08001327 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1328 return identifier.getDescriptor();
1329 }
1330 StringBuilder bob = new StringBuilder();
1331 bob.append("vendor:").append(identifier.getVendorId());
1332 bob.append(",product:").append(identifier.getProductId());
1333 return bob.toString();
1334 }
1335
1336 @Override // Binder call
1337 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1338
1339 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001340 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001341 String layout = null;
1342 // try loading it using the layout descriptor if we have it
1343 layout = mDataStore.getCurrentKeyboardLayout(key);
1344 if (layout == null && !key.equals(identifier.getDescriptor())) {
1345 // if it doesn't exist fall back to the device descriptor
1346 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1347 }
1348 if (DEBUG) {
1349 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1350 + layout);
1351 }
1352 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001353 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001354 }
1355
1356 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001357 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001358 String keyboardLayoutDescriptor) {
1359 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001360 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001361 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1362 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001363 if (keyboardLayoutDescriptor == null) {
1364 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1365 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001366
RoboErikfb290df2013-12-16 11:27:55 -08001367 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001368 synchronized (mDataStore) {
1369 try {
RoboErikfb290df2013-12-16 11:27:55 -08001370 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1371 if (DEBUG) {
1372 Slog.d(TAG, "Saved keyboard layout using " + key);
1373 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001374 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1375 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001376 } finally {
1377 mDataStore.saveIfNeeded();
1378 }
1379 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001380 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001381
Jeff Browncf39bdf2012-05-18 14:41:19 -07001382 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001383 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001384 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001385 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001386 String[] layouts = mDataStore.getKeyboardLayouts(key);
1387 if ((layouts == null || layouts.length == 0)
1388 && !key.equals(identifier.getDescriptor())) {
1389 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1390 }
1391 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001392 }
1393 }
1394
1395 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001396 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001397 String keyboardLayoutDescriptor) {
1398 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1399 "addKeyboardLayoutForInputDevice()")) {
1400 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1401 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001402 if (keyboardLayoutDescriptor == null) {
1403 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1404 }
1405
RoboErikfb290df2013-12-16 11:27:55 -08001406 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001407 synchronized (mDataStore) {
1408 try {
RoboErikfb290df2013-12-16 11:27:55 -08001409 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1410 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1411 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1412 }
1413 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001414 && !Objects.equals(oldLayout,
1415 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001416 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1417 }
1418 } finally {
1419 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001420 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001421 }
1422 }
1423
1424 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001425 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001426 String keyboardLayoutDescriptor) {
1427 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1428 "removeKeyboardLayoutForInputDevice()")) {
1429 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1430 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001431 if (keyboardLayoutDescriptor == null) {
1432 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1433 }
1434
RoboErikfb290df2013-12-16 11:27:55 -08001435 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001436 synchronized (mDataStore) {
1437 try {
RoboErikfb290df2013-12-16 11:27:55 -08001438 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1439 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1440 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1441 }
1442 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1443 if (!key.equals(identifier.getDescriptor())) {
1444 // We need to remove from both places to ensure it is gone
1445 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1446 keyboardLayoutDescriptor);
1447 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001448 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001449 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001450 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1451 }
1452 } finally {
1453 mDataStore.saveIfNeeded();
1454 }
1455 }
1456 }
1457
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001458 public void switchKeyboardLayout(int deviceId, int direction) {
1459 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001460 }
1461
1462 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001463 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1464 final InputDevice device = getInputDevice(deviceId);
1465 if (device != null) {
1466 final boolean changed;
1467 final String keyboardLayoutDescriptor;
1468
1469 String key = getLayoutDescriptor(device.getIdentifier());
1470 synchronized (mDataStore) {
1471 try {
1472 changed = mDataStore.switchKeyboardLayout(key, direction);
1473 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1474 key);
1475 } finally {
1476 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001477 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001478 }
1479
1480 if (changed) {
1481 if (mSwitchedKeyboardLayoutToast != null) {
1482 mSwitchedKeyboardLayoutToast.cancel();
1483 mSwitchedKeyboardLayoutToast = null;
1484 }
1485 if (keyboardLayoutDescriptor != null) {
1486 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1487 if (keyboardLayout != null) {
1488 mSwitchedKeyboardLayoutToast = Toast.makeText(
1489 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1490 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001491 }
1492 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001493
1494 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001495 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001496 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001497 }
1498
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001499 public void setFocusedApplication(int displayId, InputApplicationHandle application) {
1500 nativeSetFocusedApplication(mPtr, displayId, application);
1501 }
1502
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001503 public void setFocusedDisplay(int displayId) {
1504 nativeSetFocusedDisplay(mPtr, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001505 }
RoboErikfb290df2013-12-16 11:27:55 -08001506
Riddle Hsu3f2de742019-02-25 15:21:38 +08001507 /** Clean up input window handles of the given display. */
1508 public void onDisplayRemoved(int displayId) {
1509 nativeSetInputWindows(mPtr, null /* windowHandles */, displayId);
1510 }
1511
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001512 @Override
1513 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1514 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1515 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1516 + windowToken);
1517 return;
1518 }
1519 if (mFocusedWindowHasCapture == enabled) {
1520 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1521 return;
1522 }
1523 setPointerCapture(enabled);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001524 }
1525
1526 private void setPointerCapture(boolean enabled) {
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001527 if (mFocusedWindowHasCapture != enabled) {
1528 mFocusedWindowHasCapture = enabled;
1529 try {
1530 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1531 } catch (RemoteException ex) {
1532 /* ignore */
1533 }
1534 nativeSetPointerCapture(mPtr, enabled);
1535 }
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001536 }
1537
Jeff Brown349703e2010-06-22 01:27:15 -07001538 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001539 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001540 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001541
1542 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001543 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001544 }
1545
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001546 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001547 public void tryPointerSpeed(int speed) {
1548 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1549 "tryPointerSpeed()")) {
1550 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1551 }
1552
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001553 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1554 throw new IllegalArgumentException("speed out of range");
1555 }
1556
Jeff Brownac143512012-04-05 18:57:33 -07001557 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001558 }
1559
1560 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001561 int speed = getPointerSpeedSetting();
1562 setPointerSpeedUnchecked(speed);
1563 }
1564
1565 private void setPointerSpeedUnchecked(int speed) {
1566 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1567 InputManager.MAX_POINTER_SPEED);
1568 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001569 }
1570
1571 private void registerPointerSpeedSettingObserver() {
1572 mContext.getContentResolver().registerContentObserver(
1573 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001574 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001575 @Override
1576 public void onChange(boolean selfChange) {
1577 updatePointerSpeedFromSettings();
1578 }
Jeff Brownd4935962012-09-25 13:27:20 -07001579 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001580 }
1581
Jeff Brownac143512012-04-05 18:57:33 -07001582 private int getPointerSpeedSetting() {
1583 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001584 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001585 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1586 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001587 } catch (SettingNotFoundException snfe) {
1588 }
1589 return speed;
1590 }
1591
Jeff Browndaf4a122011-08-26 17:14:14 -07001592 public void updateShowTouchesFromSettings() {
1593 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001594 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001595 }
1596
1597 private void registerShowTouchesSettingObserver() {
1598 mContext.getContentResolver().registerContentObserver(
1599 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001600 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001601 @Override
1602 public void onChange(boolean selfChange) {
1603 updateShowTouchesFromSettings();
1604 }
Jeff Brownd4935962012-09-25 13:27:20 -07001605 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001606 }
1607
Jun Mukaie4e75da2015-12-15 16:19:20 -08001608 public void updateAccessibilityLargePointerFromSettings() {
1609 final int accessibilityConfig = Settings.Secure.getIntForUser(
1610 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1611 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001612 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001613 nativeReloadPointerIcons(mPtr);
1614 }
1615
Jun Mukai19a56012015-11-24 11:25:52 -08001616 private void registerAccessibilityLargePointerSettingObserver() {
1617 mContext.getContentResolver().registerContentObserver(
1618 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1619 new ContentObserver(mHandler) {
1620 @Override
1621 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001622 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001623 }
1624 }, UserHandle.USER_ALL);
1625 }
1626
Jeff Browndaf4a122011-08-26 17:14:14 -07001627 private int getShowTouchesSetting(int defaultValue) {
1628 int result = defaultValue;
1629 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001630 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1631 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001632 } catch (SettingNotFoundException snfe) {
1633 }
1634 return result;
1635 }
1636
Jeff Browna47425a2012-04-13 04:09:27 -07001637 // Binder call
1638 @Override
1639 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1640 if (repeat >= pattern.length) {
1641 throw new ArrayIndexOutOfBoundsException();
1642 }
1643
1644 VibratorToken v;
1645 synchronized (mVibratorLock) {
1646 v = mVibratorTokens.get(token);
1647 if (v == null) {
1648 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1649 try {
1650 token.linkToDeath(v, 0);
1651 } catch (RemoteException ex) {
1652 // give up
1653 throw new RuntimeException(ex);
1654 }
1655 mVibratorTokens.put(token, v);
1656 }
1657 }
1658
1659 synchronized (v) {
1660 v.mVibrating = true;
1661 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1662 }
1663 }
1664
1665 // Binder call
1666 @Override
1667 public void cancelVibrate(int deviceId, IBinder token) {
1668 VibratorToken v;
1669 synchronized (mVibratorLock) {
1670 v = mVibratorTokens.get(token);
1671 if (v == null || v.mDeviceId != deviceId) {
1672 return; // nothing to cancel
1673 }
1674 }
1675
1676 cancelVibrateIfNeeded(v);
1677 }
1678
1679 void onVibratorTokenDied(VibratorToken v) {
1680 synchronized (mVibratorLock) {
1681 mVibratorTokens.remove(v.mToken);
1682 }
1683
1684 cancelVibrateIfNeeded(v);
1685 }
1686
1687 private void cancelVibrateIfNeeded(VibratorToken v) {
1688 synchronized (v) {
1689 if (v.mVibrating) {
1690 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1691 v.mVibrating = false;
1692 }
1693 }
1694 }
1695
Jun Mukai19a56012015-11-24 11:25:52 -08001696 // Binder call
1697 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001698 public void setPointerIconType(int iconId) {
1699 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001700 }
Jun Mukai1db53972015-09-11 18:08:31 -07001701
Jun Mukaid4eaef72015-10-30 15:54:33 -07001702 // Binder call
1703 @Override
1704 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001705 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001706 nativeSetCustomPointerIcon(mPtr, icon);
1707 }
1708
Jeff Brown4532e612012-04-05 14:27:12 -07001709 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001710 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001711 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001712
1713 pw.println("INPUT MANAGER (dumpsys input)\n");
1714 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001715 if (dumpStr != null) {
1716 pw.println(dumpStr);
1717 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001718 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001719
Jeff Brownac143512012-04-05 18:57:33 -07001720 private boolean checkCallingPermission(String permission, String func) {
1721 // Quick check: if the calling permission is me, it's all okay.
1722 if (Binder.getCallingPid() == Process.myPid()) {
1723 return true;
1724 }
1725
1726 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1727 return true;
1728 }
1729 String msg = "Permission Denial: " + func + " from pid="
1730 + Binder.getCallingPid()
1731 + ", uid=" + Binder.getCallingUid()
1732 + " requires " + permission;
1733 Slog.w(TAG, msg);
1734 return false;
1735 }
1736
Jeff Brown4532e612012-04-05 14:27:12 -07001737 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001738 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001739 public void monitor() {
1740 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001741 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001742 }
1743
Jeff Brown4532e612012-04-05 14:27:12 -07001744 // Native callback.
1745 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001746 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001747 }
1748
1749 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001750 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1751 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001752 if (!mInputDevicesChangedPending) {
1753 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001754 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1755 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001756 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001757
1758 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001759 }
1760 }
1761
1762 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001763 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1764 if (DEBUG) {
1765 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1766 + ", mask=" + Integer.toHexString(switchMask));
1767 }
1768
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001769 if ((switchMask & SW_LID_BIT) != 0) {
1770 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001771 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001772 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001773
Michael Wright3818c922014-09-02 13:59:07 -07001774 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001775 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001776 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1777 }
1778
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001779 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1780 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1781 switchMask);
1782 }
Michael Wright39e5e942015-08-19 22:52:47 +01001783
Michael Wright9209c9c2015-09-03 17:57:01 +01001784 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001785 SomeArgs args = SomeArgs.obtain();
1786 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1787 args.argi2 = (int) (whenNanos >> 32);
1788 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1789 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1790 args).sendToTarget();
1791 }
Dmitry Shmidt38ab71c2019-09-19 15:28:30 -07001792
1793 if ((switchMask & SW_MUTE_DEVICE_BIT) != 0) {
1794 final boolean micMute = ((switchValues & SW_MUTE_DEVICE_BIT) != 0);
1795 AudioManager audioManager = mContext.getSystemService(AudioManager.class);
1796 audioManager.setMicrophoneMuteFromSwitch(micMute);
1797 }
Jeff Brown4532e612012-04-05 14:27:12 -07001798 }
1799
1800 // Native callback.
Robert Carre0a353c2018-08-02 16:38:04 -07001801 private void notifyInputChannelBroken(IBinder token) {
1802 mWindowManagerCallbacks.notifyInputChannelBroken(token);
Jeff Brown4532e612012-04-05 14:27:12 -07001803 }
1804
Robert Carrbd26e652018-08-21 15:46:28 -07001805 // Native callback
chaviw91089862019-01-09 15:49:11 -08001806 private void notifyFocusChanged(IBinder oldToken, IBinder newToken) {
Riddle Hsu63e40532019-01-14 21:30:07 +08001807 if (mFocusedWindow != null) {
1808 if (mFocusedWindow.asBinder() == newToken) {
1809 Slog.w(TAG, "notifyFocusChanged called with unchanged mFocusedWindow="
1810 + mFocusedWindow);
1811 return;
1812 }
1813 setPointerCapture(false);
Robert Carrbd26e652018-08-21 15:46:28 -07001814 }
chaviw78658892019-01-09 10:23:41 -08001815
chaviw91089862019-01-09 15:49:11 -08001816 mFocusedWindow = IWindow.Stub.asInterface(newToken);
Robert Carrbd26e652018-08-21 15:46:28 -07001817 }
1818
Jeff Brown4532e612012-04-05 14:27:12 -07001819 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001820 private long notifyANR(IBinder token, String reason) {
Jeff Brownbd181bb2013-09-10 16:44:24 -07001821 return mWindowManagerCallbacks.notifyANR(
Robert Carr679ccb02018-08-08 15:32:35 -07001822 token, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001823 }
1824
1825 // Native callback.
1826 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1827 synchronized (mInputFilterLock) {
1828 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001829 try {
1830 mInputFilter.filterInputEvent(event, policyFlags);
1831 } catch (RemoteException e) {
1832 /* ignore */
1833 }
Jeff Brown4532e612012-04-05 14:27:12 -07001834 return false;
1835 }
1836 }
1837 event.recycle();
1838 return true;
1839 }
1840
1841 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001842 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1843 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001844 }
1845
1846 // Native callback.
Charles Chen4cc014e12019-01-28 16:17:16 +08001847 private int interceptMotionBeforeQueueingNonInteractive(int displayId,
1848 long whenNanos, int policyFlags) {
Michael Wright70af00a2014-09-03 19:30:20 -07001849 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Charles Chen4cc014e12019-01-28 16:17:16 +08001850 displayId, whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001851 }
1852
1853 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001854 private long interceptKeyBeforeDispatching(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001855 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001856 }
1857
1858 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001859 private KeyEvent dispatchUnhandledKey(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001860 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001861 }
1862
1863 // Native callback.
1864 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1865 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1866 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1867 }
1868
1869 // Native callback.
chaviw17902c52019-03-25 13:21:56 -07001870 private void onPointerDownOutsideFocus(IBinder touchedToken) {
chaviwfa2f0042019-03-25 13:48:58 -07001871 mWindowManagerCallbacks.onPointerDownOutsideFocus(touchedToken);
chaviw17902c52019-03-25 13:21:56 -07001872 }
1873
1874 // Native callback.
Jeff Brown4532e612012-04-05 14:27:12 -07001875 private int getVirtualKeyQuietTimeMillis() {
1876 return mContext.getResources().getInteger(
1877 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1878 }
1879
1880 // Native callback.
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001881 private static String[] getExcludedDeviceNames() {
1882 List<String> names = new ArrayList<>();
Jeff Brown4532e612012-04-05 14:27:12 -07001883 // Read partner-provided list of excluded input devices
Jeff Brown4532e612012-04-05 14:27:12 -07001884 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001885 final File[] baseDirs = {
1886 Environment.getRootDirectory(),
1887 Environment.getVendorDirectory()
1888 };
1889 for (File baseDir: baseDirs) {
1890 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001891 try {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001892 InputStream stream = new FileInputStream(confFile);
1893 names.addAll(ConfigurationProcessor.processExcludedDeviceNames(stream));
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001894 } catch (FileNotFoundException e) {
1895 // It's ok if the file does not exist.
1896 } catch (Exception e) {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001897 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
Jeff Brown4532e612012-04-05 14:27:12 -07001898 }
Jeff Brown4532e612012-04-05 14:27:12 -07001899 }
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001900 return names.toArray(new String[0]);
1901 }
Jeff Brown4532e612012-04-05 14:27:12 -07001902
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001903 /**
1904 * Flatten a list of pairs into a list, with value positioned directly next to the key
1905 * @return Flattened list
1906 */
1907 private static <T> List<T> flatten(@NonNull List<Pair<T, T>> pairs) {
1908 List<T> list = new ArrayList<>(pairs.size() * 2);
1909 for (Pair<T, T> pair : pairs) {
1910 list.add(pair.first);
1911 list.add(pair.second);
1912 }
1913 return list;
1914 }
1915
1916 /**
1917 * Ports are highly platform-specific, so only allow these to be specified in the vendor
1918 * directory.
1919 */
1920 // Native callback
1921 private static String[] getInputPortAssociations() {
1922 File baseDir = Environment.getVendorDirectory();
1923 File confFile = new File(baseDir, PORT_ASSOCIATIONS_PATH);
1924
1925 try {
1926 InputStream stream = new FileInputStream(confFile);
1927 List<Pair<String, String>> associations =
1928 ConfigurationProcessor.processInputPortAssociations(stream);
1929 List<String> associationList = flatten(associations);
1930 return associationList.toArray(new String[0]);
1931 } catch (FileNotFoundException e) {
1932 // Most of the time, file will not exist, which is expected.
1933 } catch (Exception e) {
1934 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
1935 }
1936 return new String[0];
Jeff Brown4532e612012-04-05 14:27:12 -07001937 }
1938
Arthur Hung82bbfc32018-11-29 20:24:51 +08001939 /**
1940 * Gets if an input device could dispatch to the given display".
1941 * @param deviceId The input device id.
1942 * @param displayId The specific display id.
1943 * @return True if the device could dispatch to the given display, false otherwise.
1944 */
1945 public boolean canDispatchToDisplay(int deviceId, int displayId) {
1946 return nativeCanDispatchToDisplay(mPtr, deviceId, displayId);
1947 }
1948
Jeff Brown4532e612012-04-05 14:27:12 -07001949 // Native callback.
1950 private int getKeyRepeatTimeout() {
1951 return ViewConfiguration.getKeyRepeatTimeout();
1952 }
1953
1954 // Native callback.
1955 private int getKeyRepeatDelay() {
1956 return ViewConfiguration.getKeyRepeatDelay();
1957 }
1958
1959 // Native callback.
1960 private int getHoverTapTimeout() {
1961 return ViewConfiguration.getHoverTapTimeout();
1962 }
1963
1964 // Native callback.
1965 private int getHoverTapSlop() {
1966 return ViewConfiguration.getHoverTapSlop();
1967 }
1968
1969 // Native callback.
1970 private int getDoubleTapTimeout() {
1971 return ViewConfiguration.getDoubleTapTimeout();
1972 }
1973
1974 // Native callback.
1975 private int getLongPressTimeout() {
1976 return ViewConfiguration.getLongPressTimeout();
1977 }
1978
1979 // Native callback.
1980 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001981 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001982 }
1983
1984 // Native callback.
Andrii Kulianfd8666d2018-10-05 16:58:39 -07001985 private PointerIcon getPointerIcon(int displayId) {
1986 return PointerIcon.getDefaultIcon(getContextForDisplay(displayId));
1987 }
1988
1989 private Context getContextForDisplay(int displayId) {
1990 if (mDisplayContext != null && mDisplayContext.getDisplay().getDisplayId() == displayId) {
1991 return mDisplayContext;
1992 }
1993
1994 if (mContext.getDisplay().getDisplayId() == displayId) {
1995 mDisplayContext = mContext;
1996 return mDisplayContext;
1997 }
1998
1999 // Create and cache context for non-default display.
2000 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
2001 final Display display = displayManager.getDisplay(displayId);
2002 mDisplayContext = mContext.createDisplayContext(display);
2003 return mDisplayContext;
Jeff Brown4532e612012-04-05 14:27:12 -07002004 }
2005
Jeff Brown6ec6f792012-04-17 16:52:41 -07002006 // Native callback.
Arthur Hungb9b32002018-12-18 17:39:43 +08002007 private int getPointerDisplayId() {
2008 return mWindowManagerCallbacks.getPointerDisplayId();
2009 }
2010
2011 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08002012 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07002013 if (!mSystemReady) {
2014 return null;
2015 }
2016
RoboErikfb290df2013-12-16 11:27:55 -08002017 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002018 if (keyboardLayoutDescriptor == null) {
2019 return null;
2020 }
2021
2022 final String[] result = new String[2];
2023 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
2024 @Override
Michael Wright07483422015-10-30 16:20:13 +00002025 public void visitKeyboardLayout(Resources resources,
2026 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07002027 try {
Michael Wright07483422015-10-30 16:20:13 +00002028 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07002029 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07002030 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07002031 } catch (IOException ex) {
2032 } catch (NotFoundException ex) {
2033 }
2034 }
2035 });
2036 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00002037 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07002038 + keyboardLayoutDescriptor + "'.");
2039 return null;
2040 }
2041 return result;
2042 }
2043
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002044 // Native callback.
2045 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07002046 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2047 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2048 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002049 }
2050 return null;
2051 }
2052
Jeff Brown4532e612012-04-05 14:27:12 -07002053 /**
2054 * Callback interface implemented by the Window Manager.
2055 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002056 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002057 public void notifyConfigurationChanged();
2058
2059 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2060
Michael Wright3818c922014-09-02 13:59:07 -07002061 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2062
Robert Carre0a353c2018-08-02 16:38:04 -07002063 public void notifyInputChannelBroken(IBinder token);
Jeff Brown4532e612012-04-05 14:27:12 -07002064
Robert Carr679ccb02018-08-08 15:32:35 -07002065 public long notifyANR(IBinder token, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002066
Jeff Brown037c33e2014-04-09 00:31:55 -07002067 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002068
Charles Chen4cc014e12019-01-28 16:17:16 +08002069 /**
2070 * Provides an opportunity for the window manager policy to intercept early motion event
2071 * processing when the device is in a non-interactive state since these events are normally
2072 * dropped.
2073 */
2074 int interceptMotionBeforeQueueingNonInteractive(int displayId, long whenNanos,
2075 int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002076
Robert Carre0a353c2018-08-02 16:38:04 -07002077 public long interceptKeyBeforeDispatching(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07002078 KeyEvent event, int policyFlags);
2079
Robert Carre0a353c2018-08-02 16:38:04 -07002080 public KeyEvent dispatchUnhandledKey(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07002081 KeyEvent event, int policyFlags);
2082
2083 public int getPointerLayer();
Arthur Hungb9b32002018-12-18 17:39:43 +08002084
2085 public int getPointerDisplayId();
chaviwfa2f0042019-03-25 13:48:58 -07002086
2087 /**
2088 * Notifies window manager that a {@link android.view.MotionEvent#ACTION_DOWN} pointer event
2089 * occurred on a window that did not have focus.
2090 *
2091 * @param touchedToken The token for the window that received the input event.
2092 */
2093 void onPointerDownOutsideFocus(IBinder touchedToken);
Jeff Brown4532e612012-04-05 14:27:12 -07002094 }
2095
2096 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002097 * Callback interface implemented by WiredAccessoryObserver.
2098 */
2099 public interface WiredAccessoryCallbacks {
2100 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002101 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002102 }
2103
2104 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002105 * Private handler for the input manager.
2106 */
2107 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002108 public InputManagerHandler(Looper looper) {
2109 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002110 }
2111
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002112 @Override
2113 public void handleMessage(Message msg) {
2114 switch (msg.what) {
2115 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002116 deliverInputDevicesChanged((InputDevice[])msg.obj);
2117 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002118 case MSG_SWITCH_KEYBOARD_LAYOUT:
2119 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002120 break;
2121 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2122 reloadKeyboardLayouts();
2123 break;
2124 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2125 updateKeyboardLayouts();
2126 break;
2127 case MSG_RELOAD_DEVICE_ALIASES:
2128 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002129 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002130 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002131 SomeArgs args = (SomeArgs) msg.obj;
2132 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2133 boolean inTabletMode = (boolean) args.arg1;
2134 deliverTabletModeChanged(whenNanos, inTabletMode);
2135 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002136 }
2137 }
2138 }
2139
2140 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002141 * Hosting interface for input filters to call back into the input manager.
2142 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002143 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002144 private boolean mDisconnected;
2145
2146 public void disconnectLocked() {
2147 mDisconnected = true;
2148 }
2149
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002150 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002151 public void sendInputEvent(InputEvent event, int policyFlags) {
2152 if (event == null) {
2153 throw new IllegalArgumentException("event must not be null");
2154 }
2155
2156 synchronized (mInputFilterLock) {
2157 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002158 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002159 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002160 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2161 }
2162 }
2163 }
2164 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002165
Michael Wrightc7995232019-02-14 12:33:46 +00002166 /**
2167 * Interface for the system to handle request from InputMonitors.
2168 */
2169 private final class InputMonitorHost extends IInputMonitorHost.Stub {
2170 private final InputChannel mInputChannel;
2171
2172 InputMonitorHost(InputChannel channel) {
2173 mInputChannel = channel;
2174 }
2175
2176 @Override
2177 public void pilferPointers() {
2178 nativePilferPointers(mPtr, asBinder());
2179 }
2180
2181 @Override
2182 public void dispose() {
2183 nativeUnregisterInputChannel(mPtr, mInputChannel);
2184 mInputChannel.dispose();
2185 }
2186 }
2187
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002188 private static final class KeyboardLayoutDescriptor {
2189 public String packageName;
2190 public String receiverName;
2191 public String keyboardLayoutName;
2192
2193 public static String format(String packageName,
2194 String receiverName, String keyboardName) {
2195 return packageName + "/" + receiverName + "/" + keyboardName;
2196 }
2197
2198 public static KeyboardLayoutDescriptor parse(String descriptor) {
2199 int pos = descriptor.indexOf('/');
2200 if (pos < 0 || pos + 1 == descriptor.length()) {
2201 return null;
2202 }
2203 int pos2 = descriptor.indexOf('/', pos + 1);
2204 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2205 return null;
2206 }
2207
2208 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2209 result.packageName = descriptor.substring(0, pos);
2210 result.receiverName = descriptor.substring(pos + 1, pos2);
2211 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2212 return result;
2213 }
2214 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002215
Jeff Brown6ec6f792012-04-17 16:52:41 -07002216 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002217 void visitKeyboardLayout(Resources resources,
2218 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002219 }
2220
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002221 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2222 private final int mPid;
2223 private final IInputDevicesChangedListener mListener;
2224
2225 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2226 mPid = pid;
2227 mListener = listener;
2228 }
2229
2230 @Override
2231 public void binderDied() {
2232 if (DEBUG) {
2233 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2234 }
2235 onInputDevicesChangedListenerDied(mPid);
2236 }
2237
2238 public void notifyInputDevicesChanged(int[] info) {
2239 try {
2240 mListener.onInputDevicesChanged(info);
2241 } catch (RemoteException ex) {
2242 Slog.w(TAG, "Failed to notify process "
2243 + mPid + " that input devices changed, assuming it died.", ex);
2244 binderDied();
2245 }
2246 }
2247 }
Jeff Browna47425a2012-04-13 04:09:27 -07002248
Michael Wright39e5e942015-08-19 22:52:47 +01002249 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2250 private final int mPid;
2251 private final ITabletModeChangedListener mListener;
2252
2253 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2254 mPid = pid;
2255 mListener = listener;
2256 }
2257
2258 @Override
2259 public void binderDied() {
2260 if (DEBUG) {
2261 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2262 }
2263 onTabletModeChangedListenerDied(mPid);
2264 }
2265
2266 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2267 try {
2268 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2269 } catch (RemoteException ex) {
2270 Slog.w(TAG, "Failed to notify process " + mPid +
2271 " that tablet mode changed, assuming it died.", ex);
2272 binderDied();
2273 }
2274 }
2275 }
2276
Jeff Browna47425a2012-04-13 04:09:27 -07002277 private final class VibratorToken implements DeathRecipient {
2278 public final int mDeviceId;
2279 public final IBinder mToken;
2280 public final int mTokenValue;
2281
2282 public boolean mVibrating;
2283
2284 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2285 mDeviceId = deviceId;
2286 mToken = token;
2287 mTokenValue = tokenValue;
2288 }
2289
2290 @Override
2291 public void binderDied() {
2292 if (DEBUG) {
2293 Slog.d(TAG, "Vibrator token died.");
2294 }
2295 onVibratorTokenDied(this);
2296 }
2297 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002298
2299 private final class LocalService extends InputManagerInternal {
2300 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002301 public void setDisplayViewports(List<DisplayViewport> viewports) {
2302 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002303 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002304
2305 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002306 public boolean injectInputEvent(InputEvent event, int mode) {
2307 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002308 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002309
2310 @Override
2311 public void setInteractive(boolean interactive) {
2312 nativeSetInteractive(mPtr, interactive);
2313 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002314
2315 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002316 public void toggleCapsLock(int deviceId) {
2317 nativeToggleCapsLock(mPtr, deviceId);
2318 }
Adrian Roos99182342016-06-15 15:30:46 -07002319
2320 @Override
2321 public void setPulseGestureEnabled(boolean enabled) {
2322 if (mDoubleTouchGestureEnableFile != null) {
2323 FileWriter writer = null;
2324 try {
2325 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2326 writer.write(enabled ? "1" : "0");
2327 } catch (IOException e) {
2328 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2329 } finally {
2330 IoUtils.closeQuietly(writer);
2331 }
2332 }
2333 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002334 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002335}