blob: 26bce9239bd726971d206d7150d38bf774d35089 [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown4532e612012-04-05 14:27:12 -070017package com.android.server.input;
Jeff Brown46b9ac02010-04-22 18:58:52 -070018
Yohei Yukawa5660fad2016-01-27 22:04:09 -080019import android.annotation.NonNull;
Andrii Kulianed76e742017-06-26 14:57:02 -070020import android.app.IInputForwarder;
Jeff Browncf39bdf2012-05-18 14:41:19 -070021import android.app.Notification;
22import android.app.NotificationManager;
23import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070024import android.bluetooth.BluetoothAdapter;
25import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070026import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070027import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070028import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070029import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070030import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070031import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070032import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070033import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.pm.PackageManager.NameNotFoundException;
Arthur Hung39134b22018-08-14 11:58:28 +080035import android.content.pm.ResolveInfo;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070037import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.res.TypedArray;
39import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070040import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070041import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080042import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070043import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070044import android.hardware.input.IInputManager;
Arthur Hung39134b22018-08-14 11:58:28 +080045import android.hardware.input.ITabletModeChangedListener;
RoboErikfb290df2013-12-16 11:27:55 -080046import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070047import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080048import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080050import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070053import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.os.IBinder;
Arthur Hung39134b22018-08-14 11:58:28 +080056import android.os.LocaleList;
Jeff Browna9d131c2012-09-20 16:48:17 -070057import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080059import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070063import android.provider.Settings;
64import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000065import android.text.TextUtils;
Arthur Hung39134b22018-08-14 11:58:28 +080066import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070068import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070069import android.util.Xml;
Andrii Kulianed76e742017-06-26 14:57:02 -070070import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080073import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070075import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070076import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080077import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070078import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070079import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080080import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080081import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082
Arthur Hung39134b22018-08-14 11:58:28 +080083import com.android.internal.R;
84import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
85import com.android.internal.notification.SystemNotificationChannels;
86import com.android.internal.os.SomeArgs;
87import com.android.internal.util.DumpUtils;
88import com.android.internal.util.Preconditions;
89import com.android.internal.util.XmlUtils;
90import com.android.server.DisplayThread;
91import com.android.server.LocalServices;
92import com.android.server.Watchdog;
93import com.android.server.policy.WindowManagerPolicy;
94
95import libcore.io.IoUtils;
96import libcore.io.Streams;
97
98import org.xmlpull.v1.XmlPullParser;
99
Jeff Brown46b9ac02010-04-22 18:58:52 -0700100import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700101import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102import java.io.FileNotFoundException;
103import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700104import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700106import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700107import java.io.PrintWriter;
108import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000109import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700110import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700111import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100112import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000113import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000114import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700115
Jeff Brown46b9ac02010-04-22 18:58:52 -0700116/*
117 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700118 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700119public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800120 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700122 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700123
Jeff Brown4532e612012-04-05 14:27:12 -0700124 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
125
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700126 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700127 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
128 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
129 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
130 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100131 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132
Jeff Brown4532e612012-04-05 14:27:12 -0700133 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000134 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700135
Jeff Brown46b9ac02010-04-22 18:58:52 -0700136 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700138
Adrian Roos99182342016-06-15 15:30:46 -0700139 private final File mDoubleTouchGestureEnableFile;
140
Jeff Browna9d131c2012-09-20 16:48:17 -0700141 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700142 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700143 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700144 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145
Michael Wright39e5e942015-08-19 22:52:47 +0100146 private final Object mTabletModeLock = new Object();
147 // List of currently registered tablet mode changed listeners by process id
148 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
149 new SparseArray<>(); // guarded by mTabletModeLock
150 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
151 new ArrayList<>();
152
Jeff Browna3bc5652012-04-17 11:42:25 -0700153 // Persistent data store. Must be locked each time during use.
154 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700155
156 // List of currently registered input devices changed listeners by process id.
157 private Object mInputDevicesLock = new Object();
158 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
159 private InputDevice[] mInputDevices = new InputDevice[0];
160 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
161 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
162 private final ArrayList<InputDevicesChangedListenerRecord>
163 mTempInputDevicesChangedListenersToNotify =
164 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700165 private final ArrayList<InputDevice>
166 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
167 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800168 private PendingIntent mKeyboardLayoutIntent;
169 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700170
Jeff Browna47425a2012-04-13 04:09:27 -0700171 // State for vibrator tokens.
172 private Object mVibratorLock = new Object();
173 private HashMap<IBinder, VibratorToken> mVibratorTokens =
174 new HashMap<IBinder, VibratorToken>();
175 private int mNextVibratorTokenValue;
176
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177 // State for the currently installed input filter.
178 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700179 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700180 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700181
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800182 private IWindow mFocusedWindow;
183 private boolean mFocusedWindowHasCapture;
184
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000185 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700186 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native void nativeStart(long ptr);
Santos Cordonee8931e2017-04-05 10:31:15 -0700188 private static native void nativeSetVirtualDisplayViewports(long ptr,
189 DisplayViewport[] viewports);
190 private static native void nativeSetDisplayViewport(long ptr, int viewportType,
Jeff Brownd728bf52012-09-08 18:05:28 -0700191 int displayId, int rotation,
192 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700193 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
Santos Cordonee8931e2017-04-05 10:31:15 -0700194 int deviceWidth, int deviceHeight, String uniqueId);
Jeff Brownd728bf52012-09-08 18:05:28 -0700195
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700197 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700199 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000200 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700201 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000202 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700203 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000204 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800205 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000206 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
207 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800208 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700209 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
210 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800211 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800212 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
213 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000214 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
215 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
216 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700217 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000218 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700219 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000220 private static native void nativeSetPointerSpeed(long ptr, int speed);
221 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700222 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800223 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000224 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700225 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000226 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
227 private static native void nativeReloadKeyboardLayouts(long ptr);
228 private static native void nativeReloadDeviceAliases(long ptr);
229 private static native String nativeDump(long ptr);
230 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700231 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
232 private static native void nativeEnableInputDevice(long ptr, int deviceId);
233 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100234 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800235 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700236 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800237 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700238
Jeff Brownac143512012-04-05 18:57:33 -0700239 // Input event injection constants defined in InputDispatcher.h.
240 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
241 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
242 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
243 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
244
245 // Maximum number of milliseconds to wait for input event injection.
246 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
247
Jeff Brown6d0fec22010-07-23 21:28:06 -0700248 // Key states (may be returned by queries about the current state of a
249 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700250
Jeff Brown6d0fec22010-07-23 21:28:06 -0700251 /** The key state is unknown or the requested key itself is not supported. */
252 public static final int KEY_STATE_UNKNOWN = -1;
253
254 /** The key is up. /*/
255 public static final int KEY_STATE_UP = 0;
256
257 /** The key is down. */
258 public static final int KEY_STATE_DOWN = 1;
259
260 /** The key is down but is a virtual key press that is being emulated by the system. */
261 public static final int KEY_STATE_VIRTUAL = 2;
262
Jeff Brownc458ce92012-04-30 14:58:40 -0700263 /** Scan code: Mouse / trackball button. */
264 public static final int BTN_MOUSE = 0x110;
265
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700266 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700267 /** Switch code: Lid switch. When set, lid is shut. */
268 public static final int SW_LID = 0x00;
269
Michael Wright39e5e942015-08-19 22:52:47 +0100270 /** Switch code: Tablet mode switch.
271 * When set, the device is in tablet mode (i.e. no keyboard is connected).
272 */
273 public static final int SW_TABLET_MODE = 0x01;
274
Jeff Brownc458ce92012-04-30 14:58:40 -0700275 /** Switch code: Keypad slide. When set, keyboard is exposed. */
276 public static final int SW_KEYPAD_SLIDE = 0x0a;
277
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700278 /** Switch code: Headphone. When set, headphone is inserted. */
279 public static final int SW_HEADPHONE_INSERT = 0x02;
280
281 /** Switch code: Microphone. When set, microphone is inserted. */
282 public static final int SW_MICROPHONE_INSERT = 0x04;
283
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500284 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
285 public static final int SW_LINEOUT_INSERT = 0x06;
286
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700287 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
288 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
289
Michael Wright3818c922014-09-02 13:59:07 -0700290 /** Switch code: Camera lens cover. When set the lens is covered. */
291 public static final int SW_CAMERA_LENS_COVER = 0x09;
292
Santos Cordonee8931e2017-04-05 10:31:15 -0700293 // Viewport constants defined in InputReader.h.
294 public static final int VIEWPORT_DEFAULT = 1;
295 public static final int VIEWPORT_EXTERNAL = 2;
296 public static final int VIEWPORT_VIRTUAL = 3;
297
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700298 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100299 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700300 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
301 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
302 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500303 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700304 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
305 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500306 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700307 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700308
309 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
310 final boolean mUseDevInputEventForAudioJack;
311
Jeff Brown4ccb8232014-01-16 22:16:42 -0800312 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700313 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800314 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800315
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700316 mUseDevInputEventForAudioJack =
317 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
318 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
319 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700320 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800321
Adrian Roos99182342016-06-15 15:30:46 -0700322 String doubleTouchGestureEnablePath = context.getResources().getString(
323 R.string.config_doubleTouchGestureEnableFile);
324 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
325 new File(doubleTouchGestureEnablePath);
326
Jeff Brown4ccb8232014-01-16 22:16:42 -0800327 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700328 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700329
Jeff Browna9d131c2012-09-20 16:48:17 -0700330 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
331 mWindowManagerCallbacks = callbacks;
332 }
333
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700334 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
335 mWiredAccessoryCallbacks = callbacks;
336 }
337
Jeff Brown46b9ac02010-04-22 18:58:52 -0700338 public void start() {
339 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700340 nativeStart(mPtr);
341
342 // Add ourself to the Watchdog monitors.
343 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700344
345 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700346 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800347 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700348
Jeff Brownd4935962012-09-25 13:27:20 -0700349 mContext.registerReceiver(new BroadcastReceiver() {
350 @Override
351 public void onReceive(Context context, Intent intent) {
352 updatePointerSpeedFromSettings();
353 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800354 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700355 }
356 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
357
Jeff Brown1a84fd12011-06-02 01:26:32 -0700358 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700359 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800360 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700361 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700362
Matthew Xie96313142012-06-29 16:57:31 -0700363 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700364 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700365 if (DEBUG) {
366 Slog.d(TAG, "System ready.");
367 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700368 mNotificationManager = (NotificationManager)mContext.getSystemService(
369 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700370 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700371
372 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
373 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
374 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800375 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700376 filter.addDataScheme("package");
377 mContext.registerReceiver(new BroadcastReceiver() {
378 @Override
379 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700380 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700381 }
382 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700383
384 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
385 mContext.registerReceiver(new BroadcastReceiver() {
386 @Override
387 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700388 reloadDeviceAliases();
389 }
390 }, filter, null, mHandler);
391
Jeff Browncf39bdf2012-05-18 14:41:19 -0700392 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
393 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700394
395 if (mWiredAccessoryCallbacks != null) {
396 mWiredAccessoryCallbacks.systemReady();
397 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700398 }
399
400 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700401 if (DEBUG) {
402 Slog.d(TAG, "Reloading keyboard layouts.");
403 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700404 nativeReloadKeyboardLayouts(mPtr);
405 }
406
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700407 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700408 if (DEBUG) {
409 Slog.d(TAG, "Reloading device names.");
410 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700411 nativeReloadDeviceAliases(mPtr);
412 }
413
Jeff Brown4ccb8232014-01-16 22:16:42 -0800414 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Santos Cordonee8931e2017-04-05 10:31:15 -0700415 DisplayViewport externalTouchViewport,
416 List<DisplayViewport> virtualTouchViewports) {
Jeff Brownd728bf52012-09-08 18:05:28 -0700417 if (defaultViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700418 setDisplayViewport(VIEWPORT_DEFAULT, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700419 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700420
421 if (externalTouchViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700422 setDisplayViewport(VIEWPORT_EXTERNAL, externalTouchViewport);
Jeff Brownd728bf52012-09-08 18:05:28 -0700423 } else if (defaultViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700424 setDisplayViewport(VIEWPORT_EXTERNAL, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700425 }
Santos Cordonee8931e2017-04-05 10:31:15 -0700426
427 nativeSetVirtualDisplayViewports(mPtr,
428 virtualTouchViewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700429 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700430
Santos Cordonee8931e2017-04-05 10:31:15 -0700431 private void setDisplayViewport(int viewportType, DisplayViewport viewport) {
432 nativeSetDisplayViewport(mPtr, viewportType,
Jeff Brownd728bf52012-09-08 18:05:28 -0700433 viewport.displayId, viewport.orientation,
434 viewport.logicalFrame.left, viewport.logicalFrame.top,
435 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
436 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700437 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
Santos Cordonee8931e2017-04-05 10:31:15 -0700438 viewport.deviceWidth, viewport.deviceHeight, viewport.uniqueId);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700439 }
Jeff Brownac143512012-04-05 18:57:33 -0700440
Jeff Brown6d0fec22010-07-23 21:28:06 -0700441 /**
442 * Gets the current state of a key or button by key code.
443 * @param deviceId The input device id, or -1 to consult all devices.
444 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
445 * consider all input sources. An input device is consulted if at least one of its
446 * non-class input source bits matches the specified source mask.
447 * @param keyCode The key code to check.
448 * @return The key state.
449 */
450 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700451 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700452 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700453
Jeff Brown6d0fec22010-07-23 21:28:06 -0700454 /**
455 * Gets the current state of a key or button by scan code.
456 * @param deviceId The input device id, or -1 to consult all devices.
457 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
458 * consider all input sources. An input device is consulted if at least one of its
459 * non-class input source bits matches the specified source mask.
460 * @param scanCode The scan code to check.
461 * @return The key state.
462 */
463 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700464 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700465 }
RoboErikfb290df2013-12-16 11:27:55 -0800466
Jeff Brown6d0fec22010-07-23 21:28:06 -0700467 /**
468 * Gets the current state of a switch by switch code.
469 * @param deviceId The input device id, or -1 to consult all devices.
470 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
471 * consider all input sources. An input device is consulted if at least one of its
472 * non-class input source bits matches the specified source mask.
473 * @param switchCode The switch code to check.
474 * @return The switch state.
475 */
476 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700477 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700478 }
479
Jeff Brown6d0fec22010-07-23 21:28:06 -0700480 /**
481 * Determines whether the specified key codes are supported by a particular device.
482 * @param deviceId The input device id, or -1 to consult all devices.
483 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
484 * consider all input sources. An input device is consulted if at least one of its
485 * non-class input source bits matches the specified source mask.
486 * @param keyCodes The array of key codes to check.
487 * @param keyExists An array at least as large as keyCodes whose entries will be set
488 * to true or false based on the presence or absence of support for the corresponding
489 * key codes.
490 * @return True if the lookup was successful, false otherwise.
491 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700492 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700493 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700494 if (keyCodes == null) {
495 throw new IllegalArgumentException("keyCodes must not be null.");
496 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700497 if (keyExists == null || keyExists.length < keyCodes.length) {
498 throw new IllegalArgumentException("keyExists must not be null and must be at "
499 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700500 }
RoboErikfb290df2013-12-16 11:27:55 -0800501
Jeff Brown4532e612012-04-05 14:27:12 -0700502 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700503 }
RoboErikfb290df2013-12-16 11:27:55 -0800504
Jeff Browna41ca772010-08-11 14:46:32 -0700505 /**
506 * Creates an input channel that will receive all input from the input dispatcher.
507 * @param inputChannelName The input channel name.
508 * @return The input channel.
509 */
510 public InputChannel monitorInput(String inputChannelName) {
511 if (inputChannelName == null) {
512 throw new IllegalArgumentException("inputChannelName must not be null.");
513 }
RoboErikfb290df2013-12-16 11:27:55 -0800514
Jeff Browna41ca772010-08-11 14:46:32 -0700515 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700516 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700517 inputChannels[0].dispose(); // don't need to retain the Java object reference
518 return inputChannels[1];
519 }
520
521 /**
522 * Registers an input channel so that it can be used as an input event target.
523 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800524 * @param inputWindowHandle The handle of the input window associated with the
525 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700526 */
Jeff Brown928e0542011-01-10 11:17:36 -0800527 public void registerInputChannel(InputChannel inputChannel,
528 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700529 if (inputChannel == null) {
530 throw new IllegalArgumentException("inputChannel must not be null.");
531 }
RoboErikfb290df2013-12-16 11:27:55 -0800532
Jeff Brown4532e612012-04-05 14:27:12 -0700533 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700534 }
RoboErikfb290df2013-12-16 11:27:55 -0800535
Jeff Browna41ca772010-08-11 14:46:32 -0700536 /**
537 * Unregisters an input channel.
538 * @param inputChannel The input channel to unregister.
539 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700540 public void unregisterInputChannel(InputChannel inputChannel) {
541 if (inputChannel == null) {
542 throw new IllegalArgumentException("inputChannel must not be null.");
543 }
RoboErikfb290df2013-12-16 11:27:55 -0800544
Jeff Brown4532e612012-04-05 14:27:12 -0700545 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700546 }
Jeff Brown0029c662011-03-30 02:25:18 -0700547
548 /**
549 * Sets an input filter that will receive all input events before they are dispatched.
550 * The input filter may then reinterpret input events or inject new ones.
551 *
552 * To ensure consistency, the input dispatcher automatically drops all events
553 * in progress whenever an input filter is installed or uninstalled. After an input
554 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
555 * Any events it attempts to send after it has been uninstalled will be dropped.
556 *
557 * @param filter The input filter, or null to remove the current filter.
558 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700559 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700560 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700561 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700562 if (oldFilter == filter) {
563 return; // nothing to do
564 }
565
566 if (oldFilter != null) {
567 mInputFilter = null;
568 mInputFilterHost.disconnectLocked();
569 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700570 try {
571 oldFilter.uninstall();
572 } catch (RemoteException re) {
573 /* ignore */
574 }
Jeff Brown0029c662011-03-30 02:25:18 -0700575 }
576
577 if (filter != null) {
578 mInputFilter = filter;
579 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700580 try {
581 filter.install(mInputFilterHost);
582 } catch (RemoteException re) {
583 /* ignore */
584 }
Jeff Brown0029c662011-03-30 02:25:18 -0700585 }
586
Jeff Brown4532e612012-04-05 14:27:12 -0700587 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700588 }
589 }
590
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700591 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700592 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800593 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800594 }
595
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800596 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700597 if (event == null) {
598 throw new IllegalArgumentException("event must not be null");
599 }
Jeff Brownac143512012-04-05 18:57:33 -0700600 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
601 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
602 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
603 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700604 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700605
Jeff Brownac143512012-04-05 18:57:33 -0700606 final int pid = Binder.getCallingPid();
607 final int uid = Binder.getCallingUid();
608 final long ident = Binder.clearCallingIdentity();
609 final int result;
610 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800611 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700612 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
613 } finally {
614 Binder.restoreCallingIdentity(ident);
615 }
616 switch (result) {
617 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
618 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
619 throw new SecurityException(
620 "Injecting to another application requires INJECT_EVENTS permission");
621 case INPUT_EVENT_INJECTION_SUCCEEDED:
622 return true;
623 case INPUT_EVENT_INJECTION_TIMED_OUT:
624 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
625 return false;
626 case INPUT_EVENT_INJECTION_FAILED:
627 default:
628 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
629 return false;
630 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700631 }
Jeff Brown0029c662011-03-30 02:25:18 -0700632
Jeff Brown8d608662010-08-30 03:02:23 -0700633 /**
634 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700635 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700636 * @return The input device or null if not found.
637 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700638 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700639 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700640 synchronized (mInputDevicesLock) {
641 final int count = mInputDevices.length;
642 for (int i = 0; i < count; i++) {
643 final InputDevice inputDevice = mInputDevices[i];
644 if (inputDevice.getId() == deviceId) {
645 return inputDevice;
646 }
647 }
648 }
649 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700650 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700651
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700652 // Binder call
653 @Override
654 public boolean isInputDeviceEnabled(int deviceId) {
655 return nativeIsInputDeviceEnabled(mPtr, deviceId);
656 }
657
658 // Binder call
659 @Override
660 public void enableInputDevice(int deviceId) {
661 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
662 "enableInputDevice()")) {
663 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
664 }
665 nativeEnableInputDevice(mPtr, deviceId);
666 }
667
668 // Binder call
669 @Override
670 public void disableInputDevice(int deviceId) {
671 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
672 "disableInputDevice()")) {
673 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
674 }
675 nativeDisableInputDevice(mPtr, deviceId);
676 }
677
Jeff Brown8d608662010-08-30 03:02:23 -0700678 /**
679 * Gets the ids of all input devices in the system.
680 * @return The input device ids.
681 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700682 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700683 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700684 synchronized (mInputDevicesLock) {
685 final int count = mInputDevices.length;
686 int[] ids = new int[count];
687 for (int i = 0; i < count; i++) {
688 ids[i] = mInputDevices[i].getId();
689 }
690 return ids;
691 }
692 }
693
Jeff Browndaa37532012-05-01 15:54:03 -0700694 /**
695 * Gets all input devices in the system.
696 * @return The array of input devices.
697 */
698 public InputDevice[] getInputDevices() {
699 synchronized (mInputDevicesLock) {
700 return mInputDevices;
701 }
702 }
703
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700704 @Override // Binder call
705 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
706 if (listener == null) {
707 throw new IllegalArgumentException("listener must not be null");
708 }
709
710 synchronized (mInputDevicesLock) {
711 int callingPid = Binder.getCallingPid();
712 if (mInputDevicesChangedListeners.get(callingPid) != null) {
713 throw new SecurityException("The calling process has already "
714 + "registered an InputDevicesChangedListener.");
715 }
716
717 InputDevicesChangedListenerRecord record =
718 new InputDevicesChangedListenerRecord(callingPid, listener);
719 try {
720 IBinder binder = listener.asBinder();
721 binder.linkToDeath(record, 0);
722 } catch (RemoteException ex) {
723 // give up
724 throw new RuntimeException(ex);
725 }
726
727 mInputDevicesChangedListeners.put(callingPid, record);
728 }
729 }
730
731 private void onInputDevicesChangedListenerDied(int pid) {
732 synchronized (mInputDevicesLock) {
733 mInputDevicesChangedListeners.remove(pid);
734 }
735 }
736
737 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700738 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
739 // Scan for changes.
740 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700741 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700742 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700743 final int numListeners;
744 final int[] deviceIdAndGeneration;
745 synchronized (mInputDevicesLock) {
746 if (!mInputDevicesChangedPending) {
747 return;
748 }
749 mInputDevicesChangedPending = false;
750
751 numListeners = mInputDevicesChangedListeners.size();
752 for (int i = 0; i < numListeners; i++) {
753 mTempInputDevicesChangedListenersToNotify.add(
754 mInputDevicesChangedListeners.valueAt(i));
755 }
756
757 final int numDevices = mInputDevices.length;
758 deviceIdAndGeneration = new int[numDevices * 2];
759 for (int i = 0; i < numDevices; i++) {
760 final InputDevice inputDevice = mInputDevices[i];
761 deviceIdAndGeneration[i * 2] = inputDevice.getId();
762 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700763
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700764 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700765 if (!containsInputDeviceWithDescriptor(oldInputDevices,
766 inputDevice.getDescriptor())) {
767 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
768 } else {
769 mTempFullKeyboards.add(inputDevice);
770 }
771 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700772 }
773 }
774
Jeff Browncf39bdf2012-05-18 14:41:19 -0700775 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700776 for (int i = 0; i < numListeners; i++) {
777 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
778 deviceIdAndGeneration);
779 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700780 mTempInputDevicesChangedListenersToNotify.clear();
781
782 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000783 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
784 final int numFullKeyboards = mTempFullKeyboards.size();
785 synchronized (mDataStore) {
786 for (int i = 0; i < numFullKeyboards; i++) {
787 final InputDevice inputDevice = mTempFullKeyboards.get(i);
788 String layout =
789 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
790 if (layout == null) {
791 layout = getDefaultKeyboardLayout(inputDevice);
792 if (layout != null) {
793 setCurrentKeyboardLayoutForInputDevice(
794 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700795 }
796 }
Michael Wright07483422015-10-30 16:20:13 +0000797 if (layout == null) {
798 keyboardsMissingLayout.add(inputDevice);
799 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700800 }
Michael Wright07483422015-10-30 16:20:13 +0000801 }
802
803 if (mNotificationManager != null) {
804 if (!keyboardsMissingLayout.isEmpty()) {
805 if (keyboardsMissingLayout.size() > 1) {
806 // We have more than one keyboard missing a layout, so drop the
807 // user at the generic input methods page so they can pick which
808 // one to set.
809 showMissingKeyboardLayoutNotification(null);
810 } else {
811 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700812 }
813 } else if (mKeyboardLayoutNotificationShown) {
814 hideMissingKeyboardLayoutNotification();
815 }
816 }
817 mTempFullKeyboards.clear();
818 }
819
Michael Wright07483422015-10-30 16:20:13 +0000820 private String getDefaultKeyboardLayout(final InputDevice d) {
821 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
822 // If our locale doesn't have a language for some reason, then we don't really have a
823 // reasonable default.
824 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
825 return null;
826 }
827 final List<KeyboardLayout> layouts = new ArrayList<>();
828 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
829 @Override
830 public void visitKeyboardLayout(Resources resources,
831 int keyboardLayoutResId, KeyboardLayout layout) {
832 // Only select a default when we know the layout is appropriate. For now, this
833 // means its a custom layout for a specific keyboard.
834 if (layout.getVendorId() != d.getVendorId()
835 || layout.getProductId() != d.getProductId()) {
836 return;
837 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800838 final LocaleList locales = layout.getLocales();
839 final int numLocales = locales.size();
840 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
841 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000842 layouts.add(layout);
843 break;
844 }
845 }
846 }
847 });
848
849 if (layouts.isEmpty()) {
850 return null;
851 }
852
853 // First sort so that ones with higher priority are listed at the top
854 Collections.sort(layouts);
855 // Next we want to try to find an exact match of language, country and variant.
856 final int N = layouts.size();
857 for (int i = 0; i < N; i++) {
858 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800859 final LocaleList locales = layout.getLocales();
860 final int numLocales = locales.size();
861 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
862 final Locale locale = locales.get(localeIndex);
863 if (locale.getCountry().equals(systemLocale.getCountry())
864 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000865 return layout.getDescriptor();
866 }
867 }
868 }
869 // Then try an exact match of language and country
870 for (int i = 0; i < N; i++) {
871 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800872 final LocaleList locales = layout.getLocales();
873 final int numLocales = locales.size();
874 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
875 final Locale locale = locales.get(localeIndex);
876 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000877 return layout.getDescriptor();
878 }
879 }
880 }
881
882 // Give up and just use the highest priority layout with matching language
883 return layouts.get(0).getDescriptor();
884 }
885
886 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
887 // Different languages are never compatible
888 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
889 return false;
890 }
891 // If both the system and the keyboard layout have a country specifier, they must be equal.
892 if (!TextUtils.isEmpty(systemLocale.getCountry())
893 && !TextUtils.isEmpty(keyboardLocale.getCountry())
894 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
895 return false;
896 }
897 return true;
898 }
899
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800900 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700901 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
902 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800903 if (inputDeviceDescriptor == null) {
904 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
905 }
906
907 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700908 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800909 }
910 }
911
912 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700913 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800914 TouchCalibration calibration) {
915 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
916 "setTouchCalibrationForInputDevice()")) {
917 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
918 }
919 if (inputDeviceDescriptor == null) {
920 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
921 }
922 if (calibration == null) {
923 throw new IllegalArgumentException("calibration must not be null");
924 }
Jason Gerecked5220742014-03-10 09:47:59 -0700925 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
926 throw new IllegalArgumentException("surfaceRotation value out of bounds");
927 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800928
929 synchronized (mDataStore) {
930 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700931 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
932 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800933 nativeReloadCalibration(mPtr);
934 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800935 } finally {
936 mDataStore.saveIfNeeded();
937 }
938 }
939 }
940
Michael Wright39e5e942015-08-19 22:52:47 +0100941 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100942 public int isInTabletMode() {
943 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
944 "isInTabletMode()")) {
945 throw new SecurityException("Requires TABLET_MODE permission");
946 }
947 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
948 }
949
950 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100951 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100952 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100953 "registerTabletModeChangedListener()")) {
954 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
955 }
956 if (listener == null) {
957 throw new IllegalArgumentException("listener must not be null");
958 }
959
960 synchronized (mTabletModeLock) {
961 final int callingPid = Binder.getCallingPid();
962 if (mTabletModeChangedListeners.get(callingPid) != null) {
963 throw new IllegalStateException("The calling process has already registered "
964 + "a TabletModeChangedListener.");
965 }
966 TabletModeChangedListenerRecord record =
967 new TabletModeChangedListenerRecord(callingPid, listener);
968 try {
969 IBinder binder = listener.asBinder();
970 binder.linkToDeath(record, 0);
971 } catch (RemoteException ex) {
972 throw new RuntimeException(ex);
973 }
974 mTabletModeChangedListeners.put(callingPid, record);
975 }
976 }
977
978 private void onTabletModeChangedListenerDied(int pid) {
979 synchronized (mTabletModeLock) {
980 mTabletModeChangedListeners.remove(pid);
981 }
982 }
983
984 // Must be called on handler
985 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
986 mTempTabletModeChangedListenersToNotify.clear();
987 final int numListeners;
988 synchronized (mTabletModeLock) {
989 numListeners = mTabletModeChangedListeners.size();
990 for (int i = 0; i < numListeners; i++) {
991 mTempTabletModeChangedListenersToNotify.add(
992 mTabletModeChangedListeners.valueAt(i));
993 }
994 }
995 for (int i = 0; i < numListeners; i++) {
996 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
997 whenNanos, inTabletMode);
998 }
999 }
1000
Jeff Browncf39bdf2012-05-18 14:41:19 -07001001 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -07001002 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001003 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -07001004 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -07001005 if (device != null) {
1006 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001007 }
Michael Wrightc93fbd12014-09-22 20:07:59 -07001008 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1009 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1010 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1011 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
1012 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001013
1014 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001015 Notification notification =
1016 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
1017 .setContentTitle(r.getString(
1018 R.string.select_keyboard_layout_notification_title))
1019 .setContentText(r.getString(
1020 R.string.select_keyboard_layout_notification_message))
1021 .setContentIntent(keyboardLayoutIntent)
1022 .setSmallIcon(R.drawable.ic_settings_language)
1023 .setColor(mContext.getColor(
1024 com.android.internal.R.color.system_notification_accent_color))
1025 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001026 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001027 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001028 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001029 mKeyboardLayoutNotificationShown = true;
1030 }
1031 }
1032
1033 // Must be called on handler.
1034 private void hideMissingKeyboardLayoutNotification() {
1035 if (mKeyboardLayoutNotificationShown) {
1036 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001037 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001038 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001039 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001040 }
1041 }
1042
1043 // Must be called on handler.
1044 private void updateKeyboardLayouts() {
1045 // Scan all input devices state for keyboard layouts that have been uninstalled.
1046 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1047 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1048 @Override
Michael Wright07483422015-10-30 16:20:13 +00001049 public void visitKeyboardLayout(Resources resources,
1050 int keyboardLayoutResId, KeyboardLayout layout) {
1051 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001052 }
1053 });
1054 synchronized (mDataStore) {
1055 try {
1056 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1057 } finally {
1058 mDataStore.saveIfNeeded();
1059 }
1060 }
1061
1062 // Reload keyboard layouts.
1063 reloadKeyboardLayouts();
1064 }
1065
Jeff Browncf39bdf2012-05-18 14:41:19 -07001066 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1067 String descriptor) {
1068 final int numDevices = inputDevices.length;
1069 for (int i = 0; i < numDevices; i++) {
1070 final InputDevice inputDevice = inputDevices[i];
1071 if (inputDevice.getDescriptor().equals(descriptor)) {
1072 return true;
1073 }
1074 }
1075 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001076 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001077
1078 @Override // Binder call
1079 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001080 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1081 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1082 @Override
Michael Wright07483422015-10-30 16:20:13 +00001083 public void visitKeyboardLayout(Resources resources,
1084 int keyboardLayoutResId, KeyboardLayout layout) {
1085 list.add(layout);
1086 }
1087 });
1088 return list.toArray(new KeyboardLayout[list.size()]);
1089 }
1090
Michael Wrightb0e804a2016-01-04 16:48:53 -05001091 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001092 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1093 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001094 final String[] enabledLayoutDescriptors =
1095 getEnabledKeyboardLayoutsForInputDevice(identifier);
1096 final ArrayList<KeyboardLayout> enabledLayouts =
1097 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1098 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001099 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1100 boolean mHasSeenDeviceSpecificLayout;
1101
1102 @Override
1103 public void visitKeyboardLayout(Resources resources,
1104 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001105 // First check if it's enabled. If the keyboard layout is enabled then we always
1106 // want to return it as a possible layout for the device.
1107 for (String s : enabledLayoutDescriptors) {
1108 if (s != null && s.equals(layout.getDescriptor())) {
1109 enabledLayouts.add(layout);
1110 return;
1111 }
1112 }
1113 // Next find any potential layouts that aren't yet enabled for the device. For
1114 // devices that have special layouts we assume there's a reason that the generic
1115 // layouts don't work for them so we don't want to return them since it's likely
1116 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001117 if (layout.getVendorId() == identifier.getVendorId()
1118 && layout.getProductId() == identifier.getProductId()) {
1119 if (!mHasSeenDeviceSpecificLayout) {
1120 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001121 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001122 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001123 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001124 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1125 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001126 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001127 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001128 }
1129 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001130 final int enabledLayoutSize = enabledLayouts.size();
1131 final int potentialLayoutSize = potentialLayouts.size();
1132 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1133 enabledLayouts.toArray(layouts);
1134 for (int i = 0; i < potentialLayoutSize; i++) {
1135 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1136 }
1137 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001138 }
1139
1140 @Override // Binder call
1141 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1142 if (keyboardLayoutDescriptor == null) {
1143 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1144 }
1145
Jeff Brown6ec6f792012-04-17 16:52:41 -07001146 final KeyboardLayout[] result = new KeyboardLayout[1];
1147 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1148 @Override
Michael Wright07483422015-10-30 16:20:13 +00001149 public void visitKeyboardLayout(Resources resources,
1150 int keyboardLayoutResId, KeyboardLayout layout) {
1151 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001152 }
1153 });
1154 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001155 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001156 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001157 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001158 return result[0];
1159 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001160
Jeff Brown6ec6f792012-04-17 16:52:41 -07001161 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001162 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001163 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1164 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001165 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1166 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001167 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1168 final int priority = resolveInfo.priority;
1169 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001170 }
1171 }
1172
Jeff Brown6ec6f792012-04-17 16:52:41 -07001173 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1174 KeyboardLayoutVisitor visitor) {
1175 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1176 if (d != null) {
1177 final PackageManager pm = mContext.getPackageManager();
1178 try {
1179 ActivityInfo receiver = pm.getReceiverInfo(
1180 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001181 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001182 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1183 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001184 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001185 } catch (NameNotFoundException ex) {
1186 }
1187 }
1188 }
1189
1190 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001191 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001192 Bundle metaData = receiver.metaData;
1193 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001194 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001195 }
1196
1197 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1198 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001199 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001200 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001201 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001202 }
1203
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001204 CharSequence receiverLabel = receiver.loadLabel(pm);
1205 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001206 int priority;
1207 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1208 priority = requestedPriority;
1209 } else {
1210 priority = 0;
1211 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001212
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001213 try {
1214 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1215 XmlResourceParser parser = resources.getXml(configResId);
1216 try {
1217 XmlUtils.beginDocument(parser, "keyboard-layouts");
1218
1219 for (;;) {
1220 XmlUtils.nextElement(parser);
1221 String element = parser.getName();
1222 if (element == null) {
1223 break;
1224 }
1225 if (element.equals("keyboard-layout")) {
1226 TypedArray a = resources.obtainAttributes(
1227 parser, com.android.internal.R.styleable.KeyboardLayout);
1228 try {
1229 String name = a.getString(
1230 com.android.internal.R.styleable.KeyboardLayout_name);
1231 String label = a.getString(
1232 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001233 int keyboardLayoutResId = a.getResourceId(
1234 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1235 0);
Michael Wright07483422015-10-30 16:20:13 +00001236 String languageTags = a.getString(
1237 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001238 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001239 int vid = a.getInt(
1240 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1241 int pid = a.getInt(
1242 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1243
Jeff Brown2f095762012-05-10 21:29:33 -07001244 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001245 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001246 + "attributes in keyboard layout "
1247 + "resource from receiver "
1248 + receiver.packageName + "/" + receiver.name);
1249 } else {
1250 String descriptor = KeyboardLayoutDescriptor.format(
1251 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001252 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001253 KeyboardLayout layout = new KeyboardLayout(
1254 descriptor, label, collection, priority,
1255 locales, vid, pid);
1256 visitor.visitKeyboardLayout(
1257 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001258 }
1259 }
1260 } finally {
1261 a.recycle();
1262 }
1263 } else {
Michael Wright07483422015-10-30 16:20:13 +00001264 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001265 + "' in keyboard layout resource from receiver "
1266 + receiver.packageName + "/" + receiver.name);
1267 }
1268 }
1269 } finally {
1270 parser.close();
1271 }
1272 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001273 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001274 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001275 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001276 }
1277
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001278 @NonNull
1279 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001280 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001281 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001282 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001283 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001284 }
1285
RoboErikfb290df2013-12-16 11:27:55 -08001286 /**
1287 * Builds a layout descriptor for the vendor/product. This returns the
1288 * descriptor for ids that aren't useful (such as the default 0, 0).
1289 */
1290 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1291 if (identifier == null || identifier.getDescriptor() == null) {
1292 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001293 }
1294
RoboErikfb290df2013-12-16 11:27:55 -08001295 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1296 return identifier.getDescriptor();
1297 }
1298 StringBuilder bob = new StringBuilder();
1299 bob.append("vendor:").append(identifier.getVendorId());
1300 bob.append(",product:").append(identifier.getProductId());
1301 return bob.toString();
1302 }
1303
1304 @Override // Binder call
1305 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1306
1307 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001308 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001309 String layout = null;
1310 // try loading it using the layout descriptor if we have it
1311 layout = mDataStore.getCurrentKeyboardLayout(key);
1312 if (layout == null && !key.equals(identifier.getDescriptor())) {
1313 // if it doesn't exist fall back to the device descriptor
1314 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1315 }
1316 if (DEBUG) {
1317 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1318 + layout);
1319 }
1320 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001321 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001322 }
1323
1324 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001325 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001326 String keyboardLayoutDescriptor) {
1327 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001328 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001329 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1330 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001331 if (keyboardLayoutDescriptor == null) {
1332 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1333 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001334
RoboErikfb290df2013-12-16 11:27:55 -08001335 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001336 synchronized (mDataStore) {
1337 try {
RoboErikfb290df2013-12-16 11:27:55 -08001338 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1339 if (DEBUG) {
1340 Slog.d(TAG, "Saved keyboard layout using " + key);
1341 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001342 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1343 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001344 } finally {
1345 mDataStore.saveIfNeeded();
1346 }
1347 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001348 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001349
Jeff Browncf39bdf2012-05-18 14:41:19 -07001350 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001351 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001352 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001353 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001354 String[] layouts = mDataStore.getKeyboardLayouts(key);
1355 if ((layouts == null || layouts.length == 0)
1356 && !key.equals(identifier.getDescriptor())) {
1357 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1358 }
1359 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001360 }
1361 }
1362
1363 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001364 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001365 String keyboardLayoutDescriptor) {
1366 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1367 "addKeyboardLayoutForInputDevice()")) {
1368 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1369 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001370 if (keyboardLayoutDescriptor == null) {
1371 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1372 }
1373
RoboErikfb290df2013-12-16 11:27:55 -08001374 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001375 synchronized (mDataStore) {
1376 try {
RoboErikfb290df2013-12-16 11:27:55 -08001377 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1378 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1379 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1380 }
1381 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001382 && !Objects.equals(oldLayout,
1383 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001384 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1385 }
1386 } finally {
1387 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001388 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001389 }
1390 }
1391
1392 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001393 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001394 String keyboardLayoutDescriptor) {
1395 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1396 "removeKeyboardLayoutForInputDevice()")) {
1397 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1398 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001399 if (keyboardLayoutDescriptor == null) {
1400 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1401 }
1402
RoboErikfb290df2013-12-16 11:27:55 -08001403 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001404 synchronized (mDataStore) {
1405 try {
RoboErikfb290df2013-12-16 11:27:55 -08001406 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1407 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1408 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1409 }
1410 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1411 if (!key.equals(identifier.getDescriptor())) {
1412 // We need to remove from both places to ensure it is gone
1413 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1414 keyboardLayoutDescriptor);
1415 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001416 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001417 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001418 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1419 }
1420 } finally {
1421 mDataStore.saveIfNeeded();
1422 }
1423 }
1424 }
1425
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001426 public void switchKeyboardLayout(int deviceId, int direction) {
1427 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001428 }
1429
1430 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001431 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1432 final InputDevice device = getInputDevice(deviceId);
1433 if (device != null) {
1434 final boolean changed;
1435 final String keyboardLayoutDescriptor;
1436
1437 String key = getLayoutDescriptor(device.getIdentifier());
1438 synchronized (mDataStore) {
1439 try {
1440 changed = mDataStore.switchKeyboardLayout(key, direction);
1441 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1442 key);
1443 } finally {
1444 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001445 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001446 }
1447
1448 if (changed) {
1449 if (mSwitchedKeyboardLayoutToast != null) {
1450 mSwitchedKeyboardLayoutToast.cancel();
1451 mSwitchedKeyboardLayoutToast = null;
1452 }
1453 if (keyboardLayoutDescriptor != null) {
1454 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1455 if (keyboardLayout != null) {
1456 mSwitchedKeyboardLayoutToast = Toast.makeText(
1457 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1458 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001459 }
1460 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001461
1462 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001463 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001464 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001465 }
1466
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001467 public void setInputWindows(InputWindowHandle[] windowHandles,
Arthur Hung39134b22018-08-14 11:58:28 +08001468 InputWindowHandle focusedWindowHandle, int displayId) {
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001469 final IWindow newFocusedWindow =
1470 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1471 if (mFocusedWindow != newFocusedWindow) {
1472 mFocusedWindow = newFocusedWindow;
1473 if (mFocusedWindowHasCapture) {
1474 setPointerCapture(false);
1475 }
1476 }
Arthur Hung39134b22018-08-14 11:58:28 +08001477 nativeSetInputWindows(mPtr, windowHandles, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001478 }
RoboErikfb290df2013-12-16 11:27:55 -08001479
Jeff Brown9302c872011-07-13 22:51:29 -07001480 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001481 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001482 }
RoboErikfb290df2013-12-16 11:27:55 -08001483
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001484 @Override
1485 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1486 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1487 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1488 + windowToken);
1489 return;
1490 }
1491 if (mFocusedWindowHasCapture == enabled) {
1492 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1493 return;
1494 }
1495 setPointerCapture(enabled);
1496 try {
1497 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1498 } catch (RemoteException ex) {
1499 /* ignore */
1500 }
1501 }
1502
1503 private void setPointerCapture(boolean enabled) {
1504 mFocusedWindowHasCapture = enabled;
1505 nativeSetPointerCapture(mPtr, enabled);
1506 }
1507
Jeff Brown349703e2010-06-22 01:27:15 -07001508 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001509 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001510 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001511
1512 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001513 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001514 }
1515
Jeff Browne6504122010-09-27 14:52:15 -07001516 /**
1517 * Atomically transfers touch focus from one window to another as identified by
1518 * their input channels. It is possible for multiple windows to have
1519 * touch focus if they support split touch dispatch
1520 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1521 * method only transfers touch focus of the specified window without affecting
1522 * other windows that may also have touch focus at the same time.
1523 * @param fromChannel The channel of a window that currently has touch focus.
1524 * @param toChannel The channel of the window that should receive touch focus in
1525 * place of the first.
1526 * @return True if the transfer was successful. False if the window with the
1527 * specified channel did not actually have touch focus at the time of the request.
1528 */
1529 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1530 if (fromChannel == null) {
1531 throw new IllegalArgumentException("fromChannel must not be null.");
1532 }
1533 if (toChannel == null) {
1534 throw new IllegalArgumentException("toChannel must not be null.");
1535 }
Jeff Brown4532e612012-04-05 14:27:12 -07001536 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001537 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001538
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001539 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001540 public void tryPointerSpeed(int speed) {
1541 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1542 "tryPointerSpeed()")) {
1543 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1544 }
1545
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001546 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1547 throw new IllegalArgumentException("speed out of range");
1548 }
1549
Jeff Brownac143512012-04-05 18:57:33 -07001550 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001551 }
1552
1553 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001554 int speed = getPointerSpeedSetting();
1555 setPointerSpeedUnchecked(speed);
1556 }
1557
1558 private void setPointerSpeedUnchecked(int speed) {
1559 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1560 InputManager.MAX_POINTER_SPEED);
1561 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001562 }
1563
1564 private void registerPointerSpeedSettingObserver() {
1565 mContext.getContentResolver().registerContentObserver(
1566 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001567 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001568 @Override
1569 public void onChange(boolean selfChange) {
1570 updatePointerSpeedFromSettings();
1571 }
Jeff Brownd4935962012-09-25 13:27:20 -07001572 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001573 }
1574
Jeff Brownac143512012-04-05 18:57:33 -07001575 private int getPointerSpeedSetting() {
1576 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001577 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001578 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1579 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001580 } catch (SettingNotFoundException snfe) {
1581 }
1582 return speed;
1583 }
1584
Jeff Browndaf4a122011-08-26 17:14:14 -07001585 public void updateShowTouchesFromSettings() {
1586 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001587 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001588 }
1589
1590 private void registerShowTouchesSettingObserver() {
1591 mContext.getContentResolver().registerContentObserver(
1592 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001593 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001594 @Override
1595 public void onChange(boolean selfChange) {
1596 updateShowTouchesFromSettings();
1597 }
Jeff Brownd4935962012-09-25 13:27:20 -07001598 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001599 }
1600
Jun Mukaie4e75da2015-12-15 16:19:20 -08001601 public void updateAccessibilityLargePointerFromSettings() {
1602 final int accessibilityConfig = Settings.Secure.getIntForUser(
1603 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1604 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001605 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001606 nativeReloadPointerIcons(mPtr);
1607 }
1608
Jun Mukai19a56012015-11-24 11:25:52 -08001609 private void registerAccessibilityLargePointerSettingObserver() {
1610 mContext.getContentResolver().registerContentObserver(
1611 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1612 new ContentObserver(mHandler) {
1613 @Override
1614 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001615 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001616 }
1617 }, UserHandle.USER_ALL);
1618 }
1619
Jeff Browndaf4a122011-08-26 17:14:14 -07001620 private int getShowTouchesSetting(int defaultValue) {
1621 int result = defaultValue;
1622 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001623 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1624 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001625 } catch (SettingNotFoundException snfe) {
1626 }
1627 return result;
1628 }
1629
Jeff Browna47425a2012-04-13 04:09:27 -07001630 // Binder call
1631 @Override
1632 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1633 if (repeat >= pattern.length) {
1634 throw new ArrayIndexOutOfBoundsException();
1635 }
1636
1637 VibratorToken v;
1638 synchronized (mVibratorLock) {
1639 v = mVibratorTokens.get(token);
1640 if (v == null) {
1641 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1642 try {
1643 token.linkToDeath(v, 0);
1644 } catch (RemoteException ex) {
1645 // give up
1646 throw new RuntimeException(ex);
1647 }
1648 mVibratorTokens.put(token, v);
1649 }
1650 }
1651
1652 synchronized (v) {
1653 v.mVibrating = true;
1654 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1655 }
1656 }
1657
1658 // Binder call
1659 @Override
1660 public void cancelVibrate(int deviceId, IBinder token) {
1661 VibratorToken v;
1662 synchronized (mVibratorLock) {
1663 v = mVibratorTokens.get(token);
1664 if (v == null || v.mDeviceId != deviceId) {
1665 return; // nothing to cancel
1666 }
1667 }
1668
1669 cancelVibrateIfNeeded(v);
1670 }
1671
1672 void onVibratorTokenDied(VibratorToken v) {
1673 synchronized (mVibratorLock) {
1674 mVibratorTokens.remove(v.mToken);
1675 }
1676
1677 cancelVibrateIfNeeded(v);
1678 }
1679
1680 private void cancelVibrateIfNeeded(VibratorToken v) {
1681 synchronized (v) {
1682 if (v.mVibrating) {
1683 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1684 v.mVibrating = false;
1685 }
1686 }
1687 }
1688
Jun Mukai19a56012015-11-24 11:25:52 -08001689 // Binder call
1690 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001691 public void setPointerIconType(int iconId) {
1692 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001693 }
Jun Mukai1db53972015-09-11 18:08:31 -07001694
Jun Mukaid4eaef72015-10-30 15:54:33 -07001695 // Binder call
1696 @Override
1697 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001698 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001699 nativeSetCustomPointerIcon(mPtr, icon);
1700 }
1701
Jeff Brown4532e612012-04-05 14:27:12 -07001702 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001703 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001704 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001705
1706 pw.println("INPUT MANAGER (dumpsys input)\n");
1707 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001708 if (dumpStr != null) {
1709 pw.println(dumpStr);
1710 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001711 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001712
Jeff Brownac143512012-04-05 18:57:33 -07001713 private boolean checkCallingPermission(String permission, String func) {
1714 // Quick check: if the calling permission is me, it's all okay.
1715 if (Binder.getCallingPid() == Process.myPid()) {
1716 return true;
1717 }
1718
1719 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1720 return true;
1721 }
1722 String msg = "Permission Denial: " + func + " from pid="
1723 + Binder.getCallingPid()
1724 + ", uid=" + Binder.getCallingUid()
1725 + " requires " + permission;
1726 Slog.w(TAG, msg);
1727 return false;
1728 }
1729
Jeff Brown4532e612012-04-05 14:27:12 -07001730 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001731 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001732 public void monitor() {
1733 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001734 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001735 }
1736
Andrii Kulianed76e742017-06-26 14:57:02 -07001737 // Binder call
1738 @Override
1739 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1740 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1741 "createInputForwarder()")) {
1742 throw new SecurityException("Requires INJECT_EVENTS permission");
1743 }
1744 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1745 final Display display = displayManager.getDisplay(displayId);
1746 if (display == null) {
1747 throw new IllegalArgumentException(
1748 "Can't create input forwarder for non-existent displayId: " + displayId);
1749 }
1750 final int callingUid = Binder.getCallingUid();
1751 final int displayOwnerUid = display.getOwnerUid();
1752 if (callingUid != displayOwnerUid) {
1753 throw new SecurityException(
1754 "Only owner of the display can forward input events to it.");
1755 }
1756
1757 return new InputForwarder(displayId);
1758 }
1759
Jeff Brown4532e612012-04-05 14:27:12 -07001760 // Native callback.
1761 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001762 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001763 }
1764
1765 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001766 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1767 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001768 if (!mInputDevicesChangedPending) {
1769 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001770 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1771 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001772 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001773
1774 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001775 }
1776 }
1777
1778 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001779 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1780 if (DEBUG) {
1781 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1782 + ", mask=" + Integer.toHexString(switchMask));
1783 }
1784
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001785 if ((switchMask & SW_LID_BIT) != 0) {
1786 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001787 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001788 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001789
Michael Wright3818c922014-09-02 13:59:07 -07001790 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001791 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001792 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1793 }
1794
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001795 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1796 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1797 switchMask);
1798 }
Michael Wright39e5e942015-08-19 22:52:47 +01001799
Michael Wright9209c9c2015-09-03 17:57:01 +01001800 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001801 SomeArgs args = SomeArgs.obtain();
1802 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1803 args.argi2 = (int) (whenNanos >> 32);
1804 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1805 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1806 args).sendToTarget();
1807 }
Jeff Brown4532e612012-04-05 14:27:12 -07001808 }
1809
1810 // Native callback.
1811 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001812 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001813 }
1814
1815 // Native callback.
1816 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001817 InputWindowHandle inputWindowHandle, String reason) {
1818 return mWindowManagerCallbacks.notifyANR(
1819 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001820 }
1821
1822 // Native callback.
1823 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1824 synchronized (mInputFilterLock) {
1825 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001826 try {
1827 mInputFilter.filterInputEvent(event, policyFlags);
1828 } catch (RemoteException e) {
1829 /* ignore */
1830 }
Jeff Brown4532e612012-04-05 14:27:12 -07001831 return false;
1832 }
1833 }
1834 event.recycle();
1835 return true;
1836 }
1837
1838 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001839 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1840 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001841 }
1842
1843 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001844 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1845 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001846 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001847 }
1848
1849 // Native callback.
1850 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1851 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001852 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001853 }
1854
1855 // Native callback.
1856 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1857 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001858 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001859 }
1860
1861 // Native callback.
1862 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1863 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1864 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1865 }
1866
1867 // Native callback.
1868 private int getVirtualKeyQuietTimeMillis() {
1869 return mContext.getResources().getInteger(
1870 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1871 }
1872
1873 // Native callback.
1874 private String[] getExcludedDeviceNames() {
1875 ArrayList<String> names = new ArrayList<String>();
1876
1877 // Read partner-provided list of excluded input devices
1878 XmlPullParser parser = null;
1879 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1880 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1881 FileReader confreader = null;
1882 try {
1883 confreader = new FileReader(confFile);
1884 parser = Xml.newPullParser();
1885 parser.setInput(confreader);
1886 XmlUtils.beginDocument(parser, "devices");
1887
1888 while (true) {
1889 XmlUtils.nextElement(parser);
1890 if (!"device".equals(parser.getName())) {
1891 break;
1892 }
1893 String name = parser.getAttributeValue(null, "name");
1894 if (name != null) {
1895 names.add(name);
1896 }
1897 }
1898 } catch (FileNotFoundException e) {
1899 // It's ok if the file does not exist.
1900 } catch (Exception e) {
1901 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1902 } finally {
1903 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1904 }
1905
1906 return names.toArray(new String[names.size()]);
1907 }
1908
1909 // Native callback.
1910 private int getKeyRepeatTimeout() {
1911 return ViewConfiguration.getKeyRepeatTimeout();
1912 }
1913
1914 // Native callback.
1915 private int getKeyRepeatDelay() {
1916 return ViewConfiguration.getKeyRepeatDelay();
1917 }
1918
1919 // Native callback.
1920 private int getHoverTapTimeout() {
1921 return ViewConfiguration.getHoverTapTimeout();
1922 }
1923
1924 // Native callback.
1925 private int getHoverTapSlop() {
1926 return ViewConfiguration.getHoverTapSlop();
1927 }
1928
1929 // Native callback.
1930 private int getDoubleTapTimeout() {
1931 return ViewConfiguration.getDoubleTapTimeout();
1932 }
1933
1934 // Native callback.
1935 private int getLongPressTimeout() {
1936 return ViewConfiguration.getLongPressTimeout();
1937 }
1938
1939 // Native callback.
1940 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001941 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001942 }
1943
1944 // Native callback.
1945 private PointerIcon getPointerIcon() {
1946 return PointerIcon.getDefaultIcon(mContext);
1947 }
1948
Jeff Brown6ec6f792012-04-17 16:52:41 -07001949 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001950 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001951 if (!mSystemReady) {
1952 return null;
1953 }
1954
RoboErikfb290df2013-12-16 11:27:55 -08001955 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001956 if (keyboardLayoutDescriptor == null) {
1957 return null;
1958 }
1959
1960 final String[] result = new String[2];
1961 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1962 @Override
Michael Wright07483422015-10-30 16:20:13 +00001963 public void visitKeyboardLayout(Resources resources,
1964 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001965 try {
Michael Wright07483422015-10-30 16:20:13 +00001966 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001967 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001968 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001969 } catch (IOException ex) {
1970 } catch (NotFoundException ex) {
1971 }
1972 }
1973 });
1974 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001975 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001976 + keyboardLayoutDescriptor + "'.");
1977 return null;
1978 }
1979 return result;
1980 }
1981
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001982 // Native callback.
1983 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001984 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1985 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1986 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001987 }
1988 return null;
1989 }
1990
Jeff Brown4532e612012-04-05 14:27:12 -07001991 /**
1992 * Callback interface implemented by the Window Manager.
1993 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001994 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001995 public void notifyConfigurationChanged();
1996
1997 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1998
Michael Wright3818c922014-09-02 13:59:07 -07001999 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2000
Jeff Brown4532e612012-04-05 14:27:12 -07002001 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
2002
2003 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07002004 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002005
Jeff Brown037c33e2014-04-09 00:31:55 -07002006 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002007
Michael Wright70af00a2014-09-03 19:30:20 -07002008 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002009
2010 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2011 KeyEvent event, int policyFlags);
2012
2013 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2014 KeyEvent event, int policyFlags);
2015
2016 public int getPointerLayer();
2017 }
2018
2019 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002020 * Callback interface implemented by WiredAccessoryObserver.
2021 */
2022 public interface WiredAccessoryCallbacks {
2023 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002024 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002025 }
2026
2027 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002028 * Private handler for the input manager.
2029 */
2030 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002031 public InputManagerHandler(Looper looper) {
2032 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002033 }
2034
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002035 @Override
2036 public void handleMessage(Message msg) {
2037 switch (msg.what) {
2038 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002039 deliverInputDevicesChanged((InputDevice[])msg.obj);
2040 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002041 case MSG_SWITCH_KEYBOARD_LAYOUT:
2042 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002043 break;
2044 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2045 reloadKeyboardLayouts();
2046 break;
2047 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2048 updateKeyboardLayouts();
2049 break;
2050 case MSG_RELOAD_DEVICE_ALIASES:
2051 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002052 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002053 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002054 SomeArgs args = (SomeArgs) msg.obj;
2055 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2056 boolean inTabletMode = (boolean) args.arg1;
2057 deliverTabletModeChanged(whenNanos, inTabletMode);
2058 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002059 }
2060 }
2061 }
2062
2063 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002064 * Hosting interface for input filters to call back into the input manager.
2065 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002066 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002067 private boolean mDisconnected;
2068
2069 public void disconnectLocked() {
2070 mDisconnected = true;
2071 }
2072
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002073 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002074 public void sendInputEvent(InputEvent event, int policyFlags) {
2075 if (event == null) {
2076 throw new IllegalArgumentException("event must not be null");
2077 }
2078
2079 synchronized (mInputFilterLock) {
2080 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002081 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002082 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002083 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2084 }
2085 }
2086 }
2087 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002088
2089 private static final class KeyboardLayoutDescriptor {
2090 public String packageName;
2091 public String receiverName;
2092 public String keyboardLayoutName;
2093
2094 public static String format(String packageName,
2095 String receiverName, String keyboardName) {
2096 return packageName + "/" + receiverName + "/" + keyboardName;
2097 }
2098
2099 public static KeyboardLayoutDescriptor parse(String descriptor) {
2100 int pos = descriptor.indexOf('/');
2101 if (pos < 0 || pos + 1 == descriptor.length()) {
2102 return null;
2103 }
2104 int pos2 = descriptor.indexOf('/', pos + 1);
2105 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2106 return null;
2107 }
2108
2109 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2110 result.packageName = descriptor.substring(0, pos);
2111 result.receiverName = descriptor.substring(pos + 1, pos2);
2112 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2113 return result;
2114 }
2115 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002116
Jeff Brown6ec6f792012-04-17 16:52:41 -07002117 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002118 void visitKeyboardLayout(Resources resources,
2119 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002120 }
2121
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002122 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2123 private final int mPid;
2124 private final IInputDevicesChangedListener mListener;
2125
2126 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2127 mPid = pid;
2128 mListener = listener;
2129 }
2130
2131 @Override
2132 public void binderDied() {
2133 if (DEBUG) {
2134 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2135 }
2136 onInputDevicesChangedListenerDied(mPid);
2137 }
2138
2139 public void notifyInputDevicesChanged(int[] info) {
2140 try {
2141 mListener.onInputDevicesChanged(info);
2142 } catch (RemoteException ex) {
2143 Slog.w(TAG, "Failed to notify process "
2144 + mPid + " that input devices changed, assuming it died.", ex);
2145 binderDied();
2146 }
2147 }
2148 }
Jeff Browna47425a2012-04-13 04:09:27 -07002149
Michael Wright39e5e942015-08-19 22:52:47 +01002150 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2151 private final int mPid;
2152 private final ITabletModeChangedListener mListener;
2153
2154 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2155 mPid = pid;
2156 mListener = listener;
2157 }
2158
2159 @Override
2160 public void binderDied() {
2161 if (DEBUG) {
2162 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2163 }
2164 onTabletModeChangedListenerDied(mPid);
2165 }
2166
2167 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2168 try {
2169 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2170 } catch (RemoteException ex) {
2171 Slog.w(TAG, "Failed to notify process " + mPid +
2172 " that tablet mode changed, assuming it died.", ex);
2173 binderDied();
2174 }
2175 }
2176 }
2177
Jeff Browna47425a2012-04-13 04:09:27 -07002178 private final class VibratorToken implements DeathRecipient {
2179 public final int mDeviceId;
2180 public final IBinder mToken;
2181 public final int mTokenValue;
2182
2183 public boolean mVibrating;
2184
2185 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2186 mDeviceId = deviceId;
2187 mToken = token;
2188 mTokenValue = tokenValue;
2189 }
2190
2191 @Override
2192 public void binderDied() {
2193 if (DEBUG) {
2194 Slog.d(TAG, "Vibrator token died.");
2195 }
2196 onVibratorTokenDied(this);
2197 }
2198 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002199
2200 private final class LocalService extends InputManagerInternal {
2201 @Override
Santos Cordonee8931e2017-04-05 10:31:15 -07002202 public void setDisplayViewports(DisplayViewport defaultViewport,
2203 DisplayViewport externalTouchViewport,
2204 List<DisplayViewport> virtualTouchViewports) {
2205 setDisplayViewportsInternal(defaultViewport, externalTouchViewport,
2206 virtualTouchViewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002207 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002208
2209 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002210 public boolean injectInputEvent(InputEvent event, int mode) {
2211 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002212 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002213
2214 @Override
2215 public void setInteractive(boolean interactive) {
2216 nativeSetInteractive(mPtr, interactive);
2217 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002218
2219 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002220 public void toggleCapsLock(int deviceId) {
2221 nativeToggleCapsLock(mPtr, deviceId);
2222 }
Adrian Roos99182342016-06-15 15:30:46 -07002223
2224 @Override
2225 public void setPulseGestureEnabled(boolean enabled) {
2226 if (mDoubleTouchGestureEnableFile != null) {
2227 FileWriter writer = null;
2228 try {
2229 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2230 writer.write(enabled ? "1" : "0");
2231 } catch (IOException e) {
2232 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2233 } finally {
2234 IoUtils.closeQuietly(writer);
2235 }
2236 }
2237 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002238 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002239}