blob: 5e7ea05f799cd8c4c34c95dbffaca1151e449654 [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;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070067import android.util.Pair;
Jeff Brown46b9ac02010-04-22 18:58:52 -070068import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.util.SparseArray;
Andrii Kulianed76e742017-06-26 14:57:02 -070070import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080073import android.view.IWindow;
Robert Carr788f5742018-07-30 17:46:45 -070074import android.view.InputApplicationHandle;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070075import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070076import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070077import android.view.InputEvent;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -070078import android.view.InputWindowHandle;
Jeff Brown1f245102010-11-18 20:53:46 -080079import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070080import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070081import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080082import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080083import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070084
Arthur Hung39134b22018-08-14 11:58:28 +080085import com.android.internal.R;
86import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
87import com.android.internal.notification.SystemNotificationChannels;
88import com.android.internal.os.SomeArgs;
89import com.android.internal.util.DumpUtils;
90import com.android.internal.util.Preconditions;
91import com.android.internal.util.XmlUtils;
92import com.android.server.DisplayThread;
93import com.android.server.LocalServices;
94import com.android.server.Watchdog;
95import com.android.server.policy.WindowManagerPolicy;
96
97import libcore.io.IoUtils;
98import libcore.io.Streams;
99
Jeff Brown46b9ac02010-04-22 18:58:52 -0700100import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700101import java.io.FileDescriptor;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700102import java.io.FileInputStream;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700103import java.io.FileNotFoundException;
Adrian Roos99182342016-06-15 15:30:46 -0700104import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.IOException;
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700106import java.io.InputStream;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700107import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700108import java.io.PrintWriter;
109import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000110import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700111import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700112import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100113import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000114import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000115import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700116
Jeff Brown46b9ac02010-04-22 18:58:52 -0700117/*
118 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700119 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700120public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800121 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700122 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700123 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700124
Jeff Brown4532e612012-04-05 14:27:12 -0700125 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -0700126 private static final String PORT_ASSOCIATIONS_PATH = "etc/input-port-associations.xml";
Jeff Brown4532e612012-04-05 14:27:12 -0700127
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700128 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700129 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
130 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
131 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
132 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100133 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700134
Jeff Brown4532e612012-04-05 14:27:12 -0700135 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000136 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700137
Jeff Brown46b9ac02010-04-22 18:58:52 -0700138 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700139 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700140
Andrii Kulianfd8666d2018-10-05 16:58:39 -0700141 // Context cache used for loading pointer resources.
142 private Context mDisplayContext;
143
Adrian Roos99182342016-06-15 15:30:46 -0700144 private final File mDoubleTouchGestureEnableFile;
145
Jeff Browna9d131c2012-09-20 16:48:17 -0700146 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700147 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700148 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700149 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700150
Michael Wright39e5e942015-08-19 22:52:47 +0100151 private final Object mTabletModeLock = new Object();
152 // List of currently registered tablet mode changed listeners by process id
153 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
154 new SparseArray<>(); // guarded by mTabletModeLock
155 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
156 new ArrayList<>();
157
Jeff Browna3bc5652012-04-17 11:42:25 -0700158 // Persistent data store. Must be locked each time during use.
159 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700160
161 // List of currently registered input devices changed listeners by process id.
162 private Object mInputDevicesLock = new Object();
163 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
164 private InputDevice[] mInputDevices = new InputDevice[0];
165 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
166 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
167 private final ArrayList<InputDevicesChangedListenerRecord>
168 mTempInputDevicesChangedListenersToNotify =
169 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700170 private final ArrayList<InputDevice>
171 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
172 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800173 private PendingIntent mKeyboardLayoutIntent;
174 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700175
Jeff Browna47425a2012-04-13 04:09:27 -0700176 // State for vibrator tokens.
177 private Object mVibratorLock = new Object();
178 private HashMap<IBinder, VibratorToken> mVibratorTokens =
179 new HashMap<IBinder, VibratorToken>();
180 private int mNextVibratorTokenValue;
181
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700182 // State for the currently installed input filter.
183 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700184 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700185 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700186
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800187 private IWindow mFocusedWindow;
188 private boolean mFocusedWindowHasCapture;
189
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000190 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700191 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000192 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100193 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700194 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700195
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700197 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700199 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000200 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700201 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000202 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700203 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000204 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Robert Carre0a353c2018-08-02 16:38:04 -0700205 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000206 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
207 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800208 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700209 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
210 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800211 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800212 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
213 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000214 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
215 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
216 private static native void nativeSetFocusedApplication(long ptr,
Tiger Huang1e5b10a2018-07-30 20:19:51 +0800217 int displayId, InputApplicationHandle application);
218 private static native void nativeSetFocusedDisplay(long ptr, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeSetPointerSpeed(long ptr, int speed);
220 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700221 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800222 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000223 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700224 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000225 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
226 private static native void nativeReloadKeyboardLayouts(long ptr);
227 private static native void nativeReloadDeviceAliases(long ptr);
228 private static native String nativeDump(long ptr);
229 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700230 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
231 private static native void nativeEnableInputDevice(long ptr, int deviceId);
232 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100233 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800234 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700235 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800236 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Arthur Hung82bbfc32018-11-29 20:24:51 +0800237 private static native boolean nativeCanDispatchToDisplay(long ptr, int deviceId, int displayId);
Jeff Brown4532e612012-04-05 14:27:12 -0700238
Jeff Brownac143512012-04-05 18:57:33 -0700239 // Input event injection constants defined in InputDispatcher.h.
240 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
241 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
242 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
243 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
244
245 // Maximum number of milliseconds to wait for input event injection.
246 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
247
Jeff Brown6d0fec22010-07-23 21:28:06 -0700248 // Key states (may be returned by queries about the current state of a
249 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700250
Jeff Brown6d0fec22010-07-23 21:28:06 -0700251 /** The key state is unknown or the requested key itself is not supported. */
252 public static final int KEY_STATE_UNKNOWN = -1;
253
254 /** The key is up. /*/
255 public static final int KEY_STATE_UP = 0;
256
257 /** The key is down. */
258 public static final int KEY_STATE_DOWN = 1;
259
260 /** The key is down but is a virtual key press that is being emulated by the system. */
261 public static final int KEY_STATE_VIRTUAL = 2;
262
Jeff Brownc458ce92012-04-30 14:58:40 -0700263 /** Scan code: Mouse / trackball button. */
264 public static final int BTN_MOUSE = 0x110;
265
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700266 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700267 /** Switch code: Lid switch. When set, lid is shut. */
268 public static final int SW_LID = 0x00;
269
Michael Wright39e5e942015-08-19 22:52:47 +0100270 /** Switch code: Tablet mode switch.
271 * When set, the device is in tablet mode (i.e. no keyboard is connected).
272 */
273 public static final int SW_TABLET_MODE = 0x01;
274
Jeff Brownc458ce92012-04-30 14:58:40 -0700275 /** Switch code: Keypad slide. When set, keyboard is exposed. */
276 public static final int SW_KEYPAD_SLIDE = 0x0a;
277
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700278 /** Switch code: Headphone. When set, headphone is inserted. */
279 public static final int SW_HEADPHONE_INSERT = 0x02;
280
281 /** Switch code: Microphone. When set, microphone is inserted. */
282 public static final int SW_MICROPHONE_INSERT = 0x04;
283
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500284 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
285 public static final int SW_LINEOUT_INSERT = 0x06;
286
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700287 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
288 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
289
Michael Wright3818c922014-09-02 13:59:07 -0700290 /** Switch code: Camera lens cover. When set the lens is covered. */
291 public static final int SW_CAMERA_LENS_COVER = 0x09;
292
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700293 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100294 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700295 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
296 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
297 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500298 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700299 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
300 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500301 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700302 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700303
304 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
305 final boolean mUseDevInputEventForAudioJack;
306
Jeff Brown4ccb8232014-01-16 22:16:42 -0800307 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700308 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800309 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800310
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700311 mUseDevInputEventForAudioJack =
312 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
313 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
314 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700315 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800316
Adrian Roos99182342016-06-15 15:30:46 -0700317 String doubleTouchGestureEnablePath = context.getResources().getString(
318 R.string.config_doubleTouchGestureEnableFile);
319 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
320 new File(doubleTouchGestureEnablePath);
321
Jeff Brown4ccb8232014-01-16 22:16:42 -0800322 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700323 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700324
Jeff Browna9d131c2012-09-20 16:48:17 -0700325 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
326 mWindowManagerCallbacks = callbacks;
327 }
328
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700329 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
330 mWiredAccessoryCallbacks = callbacks;
331 }
332
Jeff Brown46b9ac02010-04-22 18:58:52 -0700333 public void start() {
334 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700335 nativeStart(mPtr);
336
337 // Add ourself to the Watchdog monitors.
338 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700339
340 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700341 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800342 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700343
Jeff Brownd4935962012-09-25 13:27:20 -0700344 mContext.registerReceiver(new BroadcastReceiver() {
345 @Override
346 public void onReceive(Context context, Intent intent) {
347 updatePointerSpeedFromSettings();
348 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800349 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700350 }
351 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
352
Jeff Brown1a84fd12011-06-02 01:26:32 -0700353 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700354 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800355 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700356 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700357
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100358 // TODO(BT) Pass in parameter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700359 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700360 if (DEBUG) {
361 Slog.d(TAG, "System ready.");
362 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700363 mNotificationManager = (NotificationManager)mContext.getSystemService(
364 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700365 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700366
367 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
368 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
369 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800370 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700371 filter.addDataScheme("package");
372 mContext.registerReceiver(new BroadcastReceiver() {
373 @Override
374 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700375 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700376 }
377 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700378
379 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
380 mContext.registerReceiver(new BroadcastReceiver() {
381 @Override
382 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700383 reloadDeviceAliases();
384 }
385 }, filter, null, mHandler);
386
Jeff Browncf39bdf2012-05-18 14:41:19 -0700387 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
388 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700389
390 if (mWiredAccessoryCallbacks != null) {
391 mWiredAccessoryCallbacks.systemReady();
392 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700393 }
394
395 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700396 if (DEBUG) {
397 Slog.d(TAG, "Reloading keyboard layouts.");
398 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700399 nativeReloadKeyboardLayouts(mPtr);
400 }
401
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700402 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700403 if (DEBUG) {
404 Slog.d(TAG, "Reloading device names.");
405 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700406 nativeReloadDeviceAliases(mPtr);
407 }
408
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100409 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
410 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700411 }
Jeff Brownac143512012-04-05 18:57:33 -0700412
Jeff Brown6d0fec22010-07-23 21:28:06 -0700413 /**
414 * Gets the current state of a key or button by key code.
415 * @param deviceId The input device id, or -1 to consult all devices.
416 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
417 * consider all input sources. An input device is consulted if at least one of its
418 * non-class input source bits matches the specified source mask.
419 * @param keyCode The key code to check.
420 * @return The key state.
421 */
422 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700423 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700424 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700425
Jeff Brown6d0fec22010-07-23 21:28:06 -0700426 /**
427 * Gets the current state of a key or button by scan code.
428 * @param deviceId The input device id, or -1 to consult all devices.
429 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
430 * consider all input sources. An input device is consulted if at least one of its
431 * non-class input source bits matches the specified source mask.
432 * @param scanCode The scan code to check.
433 * @return The key state.
434 */
435 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700436 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700437 }
RoboErikfb290df2013-12-16 11:27:55 -0800438
Jeff Brown6d0fec22010-07-23 21:28:06 -0700439 /**
440 * Gets the current state of a switch by switch code.
441 * @param deviceId The input device id, or -1 to consult all devices.
442 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
443 * consider all input sources. An input device is consulted if at least one of its
444 * non-class input source bits matches the specified source mask.
445 * @param switchCode The switch code to check.
446 * @return The switch state.
447 */
448 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700449 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700450 }
451
Jeff Brown6d0fec22010-07-23 21:28:06 -0700452 /**
453 * Determines whether the specified key codes are supported by a particular device.
454 * @param deviceId The input device id, or -1 to consult all devices.
455 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
456 * consider all input sources. An input device is consulted if at least one of its
457 * non-class input source bits matches the specified source mask.
458 * @param keyCodes The array of key codes to check.
459 * @param keyExists An array at least as large as keyCodes whose entries will be set
460 * to true or false based on the presence or absence of support for the corresponding
461 * key codes.
462 * @return True if the lookup was successful, false otherwise.
463 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700464 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700465 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700466 if (keyCodes == null) {
467 throw new IllegalArgumentException("keyCodes must not be null.");
468 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700469 if (keyExists == null || keyExists.length < keyCodes.length) {
470 throw new IllegalArgumentException("keyExists must not be null and must be at "
471 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700472 }
RoboErikfb290df2013-12-16 11:27:55 -0800473
Jeff Brown4532e612012-04-05 14:27:12 -0700474 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700475 }
RoboErikfb290df2013-12-16 11:27:55 -0800476
Jeff Browna41ca772010-08-11 14:46:32 -0700477 /**
478 * Creates an input channel that will receive all input from the input dispatcher.
479 * @param inputChannelName The input channel name.
Arthur Hungbe5ce212018-09-13 18:41:56 +0800480 * @param displayId Target display id.
Jeff Browna41ca772010-08-11 14:46:32 -0700481 * @return The input channel.
482 */
Arthur Hungbe5ce212018-09-13 18:41:56 +0800483 public InputChannel monitorInput(String inputChannelName, int displayId) {
Jeff Browna41ca772010-08-11 14:46:32 -0700484 if (inputChannelName == null) {
485 throw new IllegalArgumentException("inputChannelName must not be null.");
486 }
RoboErikfb290df2013-12-16 11:27:55 -0800487
Arthur Hungbe5ce212018-09-13 18:41:56 +0800488 if (displayId < Display.DEFAULT_DISPLAY) {
489 throw new IllegalArgumentException("displayId must >= 0.");
490 }
491
Jeff Browna41ca772010-08-11 14:46:32 -0700492 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Robert Carre0a353c2018-08-02 16:38:04 -0700493 nativeRegisterInputChannel(mPtr, inputChannels[0], displayId);
Jeff Browna41ca772010-08-11 14:46:32 -0700494 inputChannels[0].dispose(); // don't need to retain the Java object reference
495 return inputChannels[1];
496 }
497
498 /**
499 * Registers an input channel so that it can be used as an input event target.
500 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800501 * @param inputWindowHandle The handle of the input window associated with the
502 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700503 */
Robert Carre0a353c2018-08-02 16:38:04 -0700504 public void registerInputChannel(InputChannel inputChannel, IBinder token) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700505 if (inputChannel == null) {
506 throw new IllegalArgumentException("inputChannel must not be null.");
507 }
RoboErikfb290df2013-12-16 11:27:55 -0800508
Robert Carre0a353c2018-08-02 16:38:04 -0700509 if (token == null) {
510 token = new Binder();
511 }
512 inputChannel.setToken(token);
513
514 nativeRegisterInputChannel(mPtr, inputChannel, Display.INVALID_DISPLAY);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700515 }
RoboErikfb290df2013-12-16 11:27:55 -0800516
Jeff Browna41ca772010-08-11 14:46:32 -0700517 /**
518 * Unregisters an input channel.
519 * @param inputChannel The input channel to unregister.
520 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700521 public void unregisterInputChannel(InputChannel inputChannel) {
522 if (inputChannel == null) {
523 throw new IllegalArgumentException("inputChannel must not be null.");
524 }
RoboErikfb290df2013-12-16 11:27:55 -0800525
Jeff Brown4532e612012-04-05 14:27:12 -0700526 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700527 }
Jeff Brown0029c662011-03-30 02:25:18 -0700528
529 /**
530 * Sets an input filter that will receive all input events before they are dispatched.
531 * The input filter may then reinterpret input events or inject new ones.
532 *
533 * To ensure consistency, the input dispatcher automatically drops all events
534 * in progress whenever an input filter is installed or uninstalled. After an input
535 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
536 * Any events it attempts to send after it has been uninstalled will be dropped.
537 *
538 * @param filter The input filter, or null to remove the current filter.
539 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700540 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700541 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700542 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700543 if (oldFilter == filter) {
544 return; // nothing to do
545 }
546
547 if (oldFilter != null) {
548 mInputFilter = null;
549 mInputFilterHost.disconnectLocked();
550 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700551 try {
552 oldFilter.uninstall();
553 } catch (RemoteException re) {
554 /* ignore */
555 }
Jeff Brown0029c662011-03-30 02:25:18 -0700556 }
557
558 if (filter != null) {
559 mInputFilter = filter;
560 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700561 try {
562 filter.install(mInputFilterHost);
563 } catch (RemoteException re) {
564 /* ignore */
565 }
Jeff Brown0029c662011-03-30 02:25:18 -0700566 }
567
Jeff Brown4532e612012-04-05 14:27:12 -0700568 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700569 }
570 }
571
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700572 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700573 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800574 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800575 }
576
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800577 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700578 if (event == null) {
579 throw new IllegalArgumentException("event must not be null");
580 }
Jeff Brownac143512012-04-05 18:57:33 -0700581 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
582 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
583 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
584 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700585 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700586
Jeff Brownac143512012-04-05 18:57:33 -0700587 final int pid = Binder.getCallingPid();
588 final int uid = Binder.getCallingUid();
589 final long ident = Binder.clearCallingIdentity();
590 final int result;
591 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800592 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700593 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
594 } finally {
595 Binder.restoreCallingIdentity(ident);
596 }
597 switch (result) {
598 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
599 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
600 throw new SecurityException(
601 "Injecting to another application requires INJECT_EVENTS permission");
602 case INPUT_EVENT_INJECTION_SUCCEEDED:
603 return true;
604 case INPUT_EVENT_INJECTION_TIMED_OUT:
605 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
606 return false;
607 case INPUT_EVENT_INJECTION_FAILED:
608 default:
609 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
610 return false;
611 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700612 }
Jeff Brown0029c662011-03-30 02:25:18 -0700613
Jeff Brown8d608662010-08-30 03:02:23 -0700614 /**
615 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700616 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700617 * @return The input device or null if not found.
618 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700619 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700620 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700621 synchronized (mInputDevicesLock) {
622 final int count = mInputDevices.length;
623 for (int i = 0; i < count; i++) {
624 final InputDevice inputDevice = mInputDevices[i];
625 if (inputDevice.getId() == deviceId) {
626 return inputDevice;
627 }
628 }
629 }
630 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700631 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700632
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700633 // Binder call
634 @Override
635 public boolean isInputDeviceEnabled(int deviceId) {
636 return nativeIsInputDeviceEnabled(mPtr, deviceId);
637 }
638
639 // Binder call
640 @Override
641 public void enableInputDevice(int deviceId) {
642 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
643 "enableInputDevice()")) {
644 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
645 }
646 nativeEnableInputDevice(mPtr, deviceId);
647 }
648
649 // Binder call
650 @Override
651 public void disableInputDevice(int deviceId) {
652 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
653 "disableInputDevice()")) {
654 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
655 }
656 nativeDisableInputDevice(mPtr, deviceId);
657 }
658
Jeff Brown8d608662010-08-30 03:02:23 -0700659 /**
660 * Gets the ids of all input devices in the system.
661 * @return The input device ids.
662 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700663 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700664 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700665 synchronized (mInputDevicesLock) {
666 final int count = mInputDevices.length;
667 int[] ids = new int[count];
668 for (int i = 0; i < count; i++) {
669 ids[i] = mInputDevices[i].getId();
670 }
671 return ids;
672 }
673 }
674
Jeff Browndaa37532012-05-01 15:54:03 -0700675 /**
676 * Gets all input devices in the system.
677 * @return The array of input devices.
678 */
679 public InputDevice[] getInputDevices() {
680 synchronized (mInputDevicesLock) {
681 return mInputDevices;
682 }
683 }
684
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700685 @Override // Binder call
686 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
687 if (listener == null) {
688 throw new IllegalArgumentException("listener must not be null");
689 }
690
691 synchronized (mInputDevicesLock) {
692 int callingPid = Binder.getCallingPid();
693 if (mInputDevicesChangedListeners.get(callingPid) != null) {
694 throw new SecurityException("The calling process has already "
695 + "registered an InputDevicesChangedListener.");
696 }
697
698 InputDevicesChangedListenerRecord record =
699 new InputDevicesChangedListenerRecord(callingPid, listener);
700 try {
701 IBinder binder = listener.asBinder();
702 binder.linkToDeath(record, 0);
703 } catch (RemoteException ex) {
704 // give up
705 throw new RuntimeException(ex);
706 }
707
708 mInputDevicesChangedListeners.put(callingPid, record);
709 }
710 }
711
712 private void onInputDevicesChangedListenerDied(int pid) {
713 synchronized (mInputDevicesLock) {
714 mInputDevicesChangedListeners.remove(pid);
715 }
716 }
717
718 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700719 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
720 // Scan for changes.
721 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700722 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700723 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700724 final int numListeners;
725 final int[] deviceIdAndGeneration;
726 synchronized (mInputDevicesLock) {
727 if (!mInputDevicesChangedPending) {
728 return;
729 }
730 mInputDevicesChangedPending = false;
731
732 numListeners = mInputDevicesChangedListeners.size();
733 for (int i = 0; i < numListeners; i++) {
734 mTempInputDevicesChangedListenersToNotify.add(
735 mInputDevicesChangedListeners.valueAt(i));
736 }
737
738 final int numDevices = mInputDevices.length;
739 deviceIdAndGeneration = new int[numDevices * 2];
740 for (int i = 0; i < numDevices; i++) {
741 final InputDevice inputDevice = mInputDevices[i];
742 deviceIdAndGeneration[i * 2] = inputDevice.getId();
743 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700744
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700745 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700746 if (!containsInputDeviceWithDescriptor(oldInputDevices,
747 inputDevice.getDescriptor())) {
748 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
749 } else {
750 mTempFullKeyboards.add(inputDevice);
751 }
752 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700753 }
754 }
755
Jeff Browncf39bdf2012-05-18 14:41:19 -0700756 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700757 for (int i = 0; i < numListeners; i++) {
758 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
759 deviceIdAndGeneration);
760 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700761 mTempInputDevicesChangedListenersToNotify.clear();
762
763 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000764 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
765 final int numFullKeyboards = mTempFullKeyboards.size();
766 synchronized (mDataStore) {
767 for (int i = 0; i < numFullKeyboards; i++) {
768 final InputDevice inputDevice = mTempFullKeyboards.get(i);
769 String layout =
770 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
771 if (layout == null) {
772 layout = getDefaultKeyboardLayout(inputDevice);
773 if (layout != null) {
774 setCurrentKeyboardLayoutForInputDevice(
775 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700776 }
777 }
Michael Wright07483422015-10-30 16:20:13 +0000778 if (layout == null) {
779 keyboardsMissingLayout.add(inputDevice);
780 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700781 }
Michael Wright07483422015-10-30 16:20:13 +0000782 }
783
784 if (mNotificationManager != null) {
785 if (!keyboardsMissingLayout.isEmpty()) {
786 if (keyboardsMissingLayout.size() > 1) {
787 // We have more than one keyboard missing a layout, so drop the
788 // user at the generic input methods page so they can pick which
789 // one to set.
790 showMissingKeyboardLayoutNotification(null);
791 } else {
792 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700793 }
794 } else if (mKeyboardLayoutNotificationShown) {
795 hideMissingKeyboardLayoutNotification();
796 }
797 }
798 mTempFullKeyboards.clear();
799 }
800
Michael Wright07483422015-10-30 16:20:13 +0000801 private String getDefaultKeyboardLayout(final InputDevice d) {
802 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
803 // If our locale doesn't have a language for some reason, then we don't really have a
804 // reasonable default.
805 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
806 return null;
807 }
808 final List<KeyboardLayout> layouts = new ArrayList<>();
809 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
810 @Override
811 public void visitKeyboardLayout(Resources resources,
812 int keyboardLayoutResId, KeyboardLayout layout) {
813 // Only select a default when we know the layout is appropriate. For now, this
814 // means its a custom layout for a specific keyboard.
815 if (layout.getVendorId() != d.getVendorId()
816 || layout.getProductId() != d.getProductId()) {
817 return;
818 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800819 final LocaleList locales = layout.getLocales();
820 final int numLocales = locales.size();
821 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
822 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000823 layouts.add(layout);
824 break;
825 }
826 }
827 }
828 });
829
830 if (layouts.isEmpty()) {
831 return null;
832 }
833
834 // First sort so that ones with higher priority are listed at the top
835 Collections.sort(layouts);
836 // Next we want to try to find an exact match of language, country and variant.
837 final int N = layouts.size();
838 for (int i = 0; i < N; i++) {
839 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800840 final LocaleList locales = layout.getLocales();
841 final int numLocales = locales.size();
842 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
843 final Locale locale = locales.get(localeIndex);
844 if (locale.getCountry().equals(systemLocale.getCountry())
845 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000846 return layout.getDescriptor();
847 }
848 }
849 }
850 // Then try an exact match of language and country
851 for (int i = 0; i < N; i++) {
852 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800853 final LocaleList locales = layout.getLocales();
854 final int numLocales = locales.size();
855 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
856 final Locale locale = locales.get(localeIndex);
857 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000858 return layout.getDescriptor();
859 }
860 }
861 }
862
863 // Give up and just use the highest priority layout with matching language
864 return layouts.get(0).getDescriptor();
865 }
866
867 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
868 // Different languages are never compatible
869 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
870 return false;
871 }
872 // If both the system and the keyboard layout have a country specifier, they must be equal.
873 if (!TextUtils.isEmpty(systemLocale.getCountry())
874 && !TextUtils.isEmpty(keyboardLocale.getCountry())
875 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
876 return false;
877 }
878 return true;
879 }
880
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800881 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700882 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
883 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800884 if (inputDeviceDescriptor == null) {
885 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
886 }
887
888 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700889 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800890 }
891 }
892
893 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700894 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800895 TouchCalibration calibration) {
896 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
897 "setTouchCalibrationForInputDevice()")) {
898 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
899 }
900 if (inputDeviceDescriptor == null) {
901 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
902 }
903 if (calibration == null) {
904 throw new IllegalArgumentException("calibration must not be null");
905 }
Jason Gerecked5220742014-03-10 09:47:59 -0700906 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
907 throw new IllegalArgumentException("surfaceRotation value out of bounds");
908 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800909
910 synchronized (mDataStore) {
911 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700912 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
913 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800914 nativeReloadCalibration(mPtr);
915 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800916 } finally {
917 mDataStore.saveIfNeeded();
918 }
919 }
920 }
921
Michael Wright39e5e942015-08-19 22:52:47 +0100922 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100923 public int isInTabletMode() {
924 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
925 "isInTabletMode()")) {
926 throw new SecurityException("Requires TABLET_MODE permission");
927 }
928 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
929 }
930
931 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100932 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100933 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100934 "registerTabletModeChangedListener()")) {
935 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
936 }
937 if (listener == null) {
938 throw new IllegalArgumentException("listener must not be null");
939 }
940
941 synchronized (mTabletModeLock) {
942 final int callingPid = Binder.getCallingPid();
943 if (mTabletModeChangedListeners.get(callingPid) != null) {
944 throw new IllegalStateException("The calling process has already registered "
945 + "a TabletModeChangedListener.");
946 }
947 TabletModeChangedListenerRecord record =
948 new TabletModeChangedListenerRecord(callingPid, listener);
949 try {
950 IBinder binder = listener.asBinder();
951 binder.linkToDeath(record, 0);
952 } catch (RemoteException ex) {
953 throw new RuntimeException(ex);
954 }
955 mTabletModeChangedListeners.put(callingPid, record);
956 }
957 }
958
959 private void onTabletModeChangedListenerDied(int pid) {
960 synchronized (mTabletModeLock) {
961 mTabletModeChangedListeners.remove(pid);
962 }
963 }
964
965 // Must be called on handler
966 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
967 mTempTabletModeChangedListenersToNotify.clear();
968 final int numListeners;
969 synchronized (mTabletModeLock) {
970 numListeners = mTabletModeChangedListeners.size();
971 for (int i = 0; i < numListeners; i++) {
972 mTempTabletModeChangedListenersToNotify.add(
973 mTabletModeChangedListeners.valueAt(i));
974 }
975 }
976 for (int i = 0; i < numListeners; i++) {
977 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
978 whenNanos, inTabletMode);
979 }
980 }
981
Jeff Browncf39bdf2012-05-18 14:41:19 -0700982 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700983 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700984 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700985 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700986 if (device != null) {
987 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700988 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700989 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
990 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
991 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
992 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
993 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700994
995 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500996 Notification notification =
997 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
998 .setContentTitle(r.getString(
999 R.string.select_keyboard_layout_notification_title))
1000 .setContentText(r.getString(
1001 R.string.select_keyboard_layout_notification_message))
1002 .setContentIntent(keyboardLayoutIntent)
1003 .setSmallIcon(R.drawable.ic_settings_language)
1004 .setColor(mContext.getColor(
1005 com.android.internal.R.color.system_notification_accent_color))
1006 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001007 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001008 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001009 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001010 mKeyboardLayoutNotificationShown = true;
1011 }
1012 }
1013
1014 // Must be called on handler.
1015 private void hideMissingKeyboardLayoutNotification() {
1016 if (mKeyboardLayoutNotificationShown) {
1017 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001018 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001019 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001020 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001021 }
1022 }
1023
1024 // Must be called on handler.
1025 private void updateKeyboardLayouts() {
1026 // Scan all input devices state for keyboard layouts that have been uninstalled.
1027 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1028 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1029 @Override
Michael Wright07483422015-10-30 16:20:13 +00001030 public void visitKeyboardLayout(Resources resources,
1031 int keyboardLayoutResId, KeyboardLayout layout) {
1032 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001033 }
1034 });
1035 synchronized (mDataStore) {
1036 try {
1037 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1038 } finally {
1039 mDataStore.saveIfNeeded();
1040 }
1041 }
1042
1043 // Reload keyboard layouts.
1044 reloadKeyboardLayouts();
1045 }
1046
Jeff Browncf39bdf2012-05-18 14:41:19 -07001047 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1048 String descriptor) {
1049 final int numDevices = inputDevices.length;
1050 for (int i = 0; i < numDevices; i++) {
1051 final InputDevice inputDevice = inputDevices[i];
1052 if (inputDevice.getDescriptor().equals(descriptor)) {
1053 return true;
1054 }
1055 }
1056 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001057 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001058
1059 @Override // Binder call
1060 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001061 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1062 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1063 @Override
Michael Wright07483422015-10-30 16:20:13 +00001064 public void visitKeyboardLayout(Resources resources,
1065 int keyboardLayoutResId, KeyboardLayout layout) {
1066 list.add(layout);
1067 }
1068 });
1069 return list.toArray(new KeyboardLayout[list.size()]);
1070 }
1071
Michael Wrightb0e804a2016-01-04 16:48:53 -05001072 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001073 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1074 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001075 final String[] enabledLayoutDescriptors =
1076 getEnabledKeyboardLayoutsForInputDevice(identifier);
1077 final ArrayList<KeyboardLayout> enabledLayouts =
1078 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1079 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001080 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1081 boolean mHasSeenDeviceSpecificLayout;
1082
1083 @Override
1084 public void visitKeyboardLayout(Resources resources,
1085 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001086 // First check if it's enabled. If the keyboard layout is enabled then we always
1087 // want to return it as a possible layout for the device.
1088 for (String s : enabledLayoutDescriptors) {
1089 if (s != null && s.equals(layout.getDescriptor())) {
1090 enabledLayouts.add(layout);
1091 return;
1092 }
1093 }
1094 // Next find any potential layouts that aren't yet enabled for the device. For
1095 // devices that have special layouts we assume there's a reason that the generic
1096 // layouts don't work for them so we don't want to return them since it's likely
1097 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001098 if (layout.getVendorId() == identifier.getVendorId()
1099 && layout.getProductId() == identifier.getProductId()) {
1100 if (!mHasSeenDeviceSpecificLayout) {
1101 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001102 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001103 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001104 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001105 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1106 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001107 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001108 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001109 }
1110 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001111 final int enabledLayoutSize = enabledLayouts.size();
1112 final int potentialLayoutSize = potentialLayouts.size();
1113 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1114 enabledLayouts.toArray(layouts);
1115 for (int i = 0; i < potentialLayoutSize; i++) {
1116 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1117 }
1118 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001119 }
1120
1121 @Override // Binder call
1122 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1123 if (keyboardLayoutDescriptor == null) {
1124 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1125 }
1126
Jeff Brown6ec6f792012-04-17 16:52:41 -07001127 final KeyboardLayout[] result = new KeyboardLayout[1];
1128 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1129 @Override
Michael Wright07483422015-10-30 16:20:13 +00001130 public void visitKeyboardLayout(Resources resources,
1131 int keyboardLayoutResId, KeyboardLayout layout) {
1132 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001133 }
1134 });
1135 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001136 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001137 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001138 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001139 return result[0];
1140 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001141
Jeff Brown6ec6f792012-04-17 16:52:41 -07001142 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001143 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001144 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1145 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001146 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1147 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001148 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1149 final int priority = resolveInfo.priority;
1150 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001151 }
1152 }
1153
Jeff Brown6ec6f792012-04-17 16:52:41 -07001154 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1155 KeyboardLayoutVisitor visitor) {
1156 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1157 if (d != null) {
1158 final PackageManager pm = mContext.getPackageManager();
1159 try {
1160 ActivityInfo receiver = pm.getReceiverInfo(
1161 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001162 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001163 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1164 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001165 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001166 } catch (NameNotFoundException ex) {
1167 }
1168 }
1169 }
1170
1171 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001172 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001173 Bundle metaData = receiver.metaData;
1174 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001175 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001176 }
1177
1178 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1179 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001180 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001181 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001182 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001183 }
1184
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001185 CharSequence receiverLabel = receiver.loadLabel(pm);
1186 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001187 int priority;
1188 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1189 priority = requestedPriority;
1190 } else {
1191 priority = 0;
1192 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001193
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001194 try {
1195 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1196 XmlResourceParser parser = resources.getXml(configResId);
1197 try {
1198 XmlUtils.beginDocument(parser, "keyboard-layouts");
1199
1200 for (;;) {
1201 XmlUtils.nextElement(parser);
1202 String element = parser.getName();
1203 if (element == null) {
1204 break;
1205 }
1206 if (element.equals("keyboard-layout")) {
1207 TypedArray a = resources.obtainAttributes(
1208 parser, com.android.internal.R.styleable.KeyboardLayout);
1209 try {
1210 String name = a.getString(
1211 com.android.internal.R.styleable.KeyboardLayout_name);
1212 String label = a.getString(
1213 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001214 int keyboardLayoutResId = a.getResourceId(
1215 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1216 0);
Michael Wright07483422015-10-30 16:20:13 +00001217 String languageTags = a.getString(
1218 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001219 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001220 int vid = a.getInt(
1221 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1222 int pid = a.getInt(
1223 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1224
Jeff Brown2f095762012-05-10 21:29:33 -07001225 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001226 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001227 + "attributes in keyboard layout "
1228 + "resource from receiver "
1229 + receiver.packageName + "/" + receiver.name);
1230 } else {
1231 String descriptor = KeyboardLayoutDescriptor.format(
1232 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001233 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001234 KeyboardLayout layout = new KeyboardLayout(
1235 descriptor, label, collection, priority,
1236 locales, vid, pid);
1237 visitor.visitKeyboardLayout(
1238 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001239 }
1240 }
1241 } finally {
1242 a.recycle();
1243 }
1244 } else {
Michael Wright07483422015-10-30 16:20:13 +00001245 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001246 + "' in keyboard layout resource from receiver "
1247 + receiver.packageName + "/" + receiver.name);
1248 }
1249 }
1250 } finally {
1251 parser.close();
1252 }
1253 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001254 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001255 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001256 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001257 }
1258
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001259 @NonNull
1260 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001261 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001262 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001263 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001264 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001265 }
1266
RoboErikfb290df2013-12-16 11:27:55 -08001267 /**
1268 * Builds a layout descriptor for the vendor/product. This returns the
1269 * descriptor for ids that aren't useful (such as the default 0, 0).
1270 */
1271 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1272 if (identifier == null || identifier.getDescriptor() == null) {
1273 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001274 }
1275
RoboErikfb290df2013-12-16 11:27:55 -08001276 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1277 return identifier.getDescriptor();
1278 }
1279 StringBuilder bob = new StringBuilder();
1280 bob.append("vendor:").append(identifier.getVendorId());
1281 bob.append(",product:").append(identifier.getProductId());
1282 return bob.toString();
1283 }
1284
1285 @Override // Binder call
1286 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1287
1288 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001289 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001290 String layout = null;
1291 // try loading it using the layout descriptor if we have it
1292 layout = mDataStore.getCurrentKeyboardLayout(key);
1293 if (layout == null && !key.equals(identifier.getDescriptor())) {
1294 // if it doesn't exist fall back to the device descriptor
1295 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1296 }
1297 if (DEBUG) {
1298 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1299 + layout);
1300 }
1301 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001302 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001303 }
1304
1305 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001306 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001307 String keyboardLayoutDescriptor) {
1308 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001309 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001310 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1311 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001312 if (keyboardLayoutDescriptor == null) {
1313 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1314 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001315
RoboErikfb290df2013-12-16 11:27:55 -08001316 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001317 synchronized (mDataStore) {
1318 try {
RoboErikfb290df2013-12-16 11:27:55 -08001319 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1320 if (DEBUG) {
1321 Slog.d(TAG, "Saved keyboard layout using " + key);
1322 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001323 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1324 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001325 } finally {
1326 mDataStore.saveIfNeeded();
1327 }
1328 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001329 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001330
Jeff Browncf39bdf2012-05-18 14:41:19 -07001331 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001332 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001333 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001334 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001335 String[] layouts = mDataStore.getKeyboardLayouts(key);
1336 if ((layouts == null || layouts.length == 0)
1337 && !key.equals(identifier.getDescriptor())) {
1338 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1339 }
1340 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001341 }
1342 }
1343
1344 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001345 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001346 String keyboardLayoutDescriptor) {
1347 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1348 "addKeyboardLayoutForInputDevice()")) {
1349 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1350 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001351 if (keyboardLayoutDescriptor == null) {
1352 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1353 }
1354
RoboErikfb290df2013-12-16 11:27:55 -08001355 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001356 synchronized (mDataStore) {
1357 try {
RoboErikfb290df2013-12-16 11:27:55 -08001358 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1359 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1360 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1361 }
1362 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001363 && !Objects.equals(oldLayout,
1364 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001365 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1366 }
1367 } finally {
1368 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001369 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001370 }
1371 }
1372
1373 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001374 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001375 String keyboardLayoutDescriptor) {
1376 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1377 "removeKeyboardLayoutForInputDevice()")) {
1378 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1379 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001380 if (keyboardLayoutDescriptor == null) {
1381 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1382 }
1383
RoboErikfb290df2013-12-16 11:27:55 -08001384 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001385 synchronized (mDataStore) {
1386 try {
RoboErikfb290df2013-12-16 11:27:55 -08001387 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1388 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1389 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1390 }
1391 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1392 if (!key.equals(identifier.getDescriptor())) {
1393 // We need to remove from both places to ensure it is gone
1394 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1395 keyboardLayoutDescriptor);
1396 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001397 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001398 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001399 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1400 }
1401 } finally {
1402 mDataStore.saveIfNeeded();
1403 }
1404 }
1405 }
1406
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001407 public void switchKeyboardLayout(int deviceId, int direction) {
1408 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001409 }
1410
1411 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001412 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1413 final InputDevice device = getInputDevice(deviceId);
1414 if (device != null) {
1415 final boolean changed;
1416 final String keyboardLayoutDescriptor;
1417
1418 String key = getLayoutDescriptor(device.getIdentifier());
1419 synchronized (mDataStore) {
1420 try {
1421 changed = mDataStore.switchKeyboardLayout(key, direction);
1422 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1423 key);
1424 } finally {
1425 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001426 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001427 }
1428
1429 if (changed) {
1430 if (mSwitchedKeyboardLayoutToast != null) {
1431 mSwitchedKeyboardLayoutToast.cancel();
1432 mSwitchedKeyboardLayoutToast = null;
1433 }
1434 if (keyboardLayoutDescriptor != null) {
1435 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1436 if (keyboardLayout != null) {
1437 mSwitchedKeyboardLayoutToast = Toast.makeText(
1438 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1439 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001440 }
1441 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001442
1443 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001444 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001445 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001446 }
1447
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001448 public void setFocusedApplication(int displayId, InputApplicationHandle application) {
1449 nativeSetFocusedApplication(mPtr, displayId, application);
1450 }
1451
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001452 public void setFocusedDisplay(int displayId) {
1453 nativeSetFocusedDisplay(mPtr, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001454 }
RoboErikfb290df2013-12-16 11:27:55 -08001455
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001456 @Override
1457 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1458 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1459 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1460 + windowToken);
1461 return;
1462 }
1463 if (mFocusedWindowHasCapture == enabled) {
1464 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1465 return;
1466 }
1467 setPointerCapture(enabled);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001468 }
1469
1470 private void setPointerCapture(boolean enabled) {
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001471 if (mFocusedWindowHasCapture != enabled) {
1472 mFocusedWindowHasCapture = enabled;
1473 try {
1474 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1475 } catch (RemoteException ex) {
1476 /* ignore */
1477 }
1478 nativeSetPointerCapture(mPtr, enabled);
1479 }
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001480 }
1481
Jeff Brown349703e2010-06-22 01:27:15 -07001482 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001483 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001484 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001485
1486 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001487 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001488 }
1489
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001490 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001491 public void tryPointerSpeed(int speed) {
1492 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1493 "tryPointerSpeed()")) {
1494 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1495 }
1496
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001497 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1498 throw new IllegalArgumentException("speed out of range");
1499 }
1500
Jeff Brownac143512012-04-05 18:57:33 -07001501 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001502 }
1503
1504 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001505 int speed = getPointerSpeedSetting();
1506 setPointerSpeedUnchecked(speed);
1507 }
1508
1509 private void setPointerSpeedUnchecked(int speed) {
1510 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1511 InputManager.MAX_POINTER_SPEED);
1512 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001513 }
1514
1515 private void registerPointerSpeedSettingObserver() {
1516 mContext.getContentResolver().registerContentObserver(
1517 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001518 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001519 @Override
1520 public void onChange(boolean selfChange) {
1521 updatePointerSpeedFromSettings();
1522 }
Jeff Brownd4935962012-09-25 13:27:20 -07001523 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001524 }
1525
Jeff Brownac143512012-04-05 18:57:33 -07001526 private int getPointerSpeedSetting() {
1527 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001528 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001529 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1530 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001531 } catch (SettingNotFoundException snfe) {
1532 }
1533 return speed;
1534 }
1535
Jeff Browndaf4a122011-08-26 17:14:14 -07001536 public void updateShowTouchesFromSettings() {
1537 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001538 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001539 }
1540
1541 private void registerShowTouchesSettingObserver() {
1542 mContext.getContentResolver().registerContentObserver(
1543 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001544 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001545 @Override
1546 public void onChange(boolean selfChange) {
1547 updateShowTouchesFromSettings();
1548 }
Jeff Brownd4935962012-09-25 13:27:20 -07001549 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001550 }
1551
Jun Mukaie4e75da2015-12-15 16:19:20 -08001552 public void updateAccessibilityLargePointerFromSettings() {
1553 final int accessibilityConfig = Settings.Secure.getIntForUser(
1554 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1555 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001556 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001557 nativeReloadPointerIcons(mPtr);
1558 }
1559
Jun Mukai19a56012015-11-24 11:25:52 -08001560 private void registerAccessibilityLargePointerSettingObserver() {
1561 mContext.getContentResolver().registerContentObserver(
1562 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1563 new ContentObserver(mHandler) {
1564 @Override
1565 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001566 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001567 }
1568 }, UserHandle.USER_ALL);
1569 }
1570
Jeff Browndaf4a122011-08-26 17:14:14 -07001571 private int getShowTouchesSetting(int defaultValue) {
1572 int result = defaultValue;
1573 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001574 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1575 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001576 } catch (SettingNotFoundException snfe) {
1577 }
1578 return result;
1579 }
1580
Jeff Browna47425a2012-04-13 04:09:27 -07001581 // Binder call
1582 @Override
1583 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1584 if (repeat >= pattern.length) {
1585 throw new ArrayIndexOutOfBoundsException();
1586 }
1587
1588 VibratorToken v;
1589 synchronized (mVibratorLock) {
1590 v = mVibratorTokens.get(token);
1591 if (v == null) {
1592 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1593 try {
1594 token.linkToDeath(v, 0);
1595 } catch (RemoteException ex) {
1596 // give up
1597 throw new RuntimeException(ex);
1598 }
1599 mVibratorTokens.put(token, v);
1600 }
1601 }
1602
1603 synchronized (v) {
1604 v.mVibrating = true;
1605 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1606 }
1607 }
1608
1609 // Binder call
1610 @Override
1611 public void cancelVibrate(int deviceId, IBinder token) {
1612 VibratorToken v;
1613 synchronized (mVibratorLock) {
1614 v = mVibratorTokens.get(token);
1615 if (v == null || v.mDeviceId != deviceId) {
1616 return; // nothing to cancel
1617 }
1618 }
1619
1620 cancelVibrateIfNeeded(v);
1621 }
1622
1623 void onVibratorTokenDied(VibratorToken v) {
1624 synchronized (mVibratorLock) {
1625 mVibratorTokens.remove(v.mToken);
1626 }
1627
1628 cancelVibrateIfNeeded(v);
1629 }
1630
1631 private void cancelVibrateIfNeeded(VibratorToken v) {
1632 synchronized (v) {
1633 if (v.mVibrating) {
1634 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1635 v.mVibrating = false;
1636 }
1637 }
1638 }
1639
Jun Mukai19a56012015-11-24 11:25:52 -08001640 // Binder call
1641 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001642 public void setPointerIconType(int iconId) {
1643 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001644 }
Jun Mukai1db53972015-09-11 18:08:31 -07001645
Jun Mukaid4eaef72015-10-30 15:54:33 -07001646 // Binder call
1647 @Override
1648 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001649 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001650 nativeSetCustomPointerIcon(mPtr, icon);
1651 }
1652
Jeff Brown4532e612012-04-05 14:27:12 -07001653 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001654 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001655 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001656
1657 pw.println("INPUT MANAGER (dumpsys input)\n");
1658 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001659 if (dumpStr != null) {
1660 pw.println(dumpStr);
1661 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001662 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001663
Jeff Brownac143512012-04-05 18:57:33 -07001664 private boolean checkCallingPermission(String permission, String func) {
1665 // Quick check: if the calling permission is me, it's all okay.
1666 if (Binder.getCallingPid() == Process.myPid()) {
1667 return true;
1668 }
1669
1670 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1671 return true;
1672 }
1673 String msg = "Permission Denial: " + func + " from pid="
1674 + Binder.getCallingPid()
1675 + ", uid=" + Binder.getCallingUid()
1676 + " requires " + permission;
1677 Slog.w(TAG, msg);
1678 return false;
1679 }
1680
Jeff Brown4532e612012-04-05 14:27:12 -07001681 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001682 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001683 public void monitor() {
1684 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001685 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001686 }
1687
Andrii Kulianed76e742017-06-26 14:57:02 -07001688 // Binder call
1689 @Override
1690 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1691 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1692 "createInputForwarder()")) {
1693 throw new SecurityException("Requires INJECT_EVENTS permission");
1694 }
1695 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1696 final Display display = displayManager.getDisplay(displayId);
1697 if (display == null) {
1698 throw new IllegalArgumentException(
1699 "Can't create input forwarder for non-existent displayId: " + displayId);
1700 }
1701 final int callingUid = Binder.getCallingUid();
1702 final int displayOwnerUid = display.getOwnerUid();
1703 if (callingUid != displayOwnerUid) {
1704 throw new SecurityException(
1705 "Only owner of the display can forward input events to it.");
1706 }
1707
1708 return new InputForwarder(displayId);
1709 }
1710
Jeff Brown4532e612012-04-05 14:27:12 -07001711 // Native callback.
1712 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001713 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001714 }
1715
1716 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001717 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1718 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001719 if (!mInputDevicesChangedPending) {
1720 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001721 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1722 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001723 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001724
1725 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001726 }
1727 }
1728
1729 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001730 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1731 if (DEBUG) {
1732 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1733 + ", mask=" + Integer.toHexString(switchMask));
1734 }
1735
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001736 if ((switchMask & SW_LID_BIT) != 0) {
1737 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001738 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001739 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001740
Michael Wright3818c922014-09-02 13:59:07 -07001741 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001742 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001743 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1744 }
1745
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001746 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1747 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1748 switchMask);
1749 }
Michael Wright39e5e942015-08-19 22:52:47 +01001750
Michael Wright9209c9c2015-09-03 17:57:01 +01001751 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001752 SomeArgs args = SomeArgs.obtain();
1753 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1754 args.argi2 = (int) (whenNanos >> 32);
1755 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1756 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1757 args).sendToTarget();
1758 }
Jeff Brown4532e612012-04-05 14:27:12 -07001759 }
1760
1761 // Native callback.
Robert Carre0a353c2018-08-02 16:38:04 -07001762 private void notifyInputChannelBroken(IBinder token) {
1763 mWindowManagerCallbacks.notifyInputChannelBroken(token);
Jeff Brown4532e612012-04-05 14:27:12 -07001764 }
1765
Robert Carrbd26e652018-08-21 15:46:28 -07001766 // Native callback
chaviw91089862019-01-09 15:49:11 -08001767 private void notifyFocusChanged(IBinder oldToken, IBinder newToken) {
Riddle Hsu63e40532019-01-14 21:30:07 +08001768 if (mFocusedWindow != null) {
1769 if (mFocusedWindow.asBinder() == newToken) {
1770 Slog.w(TAG, "notifyFocusChanged called with unchanged mFocusedWindow="
1771 + mFocusedWindow);
1772 return;
1773 }
1774 setPointerCapture(false);
Robert Carrbd26e652018-08-21 15:46:28 -07001775 }
chaviw78658892019-01-09 10:23:41 -08001776
chaviw91089862019-01-09 15:49:11 -08001777 mFocusedWindow = IWindow.Stub.asInterface(newToken);
Robert Carrbd26e652018-08-21 15:46:28 -07001778 }
1779
Jeff Brown4532e612012-04-05 14:27:12 -07001780 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001781 private long notifyANR(IBinder token, String reason) {
Jeff Brownbd181bb2013-09-10 16:44:24 -07001782 return mWindowManagerCallbacks.notifyANR(
Robert Carr679ccb02018-08-08 15:32:35 -07001783 token, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001784 }
1785
1786 // Native callback.
1787 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1788 synchronized (mInputFilterLock) {
1789 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001790 try {
1791 mInputFilter.filterInputEvent(event, policyFlags);
1792 } catch (RemoteException e) {
1793 /* ignore */
1794 }
Jeff Brown4532e612012-04-05 14:27:12 -07001795 return false;
1796 }
1797 }
1798 event.recycle();
1799 return true;
1800 }
1801
1802 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001803 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1804 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001805 }
1806
1807 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001808 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1809 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001810 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001811 }
1812
1813 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001814 private long interceptKeyBeforeDispatching(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001815 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001816 }
1817
1818 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001819 private KeyEvent dispatchUnhandledKey(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001820 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001821 }
1822
1823 // Native callback.
1824 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1825 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1826 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1827 }
1828
1829 // Native callback.
1830 private int getVirtualKeyQuietTimeMillis() {
1831 return mContext.getResources().getInteger(
1832 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1833 }
1834
1835 // Native callback.
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001836 private static String[] getExcludedDeviceNames() {
1837 List<String> names = new ArrayList<>();
Jeff Brown4532e612012-04-05 14:27:12 -07001838 // Read partner-provided list of excluded input devices
Jeff Brown4532e612012-04-05 14:27:12 -07001839 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001840 final File[] baseDirs = {
1841 Environment.getRootDirectory(),
1842 Environment.getVendorDirectory()
1843 };
1844 for (File baseDir: baseDirs) {
1845 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001846 try {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001847 InputStream stream = new FileInputStream(confFile);
1848 names.addAll(ConfigurationProcessor.processExcludedDeviceNames(stream));
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001849 } catch (FileNotFoundException e) {
1850 // It's ok if the file does not exist.
1851 } catch (Exception e) {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001852 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
Jeff Brown4532e612012-04-05 14:27:12 -07001853 }
Jeff Brown4532e612012-04-05 14:27:12 -07001854 }
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001855 return names.toArray(new String[0]);
1856 }
Jeff Brown4532e612012-04-05 14:27:12 -07001857
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001858 /**
1859 * Flatten a list of pairs into a list, with value positioned directly next to the key
1860 * @return Flattened list
1861 */
1862 private static <T> List<T> flatten(@NonNull List<Pair<T, T>> pairs) {
1863 List<T> list = new ArrayList<>(pairs.size() * 2);
1864 for (Pair<T, T> pair : pairs) {
1865 list.add(pair.first);
1866 list.add(pair.second);
1867 }
1868 return list;
1869 }
1870
1871 /**
1872 * Ports are highly platform-specific, so only allow these to be specified in the vendor
1873 * directory.
1874 */
1875 // Native callback
1876 private static String[] getInputPortAssociations() {
1877 File baseDir = Environment.getVendorDirectory();
1878 File confFile = new File(baseDir, PORT_ASSOCIATIONS_PATH);
1879
1880 try {
1881 InputStream stream = new FileInputStream(confFile);
1882 List<Pair<String, String>> associations =
1883 ConfigurationProcessor.processInputPortAssociations(stream);
1884 List<String> associationList = flatten(associations);
1885 return associationList.toArray(new String[0]);
1886 } catch (FileNotFoundException e) {
1887 // Most of the time, file will not exist, which is expected.
1888 } catch (Exception e) {
1889 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
1890 }
1891 return new String[0];
Jeff Brown4532e612012-04-05 14:27:12 -07001892 }
1893
Arthur Hung82bbfc32018-11-29 20:24:51 +08001894 /**
1895 * Gets if an input device could dispatch to the given display".
1896 * @param deviceId The input device id.
1897 * @param displayId The specific display id.
1898 * @return True if the device could dispatch to the given display, false otherwise.
1899 */
1900 public boolean canDispatchToDisplay(int deviceId, int displayId) {
1901 return nativeCanDispatchToDisplay(mPtr, deviceId, displayId);
1902 }
1903
Jeff Brown4532e612012-04-05 14:27:12 -07001904 // Native callback.
1905 private int getKeyRepeatTimeout() {
1906 return ViewConfiguration.getKeyRepeatTimeout();
1907 }
1908
1909 // Native callback.
1910 private int getKeyRepeatDelay() {
1911 return ViewConfiguration.getKeyRepeatDelay();
1912 }
1913
1914 // Native callback.
1915 private int getHoverTapTimeout() {
1916 return ViewConfiguration.getHoverTapTimeout();
1917 }
1918
1919 // Native callback.
1920 private int getHoverTapSlop() {
1921 return ViewConfiguration.getHoverTapSlop();
1922 }
1923
1924 // Native callback.
1925 private int getDoubleTapTimeout() {
1926 return ViewConfiguration.getDoubleTapTimeout();
1927 }
1928
1929 // Native callback.
1930 private int getLongPressTimeout() {
1931 return ViewConfiguration.getLongPressTimeout();
1932 }
1933
1934 // Native callback.
1935 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001936 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001937 }
1938
1939 // Native callback.
Andrii Kulianfd8666d2018-10-05 16:58:39 -07001940 private PointerIcon getPointerIcon(int displayId) {
1941 return PointerIcon.getDefaultIcon(getContextForDisplay(displayId));
1942 }
1943
1944 private Context getContextForDisplay(int displayId) {
1945 if (mDisplayContext != null && mDisplayContext.getDisplay().getDisplayId() == displayId) {
1946 return mDisplayContext;
1947 }
1948
1949 if (mContext.getDisplay().getDisplayId() == displayId) {
1950 mDisplayContext = mContext;
1951 return mDisplayContext;
1952 }
1953
1954 // Create and cache context for non-default display.
1955 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1956 final Display display = displayManager.getDisplay(displayId);
1957 mDisplayContext = mContext.createDisplayContext(display);
1958 return mDisplayContext;
Jeff Brown4532e612012-04-05 14:27:12 -07001959 }
1960
Jeff Brown6ec6f792012-04-17 16:52:41 -07001961 // Native callback.
Arthur Hungb9b32002018-12-18 17:39:43 +08001962 private int getPointerDisplayId() {
1963 return mWindowManagerCallbacks.getPointerDisplayId();
1964 }
1965
1966 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001967 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001968 if (!mSystemReady) {
1969 return null;
1970 }
1971
RoboErikfb290df2013-12-16 11:27:55 -08001972 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001973 if (keyboardLayoutDescriptor == null) {
1974 return null;
1975 }
1976
1977 final String[] result = new String[2];
1978 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1979 @Override
Michael Wright07483422015-10-30 16:20:13 +00001980 public void visitKeyboardLayout(Resources resources,
1981 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001982 try {
Michael Wright07483422015-10-30 16:20:13 +00001983 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001984 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001985 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001986 } catch (IOException ex) {
1987 } catch (NotFoundException ex) {
1988 }
1989 }
1990 });
1991 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001992 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001993 + keyboardLayoutDescriptor + "'.");
1994 return null;
1995 }
1996 return result;
1997 }
1998
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001999 // Native callback.
2000 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07002001 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2002 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2003 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002004 }
2005 return null;
2006 }
2007
Jeff Brown4532e612012-04-05 14:27:12 -07002008 /**
2009 * Callback interface implemented by the Window Manager.
2010 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002011 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002012 public void notifyConfigurationChanged();
2013
2014 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2015
Michael Wright3818c922014-09-02 13:59:07 -07002016 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2017
Robert Carre0a353c2018-08-02 16:38:04 -07002018 public void notifyInputChannelBroken(IBinder token);
Jeff Brown4532e612012-04-05 14:27:12 -07002019
Robert Carr679ccb02018-08-08 15:32:35 -07002020 public long notifyANR(IBinder token, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002021
Jeff Brown037c33e2014-04-09 00:31:55 -07002022 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002023
Michael Wright70af00a2014-09-03 19:30:20 -07002024 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002025
Robert Carre0a353c2018-08-02 16:38:04 -07002026 public long interceptKeyBeforeDispatching(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07002027 KeyEvent event, int policyFlags);
2028
Robert Carre0a353c2018-08-02 16:38:04 -07002029 public KeyEvent dispatchUnhandledKey(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07002030 KeyEvent event, int policyFlags);
2031
2032 public int getPointerLayer();
Arthur Hungb9b32002018-12-18 17:39:43 +08002033
2034 public int getPointerDisplayId();
Jeff Brown4532e612012-04-05 14:27:12 -07002035 }
2036
2037 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002038 * Callback interface implemented by WiredAccessoryObserver.
2039 */
2040 public interface WiredAccessoryCallbacks {
2041 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002042 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002043 }
2044
2045 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002046 * Private handler for the input manager.
2047 */
2048 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002049 public InputManagerHandler(Looper looper) {
2050 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002051 }
2052
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002053 @Override
2054 public void handleMessage(Message msg) {
2055 switch (msg.what) {
2056 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002057 deliverInputDevicesChanged((InputDevice[])msg.obj);
2058 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002059 case MSG_SWITCH_KEYBOARD_LAYOUT:
2060 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002061 break;
2062 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2063 reloadKeyboardLayouts();
2064 break;
2065 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2066 updateKeyboardLayouts();
2067 break;
2068 case MSG_RELOAD_DEVICE_ALIASES:
2069 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002070 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002071 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002072 SomeArgs args = (SomeArgs) msg.obj;
2073 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2074 boolean inTabletMode = (boolean) args.arg1;
2075 deliverTabletModeChanged(whenNanos, inTabletMode);
2076 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002077 }
2078 }
2079 }
2080
2081 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002082 * Hosting interface for input filters to call back into the input manager.
2083 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002084 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002085 private boolean mDisconnected;
2086
2087 public void disconnectLocked() {
2088 mDisconnected = true;
2089 }
2090
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002091 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002092 public void sendInputEvent(InputEvent event, int policyFlags) {
2093 if (event == null) {
2094 throw new IllegalArgumentException("event must not be null");
2095 }
2096
2097 synchronized (mInputFilterLock) {
2098 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002099 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002100 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002101 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2102 }
2103 }
2104 }
2105 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002106
2107 private static final class KeyboardLayoutDescriptor {
2108 public String packageName;
2109 public String receiverName;
2110 public String keyboardLayoutName;
2111
2112 public static String format(String packageName,
2113 String receiverName, String keyboardName) {
2114 return packageName + "/" + receiverName + "/" + keyboardName;
2115 }
2116
2117 public static KeyboardLayoutDescriptor parse(String descriptor) {
2118 int pos = descriptor.indexOf('/');
2119 if (pos < 0 || pos + 1 == descriptor.length()) {
2120 return null;
2121 }
2122 int pos2 = descriptor.indexOf('/', pos + 1);
2123 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2124 return null;
2125 }
2126
2127 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2128 result.packageName = descriptor.substring(0, pos);
2129 result.receiverName = descriptor.substring(pos + 1, pos2);
2130 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2131 return result;
2132 }
2133 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002134
Jeff Brown6ec6f792012-04-17 16:52:41 -07002135 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002136 void visitKeyboardLayout(Resources resources,
2137 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002138 }
2139
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002140 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2141 private final int mPid;
2142 private final IInputDevicesChangedListener mListener;
2143
2144 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2145 mPid = pid;
2146 mListener = listener;
2147 }
2148
2149 @Override
2150 public void binderDied() {
2151 if (DEBUG) {
2152 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2153 }
2154 onInputDevicesChangedListenerDied(mPid);
2155 }
2156
2157 public void notifyInputDevicesChanged(int[] info) {
2158 try {
2159 mListener.onInputDevicesChanged(info);
2160 } catch (RemoteException ex) {
2161 Slog.w(TAG, "Failed to notify process "
2162 + mPid + " that input devices changed, assuming it died.", ex);
2163 binderDied();
2164 }
2165 }
2166 }
Jeff Browna47425a2012-04-13 04:09:27 -07002167
Michael Wright39e5e942015-08-19 22:52:47 +01002168 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2169 private final int mPid;
2170 private final ITabletModeChangedListener mListener;
2171
2172 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2173 mPid = pid;
2174 mListener = listener;
2175 }
2176
2177 @Override
2178 public void binderDied() {
2179 if (DEBUG) {
2180 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2181 }
2182 onTabletModeChangedListenerDied(mPid);
2183 }
2184
2185 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2186 try {
2187 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2188 } catch (RemoteException ex) {
2189 Slog.w(TAG, "Failed to notify process " + mPid +
2190 " that tablet mode changed, assuming it died.", ex);
2191 binderDied();
2192 }
2193 }
2194 }
2195
Jeff Browna47425a2012-04-13 04:09:27 -07002196 private final class VibratorToken implements DeathRecipient {
2197 public final int mDeviceId;
2198 public final IBinder mToken;
2199 public final int mTokenValue;
2200
2201 public boolean mVibrating;
2202
2203 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2204 mDeviceId = deviceId;
2205 mToken = token;
2206 mTokenValue = tokenValue;
2207 }
2208
2209 @Override
2210 public void binderDied() {
2211 if (DEBUG) {
2212 Slog.d(TAG, "Vibrator token died.");
2213 }
2214 onVibratorTokenDied(this);
2215 }
2216 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002217
2218 private final class LocalService extends InputManagerInternal {
2219 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002220 public void setDisplayViewports(List<DisplayViewport> viewports) {
2221 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002222 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002223
2224 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002225 public boolean injectInputEvent(InputEvent event, int mode) {
2226 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002227 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002228
2229 @Override
2230 public void setInteractive(boolean interactive) {
2231 nativeSetInteractive(mPtr, interactive);
2232 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002233
2234 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002235 public void toggleCapsLock(int deviceId) {
2236 nativeToggleCapsLock(mPtr, deviceId);
2237 }
Adrian Roos99182342016-06-15 15:30:46 -07002238
2239 @Override
2240 public void setPulseGestureEnabled(boolean enabled) {
2241 if (mDoubleTouchGestureEnableFile != null) {
2242 FileWriter writer = null;
2243 try {
2244 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2245 writer.write(enabled ? "1" : "0");
2246 } catch (IOException e) {
2247 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2248 } finally {
2249 IoUtils.closeQuietly(writer);
2250 }
2251 }
2252 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002253 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002254}