blob: c20079e8a68510ef0acafec412ffc739b2c91e23 [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown4532e612012-04-05 14:27:12 -070017package com.android.server.input;
Jeff Brown46b9ac02010-04-22 18:58:52 -070018
Yohei Yukawa5660fad2016-01-27 22:04:09 -080019import android.annotation.NonNull;
Andrii Kulianed76e742017-06-26 14:57:02 -070020import android.app.IInputForwarder;
Jeff Browncf39bdf2012-05-18 14:41:19 -070021import android.app.Notification;
22import android.app.NotificationManager;
23import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070024import android.bluetooth.BluetoothAdapter;
25import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070026import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070027import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070028import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070029import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070030import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070031import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070032import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070033import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.pm.PackageManager.NameNotFoundException;
Arthur Hung39134b22018-08-14 11:58:28 +080035import android.content.pm.ResolveInfo;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070037import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.res.TypedArray;
39import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070040import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070041import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080042import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070043import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070044import android.hardware.input.IInputManager;
Arthur Hung39134b22018-08-14 11:58:28 +080045import android.hardware.input.ITabletModeChangedListener;
RoboErikfb290df2013-12-16 11:27:55 -080046import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070047import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080048import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080050import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070053import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.os.IBinder;
Arthur Hung39134b22018-08-14 11:58:28 +080056import android.os.LocaleList;
Jeff Browna9d131c2012-09-20 16:48:17 -070057import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080059import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070063import android.provider.Settings;
64import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000065import android.text.TextUtils;
Arthur Hung39134b22018-08-14 11:58:28 +080066import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070068import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070069import android.util.Xml;
Andrii Kulianed76e742017-06-26 14:57:02 -070070import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080073import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070075import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070076import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080077import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070078import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070079import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080080import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080081import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082
Arthur Hung39134b22018-08-14 11:58:28 +080083import com.android.internal.R;
84import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
85import com.android.internal.notification.SystemNotificationChannels;
86import com.android.internal.os.SomeArgs;
87import com.android.internal.util.DumpUtils;
88import com.android.internal.util.Preconditions;
89import com.android.internal.util.XmlUtils;
90import com.android.server.DisplayThread;
91import com.android.server.LocalServices;
92import com.android.server.Watchdog;
93import com.android.server.policy.WindowManagerPolicy;
94
95import libcore.io.IoUtils;
96import libcore.io.Streams;
97
98import org.xmlpull.v1.XmlPullParser;
99
Jeff Brown46b9ac02010-04-22 18:58:52 -0700100import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700101import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102import java.io.FileNotFoundException;
103import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700104import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700106import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700107import java.io.PrintWriter;
108import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000109import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700110import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700111import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100112import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000113import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000114import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700115
Jeff Brown46b9ac02010-04-22 18:58:52 -0700116/*
117 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700118 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700119public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800120 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700122 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700123
Jeff Brown4532e612012-04-05 14:27:12 -0700124 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
125
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700126 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700127 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
128 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
129 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
130 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100131 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132
Jeff Brown4532e612012-04-05 14:27:12 -0700133 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000134 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700135
Jeff Brown46b9ac02010-04-22 18:58:52 -0700136 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700138
Adrian Roos99182342016-06-15 15:30:46 -0700139 private final File mDoubleTouchGestureEnableFile;
140
Jeff Browna9d131c2012-09-20 16:48:17 -0700141 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700142 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700143 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700144 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145
Michael Wright39e5e942015-08-19 22:52:47 +0100146 private final Object mTabletModeLock = new Object();
147 // List of currently registered tablet mode changed listeners by process id
148 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
149 new SparseArray<>(); // guarded by mTabletModeLock
150 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
151 new ArrayList<>();
152
Jeff Browna3bc5652012-04-17 11:42:25 -0700153 // Persistent data store. Must be locked each time during use.
154 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700155
156 // List of currently registered input devices changed listeners by process id.
157 private Object mInputDevicesLock = new Object();
158 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
159 private InputDevice[] mInputDevices = new InputDevice[0];
160 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
161 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
162 private final ArrayList<InputDevicesChangedListenerRecord>
163 mTempInputDevicesChangedListenersToNotify =
164 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700165 private final ArrayList<InputDevice>
166 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
167 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800168 private PendingIntent mKeyboardLayoutIntent;
169 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700170
Jeff Browna47425a2012-04-13 04:09:27 -0700171 // State for vibrator tokens.
172 private Object mVibratorLock = new Object();
173 private HashMap<IBinder, VibratorToken> mVibratorTokens =
174 new HashMap<IBinder, VibratorToken>();
175 private int mNextVibratorTokenValue;
176
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177 // State for the currently installed input filter.
178 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700179 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700180 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700181
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800182 private IWindow mFocusedWindow;
183 private boolean mFocusedWindowHasCapture;
184
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000185 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700186 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100188 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700189 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700190
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000191 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700192 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000193 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700194 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000195 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700196 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000197 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700198 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000199 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Arthur Hungbe5ce212018-09-13 18:41:56 +0800200 InputWindowHandle inputWindowHandle, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000201 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
202 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800203 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700204 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
205 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800206 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800207 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
208 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000209 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
210 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
211 private static native void nativeSetFocusedApplication(long ptr,
Tiger Huang1e5b10a2018-07-30 20:19:51 +0800212 int displayId, InputApplicationHandle application);
213 private static native void nativeSetFocusedDisplay(long ptr, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000214 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700215 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000216 private static native void nativeSetPointerSpeed(long ptr, int speed);
217 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700218 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800219 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000220 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700221 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000222 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
223 private static native void nativeReloadKeyboardLayouts(long ptr);
224 private static native void nativeReloadDeviceAliases(long ptr);
225 private static native String nativeDump(long ptr);
226 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700227 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
228 private static native void nativeEnableInputDevice(long ptr, int deviceId);
229 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100230 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800231 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700232 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800233 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700234
Jeff Brownac143512012-04-05 18:57:33 -0700235 // Input event injection constants defined in InputDispatcher.h.
236 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
237 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
238 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
239 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
240
241 // Maximum number of milliseconds to wait for input event injection.
242 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
243
Jeff Brown6d0fec22010-07-23 21:28:06 -0700244 // Key states (may be returned by queries about the current state of a
245 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700246
Jeff Brown6d0fec22010-07-23 21:28:06 -0700247 /** The key state is unknown or the requested key itself is not supported. */
248 public static final int KEY_STATE_UNKNOWN = -1;
249
250 /** The key is up. /*/
251 public static final int KEY_STATE_UP = 0;
252
253 /** The key is down. */
254 public static final int KEY_STATE_DOWN = 1;
255
256 /** The key is down but is a virtual key press that is being emulated by the system. */
257 public static final int KEY_STATE_VIRTUAL = 2;
258
Jeff Brownc458ce92012-04-30 14:58:40 -0700259 /** Scan code: Mouse / trackball button. */
260 public static final int BTN_MOUSE = 0x110;
261
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700262 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700263 /** Switch code: Lid switch. When set, lid is shut. */
264 public static final int SW_LID = 0x00;
265
Michael Wright39e5e942015-08-19 22:52:47 +0100266 /** Switch code: Tablet mode switch.
267 * When set, the device is in tablet mode (i.e. no keyboard is connected).
268 */
269 public static final int SW_TABLET_MODE = 0x01;
270
Jeff Brownc458ce92012-04-30 14:58:40 -0700271 /** Switch code: Keypad slide. When set, keyboard is exposed. */
272 public static final int SW_KEYPAD_SLIDE = 0x0a;
273
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700274 /** Switch code: Headphone. When set, headphone is inserted. */
275 public static final int SW_HEADPHONE_INSERT = 0x02;
276
277 /** Switch code: Microphone. When set, microphone is inserted. */
278 public static final int SW_MICROPHONE_INSERT = 0x04;
279
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500280 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
281 public static final int SW_LINEOUT_INSERT = 0x06;
282
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700283 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
284 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
285
Michael Wright3818c922014-09-02 13:59:07 -0700286 /** Switch code: Camera lens cover. When set the lens is covered. */
287 public static final int SW_CAMERA_LENS_COVER = 0x09;
288
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700289 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100290 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700291 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
292 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
293 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500294 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700295 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
296 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500297 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700298 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700299
300 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
301 final boolean mUseDevInputEventForAudioJack;
302
Jeff Brown4ccb8232014-01-16 22:16:42 -0800303 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700304 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800305 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800306
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700307 mUseDevInputEventForAudioJack =
308 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
309 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
310 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700311 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800312
Adrian Roos99182342016-06-15 15:30:46 -0700313 String doubleTouchGestureEnablePath = context.getResources().getString(
314 R.string.config_doubleTouchGestureEnableFile);
315 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
316 new File(doubleTouchGestureEnablePath);
317
Jeff Brown4ccb8232014-01-16 22:16:42 -0800318 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700319 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700320
Jeff Browna9d131c2012-09-20 16:48:17 -0700321 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
322 mWindowManagerCallbacks = callbacks;
323 }
324
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700325 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
326 mWiredAccessoryCallbacks = callbacks;
327 }
328
Jeff Brown46b9ac02010-04-22 18:58:52 -0700329 public void start() {
330 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700331 nativeStart(mPtr);
332
333 // Add ourself to the Watchdog monitors.
334 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700335
336 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700337 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800338 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700339
Jeff Brownd4935962012-09-25 13:27:20 -0700340 mContext.registerReceiver(new BroadcastReceiver() {
341 @Override
342 public void onReceive(Context context, Intent intent) {
343 updatePointerSpeedFromSettings();
344 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800345 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700346 }
347 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
348
Jeff Brown1a84fd12011-06-02 01:26:32 -0700349 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700350 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800351 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700352 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700353
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100354 // TODO(BT) Pass in parameter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700355 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700356 if (DEBUG) {
357 Slog.d(TAG, "System ready.");
358 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700359 mNotificationManager = (NotificationManager)mContext.getSystemService(
360 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700361 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700362
363 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
364 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
365 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800366 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700367 filter.addDataScheme("package");
368 mContext.registerReceiver(new BroadcastReceiver() {
369 @Override
370 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700371 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700372 }
373 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700374
375 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
376 mContext.registerReceiver(new BroadcastReceiver() {
377 @Override
378 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700379 reloadDeviceAliases();
380 }
381 }, filter, null, mHandler);
382
Jeff Browncf39bdf2012-05-18 14:41:19 -0700383 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
384 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700385
386 if (mWiredAccessoryCallbacks != null) {
387 mWiredAccessoryCallbacks.systemReady();
388 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700389 }
390
391 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700392 if (DEBUG) {
393 Slog.d(TAG, "Reloading keyboard layouts.");
394 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700395 nativeReloadKeyboardLayouts(mPtr);
396 }
397
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700398 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700399 if (DEBUG) {
400 Slog.d(TAG, "Reloading device names.");
401 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700402 nativeReloadDeviceAliases(mPtr);
403 }
404
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100405 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
406 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700407 }
Jeff Brownac143512012-04-05 18:57:33 -0700408
Jeff Brown6d0fec22010-07-23 21:28:06 -0700409 /**
410 * Gets the current state of a key or button by key code.
411 * @param deviceId The input device id, or -1 to consult all devices.
412 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
413 * consider all input sources. An input device is consulted if at least one of its
414 * non-class input source bits matches the specified source mask.
415 * @param keyCode The key code to check.
416 * @return The key state.
417 */
418 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700419 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700421
Jeff Brown6d0fec22010-07-23 21:28:06 -0700422 /**
423 * Gets the current state of a key or button by scan code.
424 * @param deviceId The input device id, or -1 to consult all devices.
425 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
426 * consider all input sources. An input device is consulted if at least one of its
427 * non-class input source bits matches the specified source mask.
428 * @param scanCode The scan code to check.
429 * @return The key state.
430 */
431 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700432 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700433 }
RoboErikfb290df2013-12-16 11:27:55 -0800434
Jeff Brown6d0fec22010-07-23 21:28:06 -0700435 /**
436 * Gets the current state of a switch by switch code.
437 * @param deviceId The input device id, or -1 to consult all devices.
438 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
439 * consider all input sources. An input device is consulted if at least one of its
440 * non-class input source bits matches the specified source mask.
441 * @param switchCode The switch code to check.
442 * @return The switch state.
443 */
444 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700445 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700446 }
447
Jeff Brown6d0fec22010-07-23 21:28:06 -0700448 /**
449 * Determines whether the specified key codes are supported by a particular device.
450 * @param deviceId The input device id, or -1 to consult all devices.
451 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
452 * consider all input sources. An input device is consulted if at least one of its
453 * non-class input source bits matches the specified source mask.
454 * @param keyCodes The array of key codes to check.
455 * @param keyExists An array at least as large as keyCodes whose entries will be set
456 * to true or false based on the presence or absence of support for the corresponding
457 * key codes.
458 * @return True if the lookup was successful, false otherwise.
459 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700460 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700461 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700462 if (keyCodes == null) {
463 throw new IllegalArgumentException("keyCodes must not be null.");
464 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700465 if (keyExists == null || keyExists.length < keyCodes.length) {
466 throw new IllegalArgumentException("keyExists must not be null and must be at "
467 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700468 }
RoboErikfb290df2013-12-16 11:27:55 -0800469
Jeff Brown4532e612012-04-05 14:27:12 -0700470 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700471 }
RoboErikfb290df2013-12-16 11:27:55 -0800472
Jeff Browna41ca772010-08-11 14:46:32 -0700473 /**
474 * Creates an input channel that will receive all input from the input dispatcher.
475 * @param inputChannelName The input channel name.
Arthur Hungbe5ce212018-09-13 18:41:56 +0800476 * @param displayId Target display id.
Jeff Browna41ca772010-08-11 14:46:32 -0700477 * @return The input channel.
478 */
Arthur Hungbe5ce212018-09-13 18:41:56 +0800479 public InputChannel monitorInput(String inputChannelName, int displayId) {
Jeff Browna41ca772010-08-11 14:46:32 -0700480 if (inputChannelName == null) {
481 throw new IllegalArgumentException("inputChannelName must not be null.");
482 }
RoboErikfb290df2013-12-16 11:27:55 -0800483
Arthur Hungbe5ce212018-09-13 18:41:56 +0800484 if (displayId < Display.DEFAULT_DISPLAY) {
485 throw new IllegalArgumentException("displayId must >= 0.");
486 }
487
Jeff Browna41ca772010-08-11 14:46:32 -0700488 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Arthur Hungbe5ce212018-09-13 18:41:56 +0800489 // Register channel for monitor.
490 nativeRegisterInputChannel(mPtr, inputChannels[0], null, displayId);
Jeff Browna41ca772010-08-11 14:46:32 -0700491 inputChannels[0].dispose(); // don't need to retain the Java object reference
492 return inputChannels[1];
493 }
494
495 /**
496 * Registers an input channel so that it can be used as an input event target.
497 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800498 * @param inputWindowHandle The handle of the input window associated with the
499 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700500 */
Jeff Brown928e0542011-01-10 11:17:36 -0800501 public void registerInputChannel(InputChannel inputChannel,
502 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700503 if (inputChannel == null) {
504 throw new IllegalArgumentException("inputChannel must not be null.");
505 }
RoboErikfb290df2013-12-16 11:27:55 -0800506
Arthur Hungbe5ce212018-09-13 18:41:56 +0800507 // Register channel for normal.
508 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, Display.INVALID_DISPLAY);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700509 }
RoboErikfb290df2013-12-16 11:27:55 -0800510
Jeff Browna41ca772010-08-11 14:46:32 -0700511 /**
512 * Unregisters an input channel.
513 * @param inputChannel The input channel to unregister.
514 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700515 public void unregisterInputChannel(InputChannel inputChannel) {
516 if (inputChannel == null) {
517 throw new IllegalArgumentException("inputChannel must not be null.");
518 }
RoboErikfb290df2013-12-16 11:27:55 -0800519
Jeff Brown4532e612012-04-05 14:27:12 -0700520 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700521 }
Jeff Brown0029c662011-03-30 02:25:18 -0700522
523 /**
524 * Sets an input filter that will receive all input events before they are dispatched.
525 * The input filter may then reinterpret input events or inject new ones.
526 *
527 * To ensure consistency, the input dispatcher automatically drops all events
528 * in progress whenever an input filter is installed or uninstalled. After an input
529 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
530 * Any events it attempts to send after it has been uninstalled will be dropped.
531 *
532 * @param filter The input filter, or null to remove the current filter.
533 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700534 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700535 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700536 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700537 if (oldFilter == filter) {
538 return; // nothing to do
539 }
540
541 if (oldFilter != null) {
542 mInputFilter = null;
543 mInputFilterHost.disconnectLocked();
544 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700545 try {
546 oldFilter.uninstall();
547 } catch (RemoteException re) {
548 /* ignore */
549 }
Jeff Brown0029c662011-03-30 02:25:18 -0700550 }
551
552 if (filter != null) {
553 mInputFilter = filter;
554 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700555 try {
556 filter.install(mInputFilterHost);
557 } catch (RemoteException re) {
558 /* ignore */
559 }
Jeff Brown0029c662011-03-30 02:25:18 -0700560 }
561
Jeff Brown4532e612012-04-05 14:27:12 -0700562 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700563 }
564 }
565
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700566 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700567 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800568 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800569 }
570
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800571 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700572 if (event == null) {
573 throw new IllegalArgumentException("event must not be null");
574 }
Jeff Brownac143512012-04-05 18:57:33 -0700575 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
576 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
577 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
578 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700579 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700580
Jeff Brownac143512012-04-05 18:57:33 -0700581 final int pid = Binder.getCallingPid();
582 final int uid = Binder.getCallingUid();
583 final long ident = Binder.clearCallingIdentity();
584 final int result;
585 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800586 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700587 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
588 } finally {
589 Binder.restoreCallingIdentity(ident);
590 }
591 switch (result) {
592 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
593 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
594 throw new SecurityException(
595 "Injecting to another application requires INJECT_EVENTS permission");
596 case INPUT_EVENT_INJECTION_SUCCEEDED:
597 return true;
598 case INPUT_EVENT_INJECTION_TIMED_OUT:
599 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
600 return false;
601 case INPUT_EVENT_INJECTION_FAILED:
602 default:
603 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
604 return false;
605 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700606 }
Jeff Brown0029c662011-03-30 02:25:18 -0700607
Jeff Brown8d608662010-08-30 03:02:23 -0700608 /**
609 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700610 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700611 * @return The input device or null if not found.
612 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700613 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700614 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700615 synchronized (mInputDevicesLock) {
616 final int count = mInputDevices.length;
617 for (int i = 0; i < count; i++) {
618 final InputDevice inputDevice = mInputDevices[i];
619 if (inputDevice.getId() == deviceId) {
620 return inputDevice;
621 }
622 }
623 }
624 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700625 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700626
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700627 // Binder call
628 @Override
629 public boolean isInputDeviceEnabled(int deviceId) {
630 return nativeIsInputDeviceEnabled(mPtr, deviceId);
631 }
632
633 // Binder call
634 @Override
635 public void enableInputDevice(int deviceId) {
636 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
637 "enableInputDevice()")) {
638 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
639 }
640 nativeEnableInputDevice(mPtr, deviceId);
641 }
642
643 // Binder call
644 @Override
645 public void disableInputDevice(int deviceId) {
646 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
647 "disableInputDevice()")) {
648 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
649 }
650 nativeDisableInputDevice(mPtr, deviceId);
651 }
652
Jeff Brown8d608662010-08-30 03:02:23 -0700653 /**
654 * Gets the ids of all input devices in the system.
655 * @return The input device ids.
656 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700657 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700658 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700659 synchronized (mInputDevicesLock) {
660 final int count = mInputDevices.length;
661 int[] ids = new int[count];
662 for (int i = 0; i < count; i++) {
663 ids[i] = mInputDevices[i].getId();
664 }
665 return ids;
666 }
667 }
668
Jeff Browndaa37532012-05-01 15:54:03 -0700669 /**
670 * Gets all input devices in the system.
671 * @return The array of input devices.
672 */
673 public InputDevice[] getInputDevices() {
674 synchronized (mInputDevicesLock) {
675 return mInputDevices;
676 }
677 }
678
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700679 @Override // Binder call
680 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
681 if (listener == null) {
682 throw new IllegalArgumentException("listener must not be null");
683 }
684
685 synchronized (mInputDevicesLock) {
686 int callingPid = Binder.getCallingPid();
687 if (mInputDevicesChangedListeners.get(callingPid) != null) {
688 throw new SecurityException("The calling process has already "
689 + "registered an InputDevicesChangedListener.");
690 }
691
692 InputDevicesChangedListenerRecord record =
693 new InputDevicesChangedListenerRecord(callingPid, listener);
694 try {
695 IBinder binder = listener.asBinder();
696 binder.linkToDeath(record, 0);
697 } catch (RemoteException ex) {
698 // give up
699 throw new RuntimeException(ex);
700 }
701
702 mInputDevicesChangedListeners.put(callingPid, record);
703 }
704 }
705
706 private void onInputDevicesChangedListenerDied(int pid) {
707 synchronized (mInputDevicesLock) {
708 mInputDevicesChangedListeners.remove(pid);
709 }
710 }
711
712 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700713 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
714 // Scan for changes.
715 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700716 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700717 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700718 final int numListeners;
719 final int[] deviceIdAndGeneration;
720 synchronized (mInputDevicesLock) {
721 if (!mInputDevicesChangedPending) {
722 return;
723 }
724 mInputDevicesChangedPending = false;
725
726 numListeners = mInputDevicesChangedListeners.size();
727 for (int i = 0; i < numListeners; i++) {
728 mTempInputDevicesChangedListenersToNotify.add(
729 mInputDevicesChangedListeners.valueAt(i));
730 }
731
732 final int numDevices = mInputDevices.length;
733 deviceIdAndGeneration = new int[numDevices * 2];
734 for (int i = 0; i < numDevices; i++) {
735 final InputDevice inputDevice = mInputDevices[i];
736 deviceIdAndGeneration[i * 2] = inputDevice.getId();
737 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700738
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700739 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700740 if (!containsInputDeviceWithDescriptor(oldInputDevices,
741 inputDevice.getDescriptor())) {
742 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
743 } else {
744 mTempFullKeyboards.add(inputDevice);
745 }
746 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700747 }
748 }
749
Jeff Browncf39bdf2012-05-18 14:41:19 -0700750 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700751 for (int i = 0; i < numListeners; i++) {
752 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
753 deviceIdAndGeneration);
754 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700755 mTempInputDevicesChangedListenersToNotify.clear();
756
757 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000758 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
759 final int numFullKeyboards = mTempFullKeyboards.size();
760 synchronized (mDataStore) {
761 for (int i = 0; i < numFullKeyboards; i++) {
762 final InputDevice inputDevice = mTempFullKeyboards.get(i);
763 String layout =
764 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
765 if (layout == null) {
766 layout = getDefaultKeyboardLayout(inputDevice);
767 if (layout != null) {
768 setCurrentKeyboardLayoutForInputDevice(
769 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700770 }
771 }
Michael Wright07483422015-10-30 16:20:13 +0000772 if (layout == null) {
773 keyboardsMissingLayout.add(inputDevice);
774 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700775 }
Michael Wright07483422015-10-30 16:20:13 +0000776 }
777
778 if (mNotificationManager != null) {
779 if (!keyboardsMissingLayout.isEmpty()) {
780 if (keyboardsMissingLayout.size() > 1) {
781 // We have more than one keyboard missing a layout, so drop the
782 // user at the generic input methods page so they can pick which
783 // one to set.
784 showMissingKeyboardLayoutNotification(null);
785 } else {
786 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700787 }
788 } else if (mKeyboardLayoutNotificationShown) {
789 hideMissingKeyboardLayoutNotification();
790 }
791 }
792 mTempFullKeyboards.clear();
793 }
794
Michael Wright07483422015-10-30 16:20:13 +0000795 private String getDefaultKeyboardLayout(final InputDevice d) {
796 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
797 // If our locale doesn't have a language for some reason, then we don't really have a
798 // reasonable default.
799 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
800 return null;
801 }
802 final List<KeyboardLayout> layouts = new ArrayList<>();
803 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
804 @Override
805 public void visitKeyboardLayout(Resources resources,
806 int keyboardLayoutResId, KeyboardLayout layout) {
807 // Only select a default when we know the layout is appropriate. For now, this
808 // means its a custom layout for a specific keyboard.
809 if (layout.getVendorId() != d.getVendorId()
810 || layout.getProductId() != d.getProductId()) {
811 return;
812 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800813 final LocaleList locales = layout.getLocales();
814 final int numLocales = locales.size();
815 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
816 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000817 layouts.add(layout);
818 break;
819 }
820 }
821 }
822 });
823
824 if (layouts.isEmpty()) {
825 return null;
826 }
827
828 // First sort so that ones with higher priority are listed at the top
829 Collections.sort(layouts);
830 // Next we want to try to find an exact match of language, country and variant.
831 final int N = layouts.size();
832 for (int i = 0; i < N; i++) {
833 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800834 final LocaleList locales = layout.getLocales();
835 final int numLocales = locales.size();
836 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
837 final Locale locale = locales.get(localeIndex);
838 if (locale.getCountry().equals(systemLocale.getCountry())
839 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000840 return layout.getDescriptor();
841 }
842 }
843 }
844 // Then try an exact match of language and country
845 for (int i = 0; i < N; i++) {
846 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800847 final LocaleList locales = layout.getLocales();
848 final int numLocales = locales.size();
849 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
850 final Locale locale = locales.get(localeIndex);
851 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000852 return layout.getDescriptor();
853 }
854 }
855 }
856
857 // Give up and just use the highest priority layout with matching language
858 return layouts.get(0).getDescriptor();
859 }
860
861 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
862 // Different languages are never compatible
863 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
864 return false;
865 }
866 // If both the system and the keyboard layout have a country specifier, they must be equal.
867 if (!TextUtils.isEmpty(systemLocale.getCountry())
868 && !TextUtils.isEmpty(keyboardLocale.getCountry())
869 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
870 return false;
871 }
872 return true;
873 }
874
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800875 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700876 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
877 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800878 if (inputDeviceDescriptor == null) {
879 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
880 }
881
882 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700883 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800884 }
885 }
886
887 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700888 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800889 TouchCalibration calibration) {
890 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
891 "setTouchCalibrationForInputDevice()")) {
892 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
893 }
894 if (inputDeviceDescriptor == null) {
895 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
896 }
897 if (calibration == null) {
898 throw new IllegalArgumentException("calibration must not be null");
899 }
Jason Gerecked5220742014-03-10 09:47:59 -0700900 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
901 throw new IllegalArgumentException("surfaceRotation value out of bounds");
902 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800903
904 synchronized (mDataStore) {
905 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700906 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
907 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800908 nativeReloadCalibration(mPtr);
909 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800910 } finally {
911 mDataStore.saveIfNeeded();
912 }
913 }
914 }
915
Michael Wright39e5e942015-08-19 22:52:47 +0100916 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100917 public int isInTabletMode() {
918 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
919 "isInTabletMode()")) {
920 throw new SecurityException("Requires TABLET_MODE permission");
921 }
922 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
923 }
924
925 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100926 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100927 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100928 "registerTabletModeChangedListener()")) {
929 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
930 }
931 if (listener == null) {
932 throw new IllegalArgumentException("listener must not be null");
933 }
934
935 synchronized (mTabletModeLock) {
936 final int callingPid = Binder.getCallingPid();
937 if (mTabletModeChangedListeners.get(callingPid) != null) {
938 throw new IllegalStateException("The calling process has already registered "
939 + "a TabletModeChangedListener.");
940 }
941 TabletModeChangedListenerRecord record =
942 new TabletModeChangedListenerRecord(callingPid, listener);
943 try {
944 IBinder binder = listener.asBinder();
945 binder.linkToDeath(record, 0);
946 } catch (RemoteException ex) {
947 throw new RuntimeException(ex);
948 }
949 mTabletModeChangedListeners.put(callingPid, record);
950 }
951 }
952
953 private void onTabletModeChangedListenerDied(int pid) {
954 synchronized (mTabletModeLock) {
955 mTabletModeChangedListeners.remove(pid);
956 }
957 }
958
959 // Must be called on handler
960 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
961 mTempTabletModeChangedListenersToNotify.clear();
962 final int numListeners;
963 synchronized (mTabletModeLock) {
964 numListeners = mTabletModeChangedListeners.size();
965 for (int i = 0; i < numListeners; i++) {
966 mTempTabletModeChangedListenersToNotify.add(
967 mTabletModeChangedListeners.valueAt(i));
968 }
969 }
970 for (int i = 0; i < numListeners; i++) {
971 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
972 whenNanos, inTabletMode);
973 }
974 }
975
Jeff Browncf39bdf2012-05-18 14:41:19 -0700976 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700977 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700978 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700979 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700980 if (device != null) {
981 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700982 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700983 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
984 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
985 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
986 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
987 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700988
989 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500990 Notification notification =
991 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
992 .setContentTitle(r.getString(
993 R.string.select_keyboard_layout_notification_title))
994 .setContentText(r.getString(
995 R.string.select_keyboard_layout_notification_message))
996 .setContentIntent(keyboardLayoutIntent)
997 .setSmallIcon(R.drawable.ic_settings_language)
998 .setColor(mContext.getColor(
999 com.android.internal.R.color.system_notification_accent_color))
1000 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001001 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001002 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001003 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001004 mKeyboardLayoutNotificationShown = true;
1005 }
1006 }
1007
1008 // Must be called on handler.
1009 private void hideMissingKeyboardLayoutNotification() {
1010 if (mKeyboardLayoutNotificationShown) {
1011 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001012 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001013 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001014 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001015 }
1016 }
1017
1018 // Must be called on handler.
1019 private void updateKeyboardLayouts() {
1020 // Scan all input devices state for keyboard layouts that have been uninstalled.
1021 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1022 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1023 @Override
Michael Wright07483422015-10-30 16:20:13 +00001024 public void visitKeyboardLayout(Resources resources,
1025 int keyboardLayoutResId, KeyboardLayout layout) {
1026 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001027 }
1028 });
1029 synchronized (mDataStore) {
1030 try {
1031 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1032 } finally {
1033 mDataStore.saveIfNeeded();
1034 }
1035 }
1036
1037 // Reload keyboard layouts.
1038 reloadKeyboardLayouts();
1039 }
1040
Jeff Browncf39bdf2012-05-18 14:41:19 -07001041 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1042 String descriptor) {
1043 final int numDevices = inputDevices.length;
1044 for (int i = 0; i < numDevices; i++) {
1045 final InputDevice inputDevice = inputDevices[i];
1046 if (inputDevice.getDescriptor().equals(descriptor)) {
1047 return true;
1048 }
1049 }
1050 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001051 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001052
1053 @Override // Binder call
1054 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001055 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1056 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1057 @Override
Michael Wright07483422015-10-30 16:20:13 +00001058 public void visitKeyboardLayout(Resources resources,
1059 int keyboardLayoutResId, KeyboardLayout layout) {
1060 list.add(layout);
1061 }
1062 });
1063 return list.toArray(new KeyboardLayout[list.size()]);
1064 }
1065
Michael Wrightb0e804a2016-01-04 16:48:53 -05001066 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001067 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1068 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001069 final String[] enabledLayoutDescriptors =
1070 getEnabledKeyboardLayoutsForInputDevice(identifier);
1071 final ArrayList<KeyboardLayout> enabledLayouts =
1072 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1073 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001074 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1075 boolean mHasSeenDeviceSpecificLayout;
1076
1077 @Override
1078 public void visitKeyboardLayout(Resources resources,
1079 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001080 // First check if it's enabled. If the keyboard layout is enabled then we always
1081 // want to return it as a possible layout for the device.
1082 for (String s : enabledLayoutDescriptors) {
1083 if (s != null && s.equals(layout.getDescriptor())) {
1084 enabledLayouts.add(layout);
1085 return;
1086 }
1087 }
1088 // Next find any potential layouts that aren't yet enabled for the device. For
1089 // devices that have special layouts we assume there's a reason that the generic
1090 // layouts don't work for them so we don't want to return them since it's likely
1091 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001092 if (layout.getVendorId() == identifier.getVendorId()
1093 && layout.getProductId() == identifier.getProductId()) {
1094 if (!mHasSeenDeviceSpecificLayout) {
1095 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001096 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001097 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001098 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001099 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1100 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001101 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001102 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001103 }
1104 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001105 final int enabledLayoutSize = enabledLayouts.size();
1106 final int potentialLayoutSize = potentialLayouts.size();
1107 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1108 enabledLayouts.toArray(layouts);
1109 for (int i = 0; i < potentialLayoutSize; i++) {
1110 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1111 }
1112 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001113 }
1114
1115 @Override // Binder call
1116 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1117 if (keyboardLayoutDescriptor == null) {
1118 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1119 }
1120
Jeff Brown6ec6f792012-04-17 16:52:41 -07001121 final KeyboardLayout[] result = new KeyboardLayout[1];
1122 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1123 @Override
Michael Wright07483422015-10-30 16:20:13 +00001124 public void visitKeyboardLayout(Resources resources,
1125 int keyboardLayoutResId, KeyboardLayout layout) {
1126 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001127 }
1128 });
1129 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001130 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001131 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001132 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001133 return result[0];
1134 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001135
Jeff Brown6ec6f792012-04-17 16:52:41 -07001136 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001137 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001138 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1139 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001140 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1141 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001142 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1143 final int priority = resolveInfo.priority;
1144 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001145 }
1146 }
1147
Jeff Brown6ec6f792012-04-17 16:52:41 -07001148 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1149 KeyboardLayoutVisitor visitor) {
1150 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1151 if (d != null) {
1152 final PackageManager pm = mContext.getPackageManager();
1153 try {
1154 ActivityInfo receiver = pm.getReceiverInfo(
1155 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001156 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001157 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1158 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001159 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001160 } catch (NameNotFoundException ex) {
1161 }
1162 }
1163 }
1164
1165 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001166 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001167 Bundle metaData = receiver.metaData;
1168 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001169 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001170 }
1171
1172 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1173 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001174 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001175 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001176 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001177 }
1178
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001179 CharSequence receiverLabel = receiver.loadLabel(pm);
1180 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001181 int priority;
1182 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1183 priority = requestedPriority;
1184 } else {
1185 priority = 0;
1186 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001187
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001188 try {
1189 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1190 XmlResourceParser parser = resources.getXml(configResId);
1191 try {
1192 XmlUtils.beginDocument(parser, "keyboard-layouts");
1193
1194 for (;;) {
1195 XmlUtils.nextElement(parser);
1196 String element = parser.getName();
1197 if (element == null) {
1198 break;
1199 }
1200 if (element.equals("keyboard-layout")) {
1201 TypedArray a = resources.obtainAttributes(
1202 parser, com.android.internal.R.styleable.KeyboardLayout);
1203 try {
1204 String name = a.getString(
1205 com.android.internal.R.styleable.KeyboardLayout_name);
1206 String label = a.getString(
1207 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001208 int keyboardLayoutResId = a.getResourceId(
1209 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1210 0);
Michael Wright07483422015-10-30 16:20:13 +00001211 String languageTags = a.getString(
1212 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001213 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001214 int vid = a.getInt(
1215 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1216 int pid = a.getInt(
1217 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1218
Jeff Brown2f095762012-05-10 21:29:33 -07001219 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001220 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001221 + "attributes in keyboard layout "
1222 + "resource from receiver "
1223 + receiver.packageName + "/" + receiver.name);
1224 } else {
1225 String descriptor = KeyboardLayoutDescriptor.format(
1226 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001227 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001228 KeyboardLayout layout = new KeyboardLayout(
1229 descriptor, label, collection, priority,
1230 locales, vid, pid);
1231 visitor.visitKeyboardLayout(
1232 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001233 }
1234 }
1235 } finally {
1236 a.recycle();
1237 }
1238 } else {
Michael Wright07483422015-10-30 16:20:13 +00001239 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001240 + "' in keyboard layout resource from receiver "
1241 + receiver.packageName + "/" + receiver.name);
1242 }
1243 }
1244 } finally {
1245 parser.close();
1246 }
1247 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001248 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001249 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001250 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001251 }
1252
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001253 @NonNull
1254 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001255 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001256 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001257 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001258 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001259 }
1260
RoboErikfb290df2013-12-16 11:27:55 -08001261 /**
1262 * Builds a layout descriptor for the vendor/product. This returns the
1263 * descriptor for ids that aren't useful (such as the default 0, 0).
1264 */
1265 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1266 if (identifier == null || identifier.getDescriptor() == null) {
1267 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001268 }
1269
RoboErikfb290df2013-12-16 11:27:55 -08001270 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1271 return identifier.getDescriptor();
1272 }
1273 StringBuilder bob = new StringBuilder();
1274 bob.append("vendor:").append(identifier.getVendorId());
1275 bob.append(",product:").append(identifier.getProductId());
1276 return bob.toString();
1277 }
1278
1279 @Override // Binder call
1280 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1281
1282 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001283 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001284 String layout = null;
1285 // try loading it using the layout descriptor if we have it
1286 layout = mDataStore.getCurrentKeyboardLayout(key);
1287 if (layout == null && !key.equals(identifier.getDescriptor())) {
1288 // if it doesn't exist fall back to the device descriptor
1289 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1290 }
1291 if (DEBUG) {
1292 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1293 + layout);
1294 }
1295 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001296 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001297 }
1298
1299 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001300 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001301 String keyboardLayoutDescriptor) {
1302 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001303 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001304 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1305 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001306 if (keyboardLayoutDescriptor == null) {
1307 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1308 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001309
RoboErikfb290df2013-12-16 11:27:55 -08001310 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001311 synchronized (mDataStore) {
1312 try {
RoboErikfb290df2013-12-16 11:27:55 -08001313 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1314 if (DEBUG) {
1315 Slog.d(TAG, "Saved keyboard layout using " + key);
1316 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001317 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1318 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001319 } finally {
1320 mDataStore.saveIfNeeded();
1321 }
1322 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001323 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001324
Jeff Browncf39bdf2012-05-18 14:41:19 -07001325 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001326 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001327 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001328 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001329 String[] layouts = mDataStore.getKeyboardLayouts(key);
1330 if ((layouts == null || layouts.length == 0)
1331 && !key.equals(identifier.getDescriptor())) {
1332 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1333 }
1334 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001335 }
1336 }
1337
1338 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001339 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001340 String keyboardLayoutDescriptor) {
1341 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1342 "addKeyboardLayoutForInputDevice()")) {
1343 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1344 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001345 if (keyboardLayoutDescriptor == null) {
1346 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1347 }
1348
RoboErikfb290df2013-12-16 11:27:55 -08001349 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001350 synchronized (mDataStore) {
1351 try {
RoboErikfb290df2013-12-16 11:27:55 -08001352 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1353 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1354 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1355 }
1356 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001357 && !Objects.equals(oldLayout,
1358 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001359 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1360 }
1361 } finally {
1362 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001363 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001364 }
1365 }
1366
1367 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001368 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001369 String keyboardLayoutDescriptor) {
1370 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1371 "removeKeyboardLayoutForInputDevice()")) {
1372 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1373 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001374 if (keyboardLayoutDescriptor == null) {
1375 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1376 }
1377
RoboErikfb290df2013-12-16 11:27:55 -08001378 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001379 synchronized (mDataStore) {
1380 try {
RoboErikfb290df2013-12-16 11:27:55 -08001381 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1382 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1383 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1384 }
1385 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1386 if (!key.equals(identifier.getDescriptor())) {
1387 // We need to remove from both places to ensure it is gone
1388 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1389 keyboardLayoutDescriptor);
1390 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001391 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001392 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001393 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1394 }
1395 } finally {
1396 mDataStore.saveIfNeeded();
1397 }
1398 }
1399 }
1400
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001401 public void switchKeyboardLayout(int deviceId, int direction) {
1402 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001403 }
1404
1405 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001406 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1407 final InputDevice device = getInputDevice(deviceId);
1408 if (device != null) {
1409 final boolean changed;
1410 final String keyboardLayoutDescriptor;
1411
1412 String key = getLayoutDescriptor(device.getIdentifier());
1413 synchronized (mDataStore) {
1414 try {
1415 changed = mDataStore.switchKeyboardLayout(key, direction);
1416 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1417 key);
1418 } finally {
1419 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001420 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001421 }
1422
1423 if (changed) {
1424 if (mSwitchedKeyboardLayoutToast != null) {
1425 mSwitchedKeyboardLayoutToast.cancel();
1426 mSwitchedKeyboardLayoutToast = null;
1427 }
1428 if (keyboardLayoutDescriptor != null) {
1429 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1430 if (keyboardLayout != null) {
1431 mSwitchedKeyboardLayoutToast = Toast.makeText(
1432 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1433 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001434 }
1435 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001436
1437 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001438 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001439 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001440 }
1441
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001442 public void setInputWindows(InputWindowHandle[] windowHandles, int displayId) {
Arthur Hung39134b22018-08-14 11:58:28 +08001443 nativeSetInputWindows(mPtr, windowHandles, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001444 }
RoboErikfb290df2013-12-16 11:27:55 -08001445
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001446 public void setFocusedApplication(int displayId, InputApplicationHandle application) {
1447 nativeSetFocusedApplication(mPtr, displayId, application);
1448 }
1449
1450 public void setFocusedWindow(InputWindowHandle focusedWindowHandle) {
1451 final IWindow newFocusedWindow =
1452 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1453 if (mFocusedWindow != newFocusedWindow) {
1454 if (mFocusedWindowHasCapture) {
1455 setPointerCapture(false);
1456 }
1457 mFocusedWindow = newFocusedWindow;
1458 }
1459 }
1460
1461 public void setFocusedDisplay(int displayId) {
1462 nativeSetFocusedDisplay(mPtr, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001463 }
RoboErikfb290df2013-12-16 11:27:55 -08001464
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001465 @Override
1466 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1467 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1468 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1469 + windowToken);
1470 return;
1471 }
1472 if (mFocusedWindowHasCapture == enabled) {
1473 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1474 return;
1475 }
1476 setPointerCapture(enabled);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001477 }
1478
1479 private void setPointerCapture(boolean enabled) {
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001480 if (mFocusedWindowHasCapture != enabled) {
1481 mFocusedWindowHasCapture = enabled;
1482 try {
1483 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1484 } catch (RemoteException ex) {
1485 /* ignore */
1486 }
1487 nativeSetPointerCapture(mPtr, enabled);
1488 }
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001489 }
1490
Jeff Brown349703e2010-06-22 01:27:15 -07001491 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001492 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001493 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001494
1495 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001496 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001497 }
1498
Jeff Browne6504122010-09-27 14:52:15 -07001499 /**
1500 * Atomically transfers touch focus from one window to another as identified by
1501 * their input channels. It is possible for multiple windows to have
1502 * touch focus if they support split touch dispatch
1503 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1504 * method only transfers touch focus of the specified window without affecting
1505 * other windows that may also have touch focus at the same time.
1506 * @param fromChannel The channel of a window that currently has touch focus.
1507 * @param toChannel The channel of the window that should receive touch focus in
1508 * place of the first.
1509 * @return True if the transfer was successful. False if the window with the
1510 * specified channel did not actually have touch focus at the time of the request.
1511 */
1512 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1513 if (fromChannel == null) {
1514 throw new IllegalArgumentException("fromChannel must not be null.");
1515 }
1516 if (toChannel == null) {
1517 throw new IllegalArgumentException("toChannel must not be null.");
1518 }
Jeff Brown4532e612012-04-05 14:27:12 -07001519 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001520 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001521
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001522 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001523 public void tryPointerSpeed(int speed) {
1524 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1525 "tryPointerSpeed()")) {
1526 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1527 }
1528
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001529 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1530 throw new IllegalArgumentException("speed out of range");
1531 }
1532
Jeff Brownac143512012-04-05 18:57:33 -07001533 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001534 }
1535
1536 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001537 int speed = getPointerSpeedSetting();
1538 setPointerSpeedUnchecked(speed);
1539 }
1540
1541 private void setPointerSpeedUnchecked(int speed) {
1542 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1543 InputManager.MAX_POINTER_SPEED);
1544 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001545 }
1546
1547 private void registerPointerSpeedSettingObserver() {
1548 mContext.getContentResolver().registerContentObserver(
1549 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001550 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001551 @Override
1552 public void onChange(boolean selfChange) {
1553 updatePointerSpeedFromSettings();
1554 }
Jeff Brownd4935962012-09-25 13:27:20 -07001555 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001556 }
1557
Jeff Brownac143512012-04-05 18:57:33 -07001558 private int getPointerSpeedSetting() {
1559 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001560 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001561 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1562 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001563 } catch (SettingNotFoundException snfe) {
1564 }
1565 return speed;
1566 }
1567
Jeff Browndaf4a122011-08-26 17:14:14 -07001568 public void updateShowTouchesFromSettings() {
1569 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001570 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001571 }
1572
1573 private void registerShowTouchesSettingObserver() {
1574 mContext.getContentResolver().registerContentObserver(
1575 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001576 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001577 @Override
1578 public void onChange(boolean selfChange) {
1579 updateShowTouchesFromSettings();
1580 }
Jeff Brownd4935962012-09-25 13:27:20 -07001581 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001582 }
1583
Jun Mukaie4e75da2015-12-15 16:19:20 -08001584 public void updateAccessibilityLargePointerFromSettings() {
1585 final int accessibilityConfig = Settings.Secure.getIntForUser(
1586 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1587 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001588 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001589 nativeReloadPointerIcons(mPtr);
1590 }
1591
Jun Mukai19a56012015-11-24 11:25:52 -08001592 private void registerAccessibilityLargePointerSettingObserver() {
1593 mContext.getContentResolver().registerContentObserver(
1594 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1595 new ContentObserver(mHandler) {
1596 @Override
1597 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001598 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001599 }
1600 }, UserHandle.USER_ALL);
1601 }
1602
Jeff Browndaf4a122011-08-26 17:14:14 -07001603 private int getShowTouchesSetting(int defaultValue) {
1604 int result = defaultValue;
1605 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001606 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1607 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001608 } catch (SettingNotFoundException snfe) {
1609 }
1610 return result;
1611 }
1612
Jeff Browna47425a2012-04-13 04:09:27 -07001613 // Binder call
1614 @Override
1615 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1616 if (repeat >= pattern.length) {
1617 throw new ArrayIndexOutOfBoundsException();
1618 }
1619
1620 VibratorToken v;
1621 synchronized (mVibratorLock) {
1622 v = mVibratorTokens.get(token);
1623 if (v == null) {
1624 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1625 try {
1626 token.linkToDeath(v, 0);
1627 } catch (RemoteException ex) {
1628 // give up
1629 throw new RuntimeException(ex);
1630 }
1631 mVibratorTokens.put(token, v);
1632 }
1633 }
1634
1635 synchronized (v) {
1636 v.mVibrating = true;
1637 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1638 }
1639 }
1640
1641 // Binder call
1642 @Override
1643 public void cancelVibrate(int deviceId, IBinder token) {
1644 VibratorToken v;
1645 synchronized (mVibratorLock) {
1646 v = mVibratorTokens.get(token);
1647 if (v == null || v.mDeviceId != deviceId) {
1648 return; // nothing to cancel
1649 }
1650 }
1651
1652 cancelVibrateIfNeeded(v);
1653 }
1654
1655 void onVibratorTokenDied(VibratorToken v) {
1656 synchronized (mVibratorLock) {
1657 mVibratorTokens.remove(v.mToken);
1658 }
1659
1660 cancelVibrateIfNeeded(v);
1661 }
1662
1663 private void cancelVibrateIfNeeded(VibratorToken v) {
1664 synchronized (v) {
1665 if (v.mVibrating) {
1666 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1667 v.mVibrating = false;
1668 }
1669 }
1670 }
1671
Jun Mukai19a56012015-11-24 11:25:52 -08001672 // Binder call
1673 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001674 public void setPointerIconType(int iconId) {
1675 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001676 }
Jun Mukai1db53972015-09-11 18:08:31 -07001677
Jun Mukaid4eaef72015-10-30 15:54:33 -07001678 // Binder call
1679 @Override
1680 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001681 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001682 nativeSetCustomPointerIcon(mPtr, icon);
1683 }
1684
Jeff Brown4532e612012-04-05 14:27:12 -07001685 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001686 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001687 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001688
1689 pw.println("INPUT MANAGER (dumpsys input)\n");
1690 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001691 if (dumpStr != null) {
1692 pw.println(dumpStr);
1693 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001694 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001695
Jeff Brownac143512012-04-05 18:57:33 -07001696 private boolean checkCallingPermission(String permission, String func) {
1697 // Quick check: if the calling permission is me, it's all okay.
1698 if (Binder.getCallingPid() == Process.myPid()) {
1699 return true;
1700 }
1701
1702 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1703 return true;
1704 }
1705 String msg = "Permission Denial: " + func + " from pid="
1706 + Binder.getCallingPid()
1707 + ", uid=" + Binder.getCallingUid()
1708 + " requires " + permission;
1709 Slog.w(TAG, msg);
1710 return false;
1711 }
1712
Jeff Brown4532e612012-04-05 14:27:12 -07001713 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001714 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001715 public void monitor() {
1716 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001717 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001718 }
1719
Andrii Kulianed76e742017-06-26 14:57:02 -07001720 // Binder call
1721 @Override
1722 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1723 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1724 "createInputForwarder()")) {
1725 throw new SecurityException("Requires INJECT_EVENTS permission");
1726 }
1727 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1728 final Display display = displayManager.getDisplay(displayId);
1729 if (display == null) {
1730 throw new IllegalArgumentException(
1731 "Can't create input forwarder for non-existent displayId: " + displayId);
1732 }
1733 final int callingUid = Binder.getCallingUid();
1734 final int displayOwnerUid = display.getOwnerUid();
1735 if (callingUid != displayOwnerUid) {
1736 throw new SecurityException(
1737 "Only owner of the display can forward input events to it.");
1738 }
1739
1740 return new InputForwarder(displayId);
1741 }
1742
Jeff Brown4532e612012-04-05 14:27:12 -07001743 // Native callback.
1744 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001745 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001746 }
1747
1748 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001749 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1750 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001751 if (!mInputDevicesChangedPending) {
1752 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001753 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1754 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001755 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001756
1757 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001758 }
1759 }
1760
1761 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001762 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1763 if (DEBUG) {
1764 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1765 + ", mask=" + Integer.toHexString(switchMask));
1766 }
1767
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001768 if ((switchMask & SW_LID_BIT) != 0) {
1769 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001770 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001771 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001772
Michael Wright3818c922014-09-02 13:59:07 -07001773 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001774 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001775 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1776 }
1777
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001778 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1779 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1780 switchMask);
1781 }
Michael Wright39e5e942015-08-19 22:52:47 +01001782
Michael Wright9209c9c2015-09-03 17:57:01 +01001783 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001784 SomeArgs args = SomeArgs.obtain();
1785 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1786 args.argi2 = (int) (whenNanos >> 32);
1787 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1788 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1789 args).sendToTarget();
1790 }
Jeff Brown4532e612012-04-05 14:27:12 -07001791 }
1792
1793 // Native callback.
1794 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001795 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001796 }
1797
1798 // Native callback.
1799 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001800 InputWindowHandle inputWindowHandle, String reason) {
1801 return mWindowManagerCallbacks.notifyANR(
1802 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001803 }
1804
1805 // Native callback.
1806 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1807 synchronized (mInputFilterLock) {
1808 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001809 try {
1810 mInputFilter.filterInputEvent(event, policyFlags);
1811 } catch (RemoteException e) {
1812 /* ignore */
1813 }
Jeff Brown4532e612012-04-05 14:27:12 -07001814 return false;
1815 }
1816 }
1817 event.recycle();
1818 return true;
1819 }
1820
1821 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001822 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1823 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001824 }
1825
1826 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001827 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1828 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001829 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001830 }
1831
1832 // Native callback.
1833 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1834 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001835 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001836 }
1837
1838 // Native callback.
1839 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1840 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001841 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001842 }
1843
1844 // Native callback.
1845 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1846 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1847 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1848 }
1849
1850 // Native callback.
1851 private int getVirtualKeyQuietTimeMillis() {
1852 return mContext.getResources().getInteger(
1853 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1854 }
1855
1856 // Native callback.
1857 private String[] getExcludedDeviceNames() {
1858 ArrayList<String> names = new ArrayList<String>();
1859
1860 // Read partner-provided list of excluded input devices
1861 XmlPullParser parser = null;
1862 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001863 final File[] baseDirs = {
1864 Environment.getRootDirectory(),
1865 Environment.getVendorDirectory()
1866 };
1867 for (File baseDir: baseDirs) {
1868 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
1869 FileReader confreader = null;
1870 try {
1871 confreader = new FileReader(confFile);
1872 parser = Xml.newPullParser();
1873 parser.setInput(confreader);
1874 XmlUtils.beginDocument(parser, "devices");
Jeff Brown4532e612012-04-05 14:27:12 -07001875
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001876 while (true) {
1877 XmlUtils.nextElement(parser);
1878 if (!"device".equals(parser.getName())) {
1879 break;
1880 }
1881 String name = parser.getAttributeValue(null, "name");
1882 if (name != null) {
1883 names.add(name);
1884 }
Jeff Brown4532e612012-04-05 14:27:12 -07001885 }
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001886 } catch (FileNotFoundException e) {
1887 // It's ok if the file does not exist.
1888 } catch (Exception e) {
1889 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1890 } finally {
1891 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001892 }
Jeff Brown4532e612012-04-05 14:27:12 -07001893 }
1894
1895 return names.toArray(new String[names.size()]);
1896 }
1897
1898 // Native callback.
1899 private int getKeyRepeatTimeout() {
1900 return ViewConfiguration.getKeyRepeatTimeout();
1901 }
1902
1903 // Native callback.
1904 private int getKeyRepeatDelay() {
1905 return ViewConfiguration.getKeyRepeatDelay();
1906 }
1907
1908 // Native callback.
1909 private int getHoverTapTimeout() {
1910 return ViewConfiguration.getHoverTapTimeout();
1911 }
1912
1913 // Native callback.
1914 private int getHoverTapSlop() {
1915 return ViewConfiguration.getHoverTapSlop();
1916 }
1917
1918 // Native callback.
1919 private int getDoubleTapTimeout() {
1920 return ViewConfiguration.getDoubleTapTimeout();
1921 }
1922
1923 // Native callback.
1924 private int getLongPressTimeout() {
1925 return ViewConfiguration.getLongPressTimeout();
1926 }
1927
1928 // Native callback.
1929 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001930 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001931 }
1932
1933 // Native callback.
1934 private PointerIcon getPointerIcon() {
1935 return PointerIcon.getDefaultIcon(mContext);
1936 }
1937
Jeff Brown6ec6f792012-04-17 16:52:41 -07001938 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001939 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001940 if (!mSystemReady) {
1941 return null;
1942 }
1943
RoboErikfb290df2013-12-16 11:27:55 -08001944 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001945 if (keyboardLayoutDescriptor == null) {
1946 return null;
1947 }
1948
1949 final String[] result = new String[2];
1950 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1951 @Override
Michael Wright07483422015-10-30 16:20:13 +00001952 public void visitKeyboardLayout(Resources resources,
1953 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001954 try {
Michael Wright07483422015-10-30 16:20:13 +00001955 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001956 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001957 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001958 } catch (IOException ex) {
1959 } catch (NotFoundException ex) {
1960 }
1961 }
1962 });
1963 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001964 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001965 + keyboardLayoutDescriptor + "'.");
1966 return null;
1967 }
1968 return result;
1969 }
1970
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001971 // Native callback.
1972 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001973 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1974 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1975 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001976 }
1977 return null;
1978 }
1979
Jeff Brown4532e612012-04-05 14:27:12 -07001980 /**
1981 * Callback interface implemented by the Window Manager.
1982 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001983 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001984 public void notifyConfigurationChanged();
1985
1986 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1987
Michael Wright3818c922014-09-02 13:59:07 -07001988 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
1989
Jeff Brown4532e612012-04-05 14:27:12 -07001990 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1991
1992 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001993 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001994
Jeff Brown037c33e2014-04-09 00:31:55 -07001995 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001996
Michael Wright70af00a2014-09-03 19:30:20 -07001997 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001998
1999 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2000 KeyEvent event, int policyFlags);
2001
2002 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2003 KeyEvent event, int policyFlags);
2004
2005 public int getPointerLayer();
2006 }
2007
2008 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002009 * Callback interface implemented by WiredAccessoryObserver.
2010 */
2011 public interface WiredAccessoryCallbacks {
2012 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002013 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002014 }
2015
2016 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002017 * Private handler for the input manager.
2018 */
2019 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002020 public InputManagerHandler(Looper looper) {
2021 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002022 }
2023
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002024 @Override
2025 public void handleMessage(Message msg) {
2026 switch (msg.what) {
2027 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002028 deliverInputDevicesChanged((InputDevice[])msg.obj);
2029 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002030 case MSG_SWITCH_KEYBOARD_LAYOUT:
2031 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002032 break;
2033 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2034 reloadKeyboardLayouts();
2035 break;
2036 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2037 updateKeyboardLayouts();
2038 break;
2039 case MSG_RELOAD_DEVICE_ALIASES:
2040 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002041 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002042 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002043 SomeArgs args = (SomeArgs) msg.obj;
2044 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2045 boolean inTabletMode = (boolean) args.arg1;
2046 deliverTabletModeChanged(whenNanos, inTabletMode);
2047 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002048 }
2049 }
2050 }
2051
2052 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002053 * Hosting interface for input filters to call back into the input manager.
2054 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002055 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002056 private boolean mDisconnected;
2057
2058 public void disconnectLocked() {
2059 mDisconnected = true;
2060 }
2061
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002062 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002063 public void sendInputEvent(InputEvent event, int policyFlags) {
2064 if (event == null) {
2065 throw new IllegalArgumentException("event must not be null");
2066 }
2067
2068 synchronized (mInputFilterLock) {
2069 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002070 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002071 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002072 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2073 }
2074 }
2075 }
2076 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002077
2078 private static final class KeyboardLayoutDescriptor {
2079 public String packageName;
2080 public String receiverName;
2081 public String keyboardLayoutName;
2082
2083 public static String format(String packageName,
2084 String receiverName, String keyboardName) {
2085 return packageName + "/" + receiverName + "/" + keyboardName;
2086 }
2087
2088 public static KeyboardLayoutDescriptor parse(String descriptor) {
2089 int pos = descriptor.indexOf('/');
2090 if (pos < 0 || pos + 1 == descriptor.length()) {
2091 return null;
2092 }
2093 int pos2 = descriptor.indexOf('/', pos + 1);
2094 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2095 return null;
2096 }
2097
2098 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2099 result.packageName = descriptor.substring(0, pos);
2100 result.receiverName = descriptor.substring(pos + 1, pos2);
2101 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2102 return result;
2103 }
2104 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002105
Jeff Brown6ec6f792012-04-17 16:52:41 -07002106 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002107 void visitKeyboardLayout(Resources resources,
2108 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002109 }
2110
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002111 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2112 private final int mPid;
2113 private final IInputDevicesChangedListener mListener;
2114
2115 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2116 mPid = pid;
2117 mListener = listener;
2118 }
2119
2120 @Override
2121 public void binderDied() {
2122 if (DEBUG) {
2123 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2124 }
2125 onInputDevicesChangedListenerDied(mPid);
2126 }
2127
2128 public void notifyInputDevicesChanged(int[] info) {
2129 try {
2130 mListener.onInputDevicesChanged(info);
2131 } catch (RemoteException ex) {
2132 Slog.w(TAG, "Failed to notify process "
2133 + mPid + " that input devices changed, assuming it died.", ex);
2134 binderDied();
2135 }
2136 }
2137 }
Jeff Browna47425a2012-04-13 04:09:27 -07002138
Michael Wright39e5e942015-08-19 22:52:47 +01002139 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2140 private final int mPid;
2141 private final ITabletModeChangedListener mListener;
2142
2143 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2144 mPid = pid;
2145 mListener = listener;
2146 }
2147
2148 @Override
2149 public void binderDied() {
2150 if (DEBUG) {
2151 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2152 }
2153 onTabletModeChangedListenerDied(mPid);
2154 }
2155
2156 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2157 try {
2158 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2159 } catch (RemoteException ex) {
2160 Slog.w(TAG, "Failed to notify process " + mPid +
2161 " that tablet mode changed, assuming it died.", ex);
2162 binderDied();
2163 }
2164 }
2165 }
2166
Jeff Browna47425a2012-04-13 04:09:27 -07002167 private final class VibratorToken implements DeathRecipient {
2168 public final int mDeviceId;
2169 public final IBinder mToken;
2170 public final int mTokenValue;
2171
2172 public boolean mVibrating;
2173
2174 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2175 mDeviceId = deviceId;
2176 mToken = token;
2177 mTokenValue = tokenValue;
2178 }
2179
2180 @Override
2181 public void binderDied() {
2182 if (DEBUG) {
2183 Slog.d(TAG, "Vibrator token died.");
2184 }
2185 onVibratorTokenDied(this);
2186 }
2187 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002188
2189 private final class LocalService extends InputManagerInternal {
2190 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002191 public void setDisplayViewports(List<DisplayViewport> viewports) {
2192 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002193 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002194
2195 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002196 public boolean injectInputEvent(InputEvent event, int mode) {
2197 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002198 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002199
2200 @Override
2201 public void setInteractive(boolean interactive) {
2202 nativeSetInteractive(mPtr, interactive);
2203 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002204
2205 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002206 public void toggleCapsLock(int deviceId) {
2207 nativeToggleCapsLock(mPtr, deviceId);
2208 }
Adrian Roos99182342016-06-15 15:30:46 -07002209
2210 @Override
2211 public void setPulseGestureEnabled(boolean enabled) {
2212 if (mDoubleTouchGestureEnableFile != null) {
2213 FileWriter writer = null;
2214 try {
2215 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2216 writer.write(enabled ? "1" : "0");
2217 } catch (IOException e) {
2218 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2219 } finally {
2220 IoUtils.closeQuietly(writer);
2221 }
2222 }
2223 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002224 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002225}