blob: df28f30d9127bc38702402ab6f57406dd4434860 [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
Adrian Roos99182342016-06-15 15:30:46 -0700141 private final File mDoubleTouchGestureEnableFile;
142
Jeff Browna9d131c2012-09-20 16:48:17 -0700143 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700144 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700145 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700146 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700147
Michael Wright39e5e942015-08-19 22:52:47 +0100148 private final Object mTabletModeLock = new Object();
149 // List of currently registered tablet mode changed listeners by process id
150 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
151 new SparseArray<>(); // guarded by mTabletModeLock
152 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
153 new ArrayList<>();
154
Jeff Browna3bc5652012-04-17 11:42:25 -0700155 // Persistent data store. Must be locked each time during use.
156 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700157
158 // List of currently registered input devices changed listeners by process id.
159 private Object mInputDevicesLock = new Object();
160 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
161 private InputDevice[] mInputDevices = new InputDevice[0];
162 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
163 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
164 private final ArrayList<InputDevicesChangedListenerRecord>
165 mTempInputDevicesChangedListenersToNotify =
166 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700167 private final ArrayList<InputDevice>
168 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
169 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800170 private PendingIntent mKeyboardLayoutIntent;
171 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700172
Jeff Browna47425a2012-04-13 04:09:27 -0700173 // State for vibrator tokens.
174 private Object mVibratorLock = new Object();
175 private HashMap<IBinder, VibratorToken> mVibratorTokens =
176 new HashMap<IBinder, VibratorToken>();
177 private int mNextVibratorTokenValue;
178
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700179 // State for the currently installed input filter.
180 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700181 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700182 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700183
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800184 private IWindow mFocusedWindow;
185 private boolean mFocusedWindowHasCapture;
186
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700188 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000189 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100190 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700191 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700192
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000193 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700194 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000195 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700196 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000197 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700198 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000199 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700200 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000201 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Robert Carre0a353c2018-08-02 16:38:04 -0700202 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000203 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
204 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800205 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700206 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
207 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800208 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800209 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
210 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000211 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
212 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
213 private static native void nativeSetFocusedApplication(long ptr,
Tiger Huang1e5b10a2018-07-30 20:19:51 +0800214 int displayId, InputApplicationHandle application);
215 private static native void nativeSetFocusedDisplay(long ptr, int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000216 private static native void nativeSetPointerSpeed(long ptr, int speed);
217 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700218 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800219 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000220 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700221 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000222 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
223 private static native void nativeReloadKeyboardLayouts(long ptr);
224 private static native void nativeReloadDeviceAliases(long ptr);
225 private static native String nativeDump(long ptr);
226 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700227 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
228 private static native void nativeEnableInputDevice(long ptr, int deviceId);
229 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100230 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800231 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700232 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800233 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700234
Jeff Brownac143512012-04-05 18:57:33 -0700235 // Input event injection constants defined in InputDispatcher.h.
236 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
237 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
238 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
239 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
240
241 // Maximum number of milliseconds to wait for input event injection.
242 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
243
Jeff Brown6d0fec22010-07-23 21:28:06 -0700244 // Key states (may be returned by queries about the current state of a
245 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700246
Jeff Brown6d0fec22010-07-23 21:28:06 -0700247 /** The key state is unknown or the requested key itself is not supported. */
248 public static final int KEY_STATE_UNKNOWN = -1;
249
250 /** The key is up. /*/
251 public static final int KEY_STATE_UP = 0;
252
253 /** The key is down. */
254 public static final int KEY_STATE_DOWN = 1;
255
256 /** The key is down but is a virtual key press that is being emulated by the system. */
257 public static final int KEY_STATE_VIRTUAL = 2;
258
Jeff Brownc458ce92012-04-30 14:58:40 -0700259 /** Scan code: Mouse / trackball button. */
260 public static final int BTN_MOUSE = 0x110;
261
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700262 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700263 /** Switch code: Lid switch. When set, lid is shut. */
264 public static final int SW_LID = 0x00;
265
Michael Wright39e5e942015-08-19 22:52:47 +0100266 /** Switch code: Tablet mode switch.
267 * When set, the device is in tablet mode (i.e. no keyboard is connected).
268 */
269 public static final int SW_TABLET_MODE = 0x01;
270
Jeff Brownc458ce92012-04-30 14:58:40 -0700271 /** Switch code: Keypad slide. When set, keyboard is exposed. */
272 public static final int SW_KEYPAD_SLIDE = 0x0a;
273
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700274 /** Switch code: Headphone. When set, headphone is inserted. */
275 public static final int SW_HEADPHONE_INSERT = 0x02;
276
277 /** Switch code: Microphone. When set, microphone is inserted. */
278 public static final int SW_MICROPHONE_INSERT = 0x04;
279
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500280 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
281 public static final int SW_LINEOUT_INSERT = 0x06;
282
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700283 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
284 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
285
Michael Wright3818c922014-09-02 13:59:07 -0700286 /** Switch code: Camera lens cover. When set the lens is covered. */
287 public static final int SW_CAMERA_LENS_COVER = 0x09;
288
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700289 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100290 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700291 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
292 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
293 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500294 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700295 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
296 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500297 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700298 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700299
300 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
301 final boolean mUseDevInputEventForAudioJack;
302
Jeff Brown4ccb8232014-01-16 22:16:42 -0800303 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700304 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800305 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800306
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700307 mUseDevInputEventForAudioJack =
308 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
309 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
310 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700311 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800312
Adrian Roos99182342016-06-15 15:30:46 -0700313 String doubleTouchGestureEnablePath = context.getResources().getString(
314 R.string.config_doubleTouchGestureEnableFile);
315 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
316 new File(doubleTouchGestureEnablePath);
317
Jeff Brown4ccb8232014-01-16 22:16:42 -0800318 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700319 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700320
Jeff Browna9d131c2012-09-20 16:48:17 -0700321 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
322 mWindowManagerCallbacks = callbacks;
323 }
324
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700325 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
326 mWiredAccessoryCallbacks = callbacks;
327 }
328
Jeff Brown46b9ac02010-04-22 18:58:52 -0700329 public void start() {
330 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700331 nativeStart(mPtr);
332
333 // Add ourself to the Watchdog monitors.
334 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700335
336 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700337 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800338 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700339
Jeff Brownd4935962012-09-25 13:27:20 -0700340 mContext.registerReceiver(new BroadcastReceiver() {
341 @Override
342 public void onReceive(Context context, Intent intent) {
343 updatePointerSpeedFromSettings();
344 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800345 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700346 }
347 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
348
Jeff Brown1a84fd12011-06-02 01:26:32 -0700349 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700350 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800351 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700352 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700353
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100354 // TODO(BT) Pass in parameter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700355 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700356 if (DEBUG) {
357 Slog.d(TAG, "System ready.");
358 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700359 mNotificationManager = (NotificationManager)mContext.getSystemService(
360 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700361 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700362
363 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
364 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
365 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800366 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700367 filter.addDataScheme("package");
368 mContext.registerReceiver(new BroadcastReceiver() {
369 @Override
370 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700371 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700372 }
373 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700374
375 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
376 mContext.registerReceiver(new BroadcastReceiver() {
377 @Override
378 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700379 reloadDeviceAliases();
380 }
381 }, filter, null, mHandler);
382
Jeff Browncf39bdf2012-05-18 14:41:19 -0700383 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
384 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700385
386 if (mWiredAccessoryCallbacks != null) {
387 mWiredAccessoryCallbacks.systemReady();
388 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700389 }
390
391 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700392 if (DEBUG) {
393 Slog.d(TAG, "Reloading keyboard layouts.");
394 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700395 nativeReloadKeyboardLayouts(mPtr);
396 }
397
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700398 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700399 if (DEBUG) {
400 Slog.d(TAG, "Reloading device names.");
401 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700402 nativeReloadDeviceAliases(mPtr);
403 }
404
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100405 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
406 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700407 }
Jeff Brownac143512012-04-05 18:57:33 -0700408
Jeff Brown6d0fec22010-07-23 21:28:06 -0700409 /**
410 * Gets the current state of a key or button by key code.
411 * @param deviceId The input device id, or -1 to consult all devices.
412 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
413 * consider all input sources. An input device is consulted if at least one of its
414 * non-class input source bits matches the specified source mask.
415 * @param keyCode The key code to check.
416 * @return The key state.
417 */
418 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700419 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700420 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700421
Jeff Brown6d0fec22010-07-23 21:28:06 -0700422 /**
423 * Gets the current state of a key or button by scan code.
424 * @param deviceId The input device id, or -1 to consult all devices.
425 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
426 * consider all input sources. An input device is consulted if at least one of its
427 * non-class input source bits matches the specified source mask.
428 * @param scanCode The scan code to check.
429 * @return The key state.
430 */
431 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700432 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700433 }
RoboErikfb290df2013-12-16 11:27:55 -0800434
Jeff Brown6d0fec22010-07-23 21:28:06 -0700435 /**
436 * Gets the current state of a switch by switch code.
437 * @param deviceId The input device id, or -1 to consult all devices.
438 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
439 * consider all input sources. An input device is consulted if at least one of its
440 * non-class input source bits matches the specified source mask.
441 * @param switchCode The switch code to check.
442 * @return The switch state.
443 */
444 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700445 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700446 }
447
Jeff Brown6d0fec22010-07-23 21:28:06 -0700448 /**
449 * Determines whether the specified key codes are supported by a particular device.
450 * @param deviceId The input device id, or -1 to consult all devices.
451 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
452 * consider all input sources. An input device is consulted if at least one of its
453 * non-class input source bits matches the specified source mask.
454 * @param keyCodes The array of key codes to check.
455 * @param keyExists An array at least as large as keyCodes whose entries will be set
456 * to true or false based on the presence or absence of support for the corresponding
457 * key codes.
458 * @return True if the lookup was successful, false otherwise.
459 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700460 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700461 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700462 if (keyCodes == null) {
463 throw new IllegalArgumentException("keyCodes must not be null.");
464 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700465 if (keyExists == null || keyExists.length < keyCodes.length) {
466 throw new IllegalArgumentException("keyExists must not be null and must be at "
467 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700468 }
RoboErikfb290df2013-12-16 11:27:55 -0800469
Jeff Brown4532e612012-04-05 14:27:12 -0700470 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700471 }
RoboErikfb290df2013-12-16 11:27:55 -0800472
Jeff Browna41ca772010-08-11 14:46:32 -0700473 /**
474 * Creates an input channel that will receive all input from the input dispatcher.
475 * @param inputChannelName The input channel name.
Arthur Hungbe5ce212018-09-13 18:41:56 +0800476 * @param displayId Target display id.
Jeff Browna41ca772010-08-11 14:46:32 -0700477 * @return The input channel.
478 */
Arthur Hungbe5ce212018-09-13 18:41:56 +0800479 public InputChannel monitorInput(String inputChannelName, int displayId) {
Jeff Browna41ca772010-08-11 14:46:32 -0700480 if (inputChannelName == null) {
481 throw new IllegalArgumentException("inputChannelName must not be null.");
482 }
RoboErikfb290df2013-12-16 11:27:55 -0800483
Arthur Hungbe5ce212018-09-13 18:41:56 +0800484 if (displayId < Display.DEFAULT_DISPLAY) {
485 throw new IllegalArgumentException("displayId must >= 0.");
486 }
487
Jeff Browna41ca772010-08-11 14:46:32 -0700488 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Robert Carre0a353c2018-08-02 16:38:04 -0700489 nativeRegisterInputChannel(mPtr, inputChannels[0], displayId);
Jeff Browna41ca772010-08-11 14:46:32 -0700490 inputChannels[0].dispose(); // don't need to retain the Java object reference
491 return inputChannels[1];
492 }
493
494 /**
495 * Registers an input channel so that it can be used as an input event target.
496 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800497 * @param inputWindowHandle The handle of the input window associated with the
498 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700499 */
Robert Carre0a353c2018-08-02 16:38:04 -0700500 public void registerInputChannel(InputChannel inputChannel, IBinder token) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700501 if (inputChannel == null) {
502 throw new IllegalArgumentException("inputChannel must not be null.");
503 }
RoboErikfb290df2013-12-16 11:27:55 -0800504
Robert Carre0a353c2018-08-02 16:38:04 -0700505 if (token == null) {
506 token = new Binder();
507 }
508 inputChannel.setToken(token);
509
510 nativeRegisterInputChannel(mPtr, inputChannel, Display.INVALID_DISPLAY);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700511 }
RoboErikfb290df2013-12-16 11:27:55 -0800512
Jeff Browna41ca772010-08-11 14:46:32 -0700513 /**
514 * Unregisters an input channel.
515 * @param inputChannel The input channel to unregister.
516 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700517 public void unregisterInputChannel(InputChannel inputChannel) {
518 if (inputChannel == null) {
519 throw new IllegalArgumentException("inputChannel must not be null.");
520 }
RoboErikfb290df2013-12-16 11:27:55 -0800521
Jeff Brown4532e612012-04-05 14:27:12 -0700522 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700523 }
Jeff Brown0029c662011-03-30 02:25:18 -0700524
525 /**
526 * Sets an input filter that will receive all input events before they are dispatched.
527 * The input filter may then reinterpret input events or inject new ones.
528 *
529 * To ensure consistency, the input dispatcher automatically drops all events
530 * in progress whenever an input filter is installed or uninstalled. After an input
531 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
532 * Any events it attempts to send after it has been uninstalled will be dropped.
533 *
534 * @param filter The input filter, or null to remove the current filter.
535 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700536 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700537 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700538 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700539 if (oldFilter == filter) {
540 return; // nothing to do
541 }
542
543 if (oldFilter != null) {
544 mInputFilter = null;
545 mInputFilterHost.disconnectLocked();
546 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700547 try {
548 oldFilter.uninstall();
549 } catch (RemoteException re) {
550 /* ignore */
551 }
Jeff Brown0029c662011-03-30 02:25:18 -0700552 }
553
554 if (filter != null) {
555 mInputFilter = filter;
556 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700557 try {
558 filter.install(mInputFilterHost);
559 } catch (RemoteException re) {
560 /* ignore */
561 }
Jeff Brown0029c662011-03-30 02:25:18 -0700562 }
563
Jeff Brown4532e612012-04-05 14:27:12 -0700564 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700565 }
566 }
567
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700568 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700569 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800570 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800571 }
572
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800573 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700574 if (event == null) {
575 throw new IllegalArgumentException("event must not be null");
576 }
Jeff Brownac143512012-04-05 18:57:33 -0700577 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
578 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
579 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
580 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700581 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700582
Jeff Brownac143512012-04-05 18:57:33 -0700583 final int pid = Binder.getCallingPid();
584 final int uid = Binder.getCallingUid();
585 final long ident = Binder.clearCallingIdentity();
586 final int result;
587 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800588 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700589 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
590 } finally {
591 Binder.restoreCallingIdentity(ident);
592 }
593 switch (result) {
594 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
595 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
596 throw new SecurityException(
597 "Injecting to another application requires INJECT_EVENTS permission");
598 case INPUT_EVENT_INJECTION_SUCCEEDED:
599 return true;
600 case INPUT_EVENT_INJECTION_TIMED_OUT:
601 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
602 return false;
603 case INPUT_EVENT_INJECTION_FAILED:
604 default:
605 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
606 return false;
607 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700608 }
Jeff Brown0029c662011-03-30 02:25:18 -0700609
Jeff Brown8d608662010-08-30 03:02:23 -0700610 /**
611 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700612 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700613 * @return The input device or null if not found.
614 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700615 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700616 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700617 synchronized (mInputDevicesLock) {
618 final int count = mInputDevices.length;
619 for (int i = 0; i < count; i++) {
620 final InputDevice inputDevice = mInputDevices[i];
621 if (inputDevice.getId() == deviceId) {
622 return inputDevice;
623 }
624 }
625 }
626 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700627 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700628
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700629 // Binder call
630 @Override
631 public boolean isInputDeviceEnabled(int deviceId) {
632 return nativeIsInputDeviceEnabled(mPtr, deviceId);
633 }
634
635 // Binder call
636 @Override
637 public void enableInputDevice(int deviceId) {
638 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
639 "enableInputDevice()")) {
640 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
641 }
642 nativeEnableInputDevice(mPtr, deviceId);
643 }
644
645 // Binder call
646 @Override
647 public void disableInputDevice(int deviceId) {
648 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
649 "disableInputDevice()")) {
650 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
651 }
652 nativeDisableInputDevice(mPtr, deviceId);
653 }
654
Jeff Brown8d608662010-08-30 03:02:23 -0700655 /**
656 * Gets the ids of all input devices in the system.
657 * @return The input device ids.
658 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700659 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700660 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700661 synchronized (mInputDevicesLock) {
662 final int count = mInputDevices.length;
663 int[] ids = new int[count];
664 for (int i = 0; i < count; i++) {
665 ids[i] = mInputDevices[i].getId();
666 }
667 return ids;
668 }
669 }
670
Jeff Browndaa37532012-05-01 15:54:03 -0700671 /**
672 * Gets all input devices in the system.
673 * @return The array of input devices.
674 */
675 public InputDevice[] getInputDevices() {
676 synchronized (mInputDevicesLock) {
677 return mInputDevices;
678 }
679 }
680
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700681 @Override // Binder call
682 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
683 if (listener == null) {
684 throw new IllegalArgumentException("listener must not be null");
685 }
686
687 synchronized (mInputDevicesLock) {
688 int callingPid = Binder.getCallingPid();
689 if (mInputDevicesChangedListeners.get(callingPid) != null) {
690 throw new SecurityException("The calling process has already "
691 + "registered an InputDevicesChangedListener.");
692 }
693
694 InputDevicesChangedListenerRecord record =
695 new InputDevicesChangedListenerRecord(callingPid, listener);
696 try {
697 IBinder binder = listener.asBinder();
698 binder.linkToDeath(record, 0);
699 } catch (RemoteException ex) {
700 // give up
701 throw new RuntimeException(ex);
702 }
703
704 mInputDevicesChangedListeners.put(callingPid, record);
705 }
706 }
707
708 private void onInputDevicesChangedListenerDied(int pid) {
709 synchronized (mInputDevicesLock) {
710 mInputDevicesChangedListeners.remove(pid);
711 }
712 }
713
714 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700715 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
716 // Scan for changes.
717 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700718 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700719 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700720 final int numListeners;
721 final int[] deviceIdAndGeneration;
722 synchronized (mInputDevicesLock) {
723 if (!mInputDevicesChangedPending) {
724 return;
725 }
726 mInputDevicesChangedPending = false;
727
728 numListeners = mInputDevicesChangedListeners.size();
729 for (int i = 0; i < numListeners; i++) {
730 mTempInputDevicesChangedListenersToNotify.add(
731 mInputDevicesChangedListeners.valueAt(i));
732 }
733
734 final int numDevices = mInputDevices.length;
735 deviceIdAndGeneration = new int[numDevices * 2];
736 for (int i = 0; i < numDevices; i++) {
737 final InputDevice inputDevice = mInputDevices[i];
738 deviceIdAndGeneration[i * 2] = inputDevice.getId();
739 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700740
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700741 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700742 if (!containsInputDeviceWithDescriptor(oldInputDevices,
743 inputDevice.getDescriptor())) {
744 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
745 } else {
746 mTempFullKeyboards.add(inputDevice);
747 }
748 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700749 }
750 }
751
Jeff Browncf39bdf2012-05-18 14:41:19 -0700752 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700753 for (int i = 0; i < numListeners; i++) {
754 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
755 deviceIdAndGeneration);
756 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700757 mTempInputDevicesChangedListenersToNotify.clear();
758
759 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000760 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
761 final int numFullKeyboards = mTempFullKeyboards.size();
762 synchronized (mDataStore) {
763 for (int i = 0; i < numFullKeyboards; i++) {
764 final InputDevice inputDevice = mTempFullKeyboards.get(i);
765 String layout =
766 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
767 if (layout == null) {
768 layout = getDefaultKeyboardLayout(inputDevice);
769 if (layout != null) {
770 setCurrentKeyboardLayoutForInputDevice(
771 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700772 }
773 }
Michael Wright07483422015-10-30 16:20:13 +0000774 if (layout == null) {
775 keyboardsMissingLayout.add(inputDevice);
776 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700777 }
Michael Wright07483422015-10-30 16:20:13 +0000778 }
779
780 if (mNotificationManager != null) {
781 if (!keyboardsMissingLayout.isEmpty()) {
782 if (keyboardsMissingLayout.size() > 1) {
783 // We have more than one keyboard missing a layout, so drop the
784 // user at the generic input methods page so they can pick which
785 // one to set.
786 showMissingKeyboardLayoutNotification(null);
787 } else {
788 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700789 }
790 } else if (mKeyboardLayoutNotificationShown) {
791 hideMissingKeyboardLayoutNotification();
792 }
793 }
794 mTempFullKeyboards.clear();
795 }
796
Michael Wright07483422015-10-30 16:20:13 +0000797 private String getDefaultKeyboardLayout(final InputDevice d) {
798 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
799 // If our locale doesn't have a language for some reason, then we don't really have a
800 // reasonable default.
801 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
802 return null;
803 }
804 final List<KeyboardLayout> layouts = new ArrayList<>();
805 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
806 @Override
807 public void visitKeyboardLayout(Resources resources,
808 int keyboardLayoutResId, KeyboardLayout layout) {
809 // Only select a default when we know the layout is appropriate. For now, this
810 // means its a custom layout for a specific keyboard.
811 if (layout.getVendorId() != d.getVendorId()
812 || layout.getProductId() != d.getProductId()) {
813 return;
814 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800815 final LocaleList locales = layout.getLocales();
816 final int numLocales = locales.size();
817 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
818 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000819 layouts.add(layout);
820 break;
821 }
822 }
823 }
824 });
825
826 if (layouts.isEmpty()) {
827 return null;
828 }
829
830 // First sort so that ones with higher priority are listed at the top
831 Collections.sort(layouts);
832 // Next we want to try to find an exact match of language, country and variant.
833 final int N = layouts.size();
834 for (int i = 0; i < N; i++) {
835 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800836 final LocaleList locales = layout.getLocales();
837 final int numLocales = locales.size();
838 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
839 final Locale locale = locales.get(localeIndex);
840 if (locale.getCountry().equals(systemLocale.getCountry())
841 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000842 return layout.getDescriptor();
843 }
844 }
845 }
846 // Then try an exact match of language and country
847 for (int i = 0; i < N; i++) {
848 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800849 final LocaleList locales = layout.getLocales();
850 final int numLocales = locales.size();
851 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
852 final Locale locale = locales.get(localeIndex);
853 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000854 return layout.getDescriptor();
855 }
856 }
857 }
858
859 // Give up and just use the highest priority layout with matching language
860 return layouts.get(0).getDescriptor();
861 }
862
863 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
864 // Different languages are never compatible
865 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
866 return false;
867 }
868 // If both the system and the keyboard layout have a country specifier, they must be equal.
869 if (!TextUtils.isEmpty(systemLocale.getCountry())
870 && !TextUtils.isEmpty(keyboardLocale.getCountry())
871 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
872 return false;
873 }
874 return true;
875 }
876
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800877 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700878 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
879 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800880 if (inputDeviceDescriptor == null) {
881 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
882 }
883
884 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700885 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800886 }
887 }
888
889 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700890 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800891 TouchCalibration calibration) {
892 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
893 "setTouchCalibrationForInputDevice()")) {
894 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
895 }
896 if (inputDeviceDescriptor == null) {
897 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
898 }
899 if (calibration == null) {
900 throw new IllegalArgumentException("calibration must not be null");
901 }
Jason Gerecked5220742014-03-10 09:47:59 -0700902 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
903 throw new IllegalArgumentException("surfaceRotation value out of bounds");
904 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800905
906 synchronized (mDataStore) {
907 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700908 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
909 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800910 nativeReloadCalibration(mPtr);
911 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800912 } finally {
913 mDataStore.saveIfNeeded();
914 }
915 }
916 }
917
Michael Wright39e5e942015-08-19 22:52:47 +0100918 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100919 public int isInTabletMode() {
920 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
921 "isInTabletMode()")) {
922 throw new SecurityException("Requires TABLET_MODE permission");
923 }
924 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
925 }
926
927 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100928 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100929 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100930 "registerTabletModeChangedListener()")) {
931 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
932 }
933 if (listener == null) {
934 throw new IllegalArgumentException("listener must not be null");
935 }
936
937 synchronized (mTabletModeLock) {
938 final int callingPid = Binder.getCallingPid();
939 if (mTabletModeChangedListeners.get(callingPid) != null) {
940 throw new IllegalStateException("The calling process has already registered "
941 + "a TabletModeChangedListener.");
942 }
943 TabletModeChangedListenerRecord record =
944 new TabletModeChangedListenerRecord(callingPid, listener);
945 try {
946 IBinder binder = listener.asBinder();
947 binder.linkToDeath(record, 0);
948 } catch (RemoteException ex) {
949 throw new RuntimeException(ex);
950 }
951 mTabletModeChangedListeners.put(callingPid, record);
952 }
953 }
954
955 private void onTabletModeChangedListenerDied(int pid) {
956 synchronized (mTabletModeLock) {
957 mTabletModeChangedListeners.remove(pid);
958 }
959 }
960
961 // Must be called on handler
962 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
963 mTempTabletModeChangedListenersToNotify.clear();
964 final int numListeners;
965 synchronized (mTabletModeLock) {
966 numListeners = mTabletModeChangedListeners.size();
967 for (int i = 0; i < numListeners; i++) {
968 mTempTabletModeChangedListenersToNotify.add(
969 mTabletModeChangedListeners.valueAt(i));
970 }
971 }
972 for (int i = 0; i < numListeners; i++) {
973 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
974 whenNanos, inTabletMode);
975 }
976 }
977
Jeff Browncf39bdf2012-05-18 14:41:19 -0700978 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700979 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700980 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700981 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700982 if (device != null) {
983 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700984 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700985 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
986 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
987 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
988 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
989 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700990
991 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500992 Notification notification =
993 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
994 .setContentTitle(r.getString(
995 R.string.select_keyboard_layout_notification_title))
996 .setContentText(r.getString(
997 R.string.select_keyboard_layout_notification_message))
998 .setContentIntent(keyboardLayoutIntent)
999 .setSmallIcon(R.drawable.ic_settings_language)
1000 .setColor(mContext.getColor(
1001 com.android.internal.R.color.system_notification_accent_color))
1002 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001003 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001004 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001005 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001006 mKeyboardLayoutNotificationShown = true;
1007 }
1008 }
1009
1010 // Must be called on handler.
1011 private void hideMissingKeyboardLayoutNotification() {
1012 if (mKeyboardLayoutNotificationShown) {
1013 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001014 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001015 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001016 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001017 }
1018 }
1019
1020 // Must be called on handler.
1021 private void updateKeyboardLayouts() {
1022 // Scan all input devices state for keyboard layouts that have been uninstalled.
1023 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1024 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1025 @Override
Michael Wright07483422015-10-30 16:20:13 +00001026 public void visitKeyboardLayout(Resources resources,
1027 int keyboardLayoutResId, KeyboardLayout layout) {
1028 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001029 }
1030 });
1031 synchronized (mDataStore) {
1032 try {
1033 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1034 } finally {
1035 mDataStore.saveIfNeeded();
1036 }
1037 }
1038
1039 // Reload keyboard layouts.
1040 reloadKeyboardLayouts();
1041 }
1042
Jeff Browncf39bdf2012-05-18 14:41:19 -07001043 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1044 String descriptor) {
1045 final int numDevices = inputDevices.length;
1046 for (int i = 0; i < numDevices; i++) {
1047 final InputDevice inputDevice = inputDevices[i];
1048 if (inputDevice.getDescriptor().equals(descriptor)) {
1049 return true;
1050 }
1051 }
1052 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001053 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001054
1055 @Override // Binder call
1056 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001057 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1058 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1059 @Override
Michael Wright07483422015-10-30 16:20:13 +00001060 public void visitKeyboardLayout(Resources resources,
1061 int keyboardLayoutResId, KeyboardLayout layout) {
1062 list.add(layout);
1063 }
1064 });
1065 return list.toArray(new KeyboardLayout[list.size()]);
1066 }
1067
Michael Wrightb0e804a2016-01-04 16:48:53 -05001068 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001069 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1070 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001071 final String[] enabledLayoutDescriptors =
1072 getEnabledKeyboardLayoutsForInputDevice(identifier);
1073 final ArrayList<KeyboardLayout> enabledLayouts =
1074 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1075 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001076 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1077 boolean mHasSeenDeviceSpecificLayout;
1078
1079 @Override
1080 public void visitKeyboardLayout(Resources resources,
1081 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001082 // First check if it's enabled. If the keyboard layout is enabled then we always
1083 // want to return it as a possible layout for the device.
1084 for (String s : enabledLayoutDescriptors) {
1085 if (s != null && s.equals(layout.getDescriptor())) {
1086 enabledLayouts.add(layout);
1087 return;
1088 }
1089 }
1090 // Next find any potential layouts that aren't yet enabled for the device. For
1091 // devices that have special layouts we assume there's a reason that the generic
1092 // layouts don't work for them so we don't want to return them since it's likely
1093 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001094 if (layout.getVendorId() == identifier.getVendorId()
1095 && layout.getProductId() == identifier.getProductId()) {
1096 if (!mHasSeenDeviceSpecificLayout) {
1097 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001098 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001099 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001100 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001101 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1102 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001103 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001104 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001105 }
1106 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001107 final int enabledLayoutSize = enabledLayouts.size();
1108 final int potentialLayoutSize = potentialLayouts.size();
1109 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1110 enabledLayouts.toArray(layouts);
1111 for (int i = 0; i < potentialLayoutSize; i++) {
1112 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1113 }
1114 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001115 }
1116
1117 @Override // Binder call
1118 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1119 if (keyboardLayoutDescriptor == null) {
1120 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1121 }
1122
Jeff Brown6ec6f792012-04-17 16:52:41 -07001123 final KeyboardLayout[] result = new KeyboardLayout[1];
1124 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1125 @Override
Michael Wright07483422015-10-30 16:20:13 +00001126 public void visitKeyboardLayout(Resources resources,
1127 int keyboardLayoutResId, KeyboardLayout layout) {
1128 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001129 }
1130 });
1131 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001132 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001133 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001134 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001135 return result[0];
1136 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001137
Jeff Brown6ec6f792012-04-17 16:52:41 -07001138 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001139 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001140 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1141 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001142 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1143 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001144 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1145 final int priority = resolveInfo.priority;
1146 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001147 }
1148 }
1149
Jeff Brown6ec6f792012-04-17 16:52:41 -07001150 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1151 KeyboardLayoutVisitor visitor) {
1152 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1153 if (d != null) {
1154 final PackageManager pm = mContext.getPackageManager();
1155 try {
1156 ActivityInfo receiver = pm.getReceiverInfo(
1157 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001158 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001159 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1160 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001161 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001162 } catch (NameNotFoundException ex) {
1163 }
1164 }
1165 }
1166
1167 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001168 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001169 Bundle metaData = receiver.metaData;
1170 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001171 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001172 }
1173
1174 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1175 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001176 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001177 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001178 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001179 }
1180
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001181 CharSequence receiverLabel = receiver.loadLabel(pm);
1182 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001183 int priority;
1184 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1185 priority = requestedPriority;
1186 } else {
1187 priority = 0;
1188 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001189
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001190 try {
1191 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1192 XmlResourceParser parser = resources.getXml(configResId);
1193 try {
1194 XmlUtils.beginDocument(parser, "keyboard-layouts");
1195
1196 for (;;) {
1197 XmlUtils.nextElement(parser);
1198 String element = parser.getName();
1199 if (element == null) {
1200 break;
1201 }
1202 if (element.equals("keyboard-layout")) {
1203 TypedArray a = resources.obtainAttributes(
1204 parser, com.android.internal.R.styleable.KeyboardLayout);
1205 try {
1206 String name = a.getString(
1207 com.android.internal.R.styleable.KeyboardLayout_name);
1208 String label = a.getString(
1209 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001210 int keyboardLayoutResId = a.getResourceId(
1211 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1212 0);
Michael Wright07483422015-10-30 16:20:13 +00001213 String languageTags = a.getString(
1214 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001215 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001216 int vid = a.getInt(
1217 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1218 int pid = a.getInt(
1219 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1220
Jeff Brown2f095762012-05-10 21:29:33 -07001221 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001222 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001223 + "attributes in keyboard layout "
1224 + "resource from receiver "
1225 + receiver.packageName + "/" + receiver.name);
1226 } else {
1227 String descriptor = KeyboardLayoutDescriptor.format(
1228 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001229 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001230 KeyboardLayout layout = new KeyboardLayout(
1231 descriptor, label, collection, priority,
1232 locales, vid, pid);
1233 visitor.visitKeyboardLayout(
1234 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001235 }
1236 }
1237 } finally {
1238 a.recycle();
1239 }
1240 } else {
Michael Wright07483422015-10-30 16:20:13 +00001241 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001242 + "' in keyboard layout resource from receiver "
1243 + receiver.packageName + "/" + receiver.name);
1244 }
1245 }
1246 } finally {
1247 parser.close();
1248 }
1249 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001250 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001251 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001252 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001253 }
1254
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001255 @NonNull
1256 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001257 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001258 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001259 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001260 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001261 }
1262
RoboErikfb290df2013-12-16 11:27:55 -08001263 /**
1264 * Builds a layout descriptor for the vendor/product. This returns the
1265 * descriptor for ids that aren't useful (such as the default 0, 0).
1266 */
1267 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1268 if (identifier == null || identifier.getDescriptor() == null) {
1269 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001270 }
1271
RoboErikfb290df2013-12-16 11:27:55 -08001272 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1273 return identifier.getDescriptor();
1274 }
1275 StringBuilder bob = new StringBuilder();
1276 bob.append("vendor:").append(identifier.getVendorId());
1277 bob.append(",product:").append(identifier.getProductId());
1278 return bob.toString();
1279 }
1280
1281 @Override // Binder call
1282 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1283
1284 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001285 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001286 String layout = null;
1287 // try loading it using the layout descriptor if we have it
1288 layout = mDataStore.getCurrentKeyboardLayout(key);
1289 if (layout == null && !key.equals(identifier.getDescriptor())) {
1290 // if it doesn't exist fall back to the device descriptor
1291 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1292 }
1293 if (DEBUG) {
1294 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1295 + layout);
1296 }
1297 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001298 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001299 }
1300
1301 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001302 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001303 String keyboardLayoutDescriptor) {
1304 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001305 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001306 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1307 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001308 if (keyboardLayoutDescriptor == null) {
1309 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1310 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001311
RoboErikfb290df2013-12-16 11:27:55 -08001312 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001313 synchronized (mDataStore) {
1314 try {
RoboErikfb290df2013-12-16 11:27:55 -08001315 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1316 if (DEBUG) {
1317 Slog.d(TAG, "Saved keyboard layout using " + key);
1318 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001319 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1320 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001321 } finally {
1322 mDataStore.saveIfNeeded();
1323 }
1324 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001325 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001326
Jeff Browncf39bdf2012-05-18 14:41:19 -07001327 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001328 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001329 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001330 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001331 String[] layouts = mDataStore.getKeyboardLayouts(key);
1332 if ((layouts == null || layouts.length == 0)
1333 && !key.equals(identifier.getDescriptor())) {
1334 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1335 }
1336 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001337 }
1338 }
1339
1340 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001341 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001342 String keyboardLayoutDescriptor) {
1343 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1344 "addKeyboardLayoutForInputDevice()")) {
1345 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1346 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001347 if (keyboardLayoutDescriptor == null) {
1348 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1349 }
1350
RoboErikfb290df2013-12-16 11:27:55 -08001351 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001352 synchronized (mDataStore) {
1353 try {
RoboErikfb290df2013-12-16 11:27:55 -08001354 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1355 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1356 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1357 }
1358 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001359 && !Objects.equals(oldLayout,
1360 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001361 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1362 }
1363 } finally {
1364 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001365 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001366 }
1367 }
1368
1369 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001370 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001371 String keyboardLayoutDescriptor) {
1372 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1373 "removeKeyboardLayoutForInputDevice()")) {
1374 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1375 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001376 if (keyboardLayoutDescriptor == null) {
1377 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1378 }
1379
RoboErikfb290df2013-12-16 11:27:55 -08001380 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001381 synchronized (mDataStore) {
1382 try {
RoboErikfb290df2013-12-16 11:27:55 -08001383 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1384 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1385 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1386 }
1387 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1388 if (!key.equals(identifier.getDescriptor())) {
1389 // We need to remove from both places to ensure it is gone
1390 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1391 keyboardLayoutDescriptor);
1392 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001393 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001394 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001395 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1396 }
1397 } finally {
1398 mDataStore.saveIfNeeded();
1399 }
1400 }
1401 }
1402
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001403 public void switchKeyboardLayout(int deviceId, int direction) {
1404 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001405 }
1406
1407 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001408 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1409 final InputDevice device = getInputDevice(deviceId);
1410 if (device != null) {
1411 final boolean changed;
1412 final String keyboardLayoutDescriptor;
1413
1414 String key = getLayoutDescriptor(device.getIdentifier());
1415 synchronized (mDataStore) {
1416 try {
1417 changed = mDataStore.switchKeyboardLayout(key, direction);
1418 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1419 key);
1420 } finally {
1421 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001422 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001423 }
1424
1425 if (changed) {
1426 if (mSwitchedKeyboardLayoutToast != null) {
1427 mSwitchedKeyboardLayoutToast.cancel();
1428 mSwitchedKeyboardLayoutToast = null;
1429 }
1430 if (keyboardLayoutDescriptor != null) {
1431 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1432 if (keyboardLayout != null) {
1433 mSwitchedKeyboardLayoutToast = Toast.makeText(
1434 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1435 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001436 }
1437 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001438
1439 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001440 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001441 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001442 }
1443
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001444 public void setFocusedApplication(int displayId, InputApplicationHandle application) {
1445 nativeSetFocusedApplication(mPtr, displayId, application);
1446 }
1447
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001448 public void setFocusedDisplay(int displayId) {
1449 nativeSetFocusedDisplay(mPtr, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001450 }
RoboErikfb290df2013-12-16 11:27:55 -08001451
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001452 @Override
1453 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1454 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1455 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1456 + windowToken);
1457 return;
1458 }
1459 if (mFocusedWindowHasCapture == enabled) {
1460 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1461 return;
1462 }
1463 setPointerCapture(enabled);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001464 }
1465
1466 private void setPointerCapture(boolean enabled) {
Tiger Huang1e5b10a2018-07-30 20:19:51 +08001467 if (mFocusedWindowHasCapture != enabled) {
1468 mFocusedWindowHasCapture = enabled;
1469 try {
1470 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1471 } catch (RemoteException ex) {
1472 /* ignore */
1473 }
1474 nativeSetPointerCapture(mPtr, enabled);
1475 }
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001476 }
1477
Jeff Brown349703e2010-06-22 01:27:15 -07001478 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001479 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001480 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001481
1482 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001483 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001484 }
1485
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001486 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001487 public void tryPointerSpeed(int speed) {
1488 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1489 "tryPointerSpeed()")) {
1490 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1491 }
1492
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001493 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1494 throw new IllegalArgumentException("speed out of range");
1495 }
1496
Jeff Brownac143512012-04-05 18:57:33 -07001497 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001498 }
1499
1500 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001501 int speed = getPointerSpeedSetting();
1502 setPointerSpeedUnchecked(speed);
1503 }
1504
1505 private void setPointerSpeedUnchecked(int speed) {
1506 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1507 InputManager.MAX_POINTER_SPEED);
1508 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001509 }
1510
1511 private void registerPointerSpeedSettingObserver() {
1512 mContext.getContentResolver().registerContentObserver(
1513 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001514 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001515 @Override
1516 public void onChange(boolean selfChange) {
1517 updatePointerSpeedFromSettings();
1518 }
Jeff Brownd4935962012-09-25 13:27:20 -07001519 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001520 }
1521
Jeff Brownac143512012-04-05 18:57:33 -07001522 private int getPointerSpeedSetting() {
1523 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001524 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001525 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1526 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001527 } catch (SettingNotFoundException snfe) {
1528 }
1529 return speed;
1530 }
1531
Jeff Browndaf4a122011-08-26 17:14:14 -07001532 public void updateShowTouchesFromSettings() {
1533 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001534 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001535 }
1536
1537 private void registerShowTouchesSettingObserver() {
1538 mContext.getContentResolver().registerContentObserver(
1539 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001540 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001541 @Override
1542 public void onChange(boolean selfChange) {
1543 updateShowTouchesFromSettings();
1544 }
Jeff Brownd4935962012-09-25 13:27:20 -07001545 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001546 }
1547
Jun Mukaie4e75da2015-12-15 16:19:20 -08001548 public void updateAccessibilityLargePointerFromSettings() {
1549 final int accessibilityConfig = Settings.Secure.getIntForUser(
1550 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1551 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001552 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001553 nativeReloadPointerIcons(mPtr);
1554 }
1555
Jun Mukai19a56012015-11-24 11:25:52 -08001556 private void registerAccessibilityLargePointerSettingObserver() {
1557 mContext.getContentResolver().registerContentObserver(
1558 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1559 new ContentObserver(mHandler) {
1560 @Override
1561 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001562 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001563 }
1564 }, UserHandle.USER_ALL);
1565 }
1566
Jeff Browndaf4a122011-08-26 17:14:14 -07001567 private int getShowTouchesSetting(int defaultValue) {
1568 int result = defaultValue;
1569 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001570 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1571 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001572 } catch (SettingNotFoundException snfe) {
1573 }
1574 return result;
1575 }
1576
Jeff Browna47425a2012-04-13 04:09:27 -07001577 // Binder call
1578 @Override
1579 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1580 if (repeat >= pattern.length) {
1581 throw new ArrayIndexOutOfBoundsException();
1582 }
1583
1584 VibratorToken v;
1585 synchronized (mVibratorLock) {
1586 v = mVibratorTokens.get(token);
1587 if (v == null) {
1588 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1589 try {
1590 token.linkToDeath(v, 0);
1591 } catch (RemoteException ex) {
1592 // give up
1593 throw new RuntimeException(ex);
1594 }
1595 mVibratorTokens.put(token, v);
1596 }
1597 }
1598
1599 synchronized (v) {
1600 v.mVibrating = true;
1601 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1602 }
1603 }
1604
1605 // Binder call
1606 @Override
1607 public void cancelVibrate(int deviceId, IBinder token) {
1608 VibratorToken v;
1609 synchronized (mVibratorLock) {
1610 v = mVibratorTokens.get(token);
1611 if (v == null || v.mDeviceId != deviceId) {
1612 return; // nothing to cancel
1613 }
1614 }
1615
1616 cancelVibrateIfNeeded(v);
1617 }
1618
1619 void onVibratorTokenDied(VibratorToken v) {
1620 synchronized (mVibratorLock) {
1621 mVibratorTokens.remove(v.mToken);
1622 }
1623
1624 cancelVibrateIfNeeded(v);
1625 }
1626
1627 private void cancelVibrateIfNeeded(VibratorToken v) {
1628 synchronized (v) {
1629 if (v.mVibrating) {
1630 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1631 v.mVibrating = false;
1632 }
1633 }
1634 }
1635
Jun Mukai19a56012015-11-24 11:25:52 -08001636 // Binder call
1637 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001638 public void setPointerIconType(int iconId) {
1639 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001640 }
Jun Mukai1db53972015-09-11 18:08:31 -07001641
Jun Mukaid4eaef72015-10-30 15:54:33 -07001642 // Binder call
1643 @Override
1644 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001645 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001646 nativeSetCustomPointerIcon(mPtr, icon);
1647 }
1648
Jeff Brown4532e612012-04-05 14:27:12 -07001649 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001650 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001651 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001652
1653 pw.println("INPUT MANAGER (dumpsys input)\n");
1654 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001655 if (dumpStr != null) {
1656 pw.println(dumpStr);
1657 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001658 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001659
Jeff Brownac143512012-04-05 18:57:33 -07001660 private boolean checkCallingPermission(String permission, String func) {
1661 // Quick check: if the calling permission is me, it's all okay.
1662 if (Binder.getCallingPid() == Process.myPid()) {
1663 return true;
1664 }
1665
1666 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1667 return true;
1668 }
1669 String msg = "Permission Denial: " + func + " from pid="
1670 + Binder.getCallingPid()
1671 + ", uid=" + Binder.getCallingUid()
1672 + " requires " + permission;
1673 Slog.w(TAG, msg);
1674 return false;
1675 }
1676
Jeff Brown4532e612012-04-05 14:27:12 -07001677 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001678 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001679 public void monitor() {
1680 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001681 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001682 }
1683
Andrii Kulianed76e742017-06-26 14:57:02 -07001684 // Binder call
1685 @Override
1686 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1687 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1688 "createInputForwarder()")) {
1689 throw new SecurityException("Requires INJECT_EVENTS permission");
1690 }
1691 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1692 final Display display = displayManager.getDisplay(displayId);
1693 if (display == null) {
1694 throw new IllegalArgumentException(
1695 "Can't create input forwarder for non-existent displayId: " + displayId);
1696 }
1697 final int callingUid = Binder.getCallingUid();
1698 final int displayOwnerUid = display.getOwnerUid();
1699 if (callingUid != displayOwnerUid) {
1700 throw new SecurityException(
1701 "Only owner of the display can forward input events to it.");
1702 }
1703
1704 return new InputForwarder(displayId);
1705 }
1706
Jeff Brown4532e612012-04-05 14:27:12 -07001707 // Native callback.
1708 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001709 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001710 }
1711
1712 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001713 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1714 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001715 if (!mInputDevicesChangedPending) {
1716 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001717 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1718 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001719 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001720
1721 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001722 }
1723 }
1724
1725 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001726 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1727 if (DEBUG) {
1728 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1729 + ", mask=" + Integer.toHexString(switchMask));
1730 }
1731
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001732 if ((switchMask & SW_LID_BIT) != 0) {
1733 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001734 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001735 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001736
Michael Wright3818c922014-09-02 13:59:07 -07001737 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001738 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001739 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1740 }
1741
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001742 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1743 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1744 switchMask);
1745 }
Michael Wright39e5e942015-08-19 22:52:47 +01001746
Michael Wright9209c9c2015-09-03 17:57:01 +01001747 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001748 SomeArgs args = SomeArgs.obtain();
1749 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1750 args.argi2 = (int) (whenNanos >> 32);
1751 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1752 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1753 args).sendToTarget();
1754 }
Jeff Brown4532e612012-04-05 14:27:12 -07001755 }
1756
1757 // Native callback.
Robert Carre0a353c2018-08-02 16:38:04 -07001758 private void notifyInputChannelBroken(IBinder token) {
1759 mWindowManagerCallbacks.notifyInputChannelBroken(token);
Jeff Brown4532e612012-04-05 14:27:12 -07001760 }
1761
Robert Carrbd26e652018-08-21 15:46:28 -07001762 // Native callback
chaviw91089862019-01-09 15:49:11 -08001763 private void notifyFocusChanged(IBinder oldToken, IBinder newToken) {
1764 if (mFocusedWindow.asBinder() == newToken) {
chaviw78658892019-01-09 10:23:41 -08001765 Log.w(TAG, "notifyFocusChanged called with unchanged mFocusedWindow=" + mFocusedWindow);
1766 return;
Robert Carrbd26e652018-08-21 15:46:28 -07001767 }
chaviw78658892019-01-09 10:23:41 -08001768
1769 setPointerCapture(false);
chaviw91089862019-01-09 15:49:11 -08001770 mFocusedWindow = IWindow.Stub.asInterface(newToken);
Robert Carrbd26e652018-08-21 15:46:28 -07001771 }
1772
Jeff Brown4532e612012-04-05 14:27:12 -07001773 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001774 private long notifyANR(IBinder token, String reason) {
Jeff Brownbd181bb2013-09-10 16:44:24 -07001775 return mWindowManagerCallbacks.notifyANR(
Robert Carr679ccb02018-08-08 15:32:35 -07001776 token, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001777 }
1778
1779 // Native callback.
1780 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1781 synchronized (mInputFilterLock) {
1782 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001783 try {
1784 mInputFilter.filterInputEvent(event, policyFlags);
1785 } catch (RemoteException e) {
1786 /* ignore */
1787 }
Jeff Brown4532e612012-04-05 14:27:12 -07001788 return false;
1789 }
1790 }
1791 event.recycle();
1792 return true;
1793 }
1794
1795 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001796 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1797 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001798 }
1799
1800 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001801 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1802 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001803 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001804 }
1805
1806 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001807 private long interceptKeyBeforeDispatching(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001808 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001809 }
1810
1811 // Native callback.
Robert Carr679ccb02018-08-08 15:32:35 -07001812 private KeyEvent dispatchUnhandledKey(IBinder focus, KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001813 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001814 }
1815
1816 // Native callback.
1817 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1818 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1819 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1820 }
1821
1822 // Native callback.
1823 private int getVirtualKeyQuietTimeMillis() {
1824 return mContext.getResources().getInteger(
1825 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1826 }
1827
1828 // Native callback.
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001829 private static String[] getExcludedDeviceNames() {
1830 List<String> names = new ArrayList<>();
Jeff Brown4532e612012-04-05 14:27:12 -07001831 // Read partner-provided list of excluded input devices
Jeff Brown4532e612012-04-05 14:27:12 -07001832 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001833 final File[] baseDirs = {
1834 Environment.getRootDirectory(),
1835 Environment.getVendorDirectory()
1836 };
1837 for (File baseDir: baseDirs) {
1838 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001839 try {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001840 InputStream stream = new FileInputStream(confFile);
1841 names.addAll(ConfigurationProcessor.processExcludedDeviceNames(stream));
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001842 } catch (FileNotFoundException e) {
1843 // It's ok if the file does not exist.
1844 } catch (Exception e) {
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001845 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
Jeff Brown4532e612012-04-05 14:27:12 -07001846 }
Jeff Brown4532e612012-04-05 14:27:12 -07001847 }
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001848 return names.toArray(new String[0]);
1849 }
Jeff Brown4532e612012-04-05 14:27:12 -07001850
Siarhei Vishniakou15a412d2018-10-04 19:01:04 -07001851 /**
1852 * Flatten a list of pairs into a list, with value positioned directly next to the key
1853 * @return Flattened list
1854 */
1855 private static <T> List<T> flatten(@NonNull List<Pair<T, T>> pairs) {
1856 List<T> list = new ArrayList<>(pairs.size() * 2);
1857 for (Pair<T, T> pair : pairs) {
1858 list.add(pair.first);
1859 list.add(pair.second);
1860 }
1861 return list;
1862 }
1863
1864 /**
1865 * Ports are highly platform-specific, so only allow these to be specified in the vendor
1866 * directory.
1867 */
1868 // Native callback
1869 private static String[] getInputPortAssociations() {
1870 File baseDir = Environment.getVendorDirectory();
1871 File confFile = new File(baseDir, PORT_ASSOCIATIONS_PATH);
1872
1873 try {
1874 InputStream stream = new FileInputStream(confFile);
1875 List<Pair<String, String>> associations =
1876 ConfigurationProcessor.processInputPortAssociations(stream);
1877 List<String> associationList = flatten(associations);
1878 return associationList.toArray(new String[0]);
1879 } catch (FileNotFoundException e) {
1880 // Most of the time, file will not exist, which is expected.
1881 } catch (Exception e) {
1882 Slog.e(TAG, "Could not parse '" + confFile.getAbsolutePath() + "'", e);
1883 }
1884 return new String[0];
Jeff Brown4532e612012-04-05 14:27:12 -07001885 }
1886
1887 // Native callback.
1888 private int getKeyRepeatTimeout() {
1889 return ViewConfiguration.getKeyRepeatTimeout();
1890 }
1891
1892 // Native callback.
1893 private int getKeyRepeatDelay() {
1894 return ViewConfiguration.getKeyRepeatDelay();
1895 }
1896
1897 // Native callback.
1898 private int getHoverTapTimeout() {
1899 return ViewConfiguration.getHoverTapTimeout();
1900 }
1901
1902 // Native callback.
1903 private int getHoverTapSlop() {
1904 return ViewConfiguration.getHoverTapSlop();
1905 }
1906
1907 // Native callback.
1908 private int getDoubleTapTimeout() {
1909 return ViewConfiguration.getDoubleTapTimeout();
1910 }
1911
1912 // Native callback.
1913 private int getLongPressTimeout() {
1914 return ViewConfiguration.getLongPressTimeout();
1915 }
1916
1917 // Native callback.
1918 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001919 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001920 }
1921
1922 // Native callback.
1923 private PointerIcon getPointerIcon() {
1924 return PointerIcon.getDefaultIcon(mContext);
1925 }
1926
Jeff Brown6ec6f792012-04-17 16:52:41 -07001927 // Native callback.
Arthur Hungb9b32002018-12-18 17:39:43 +08001928 private int getPointerDisplayId() {
1929 return mWindowManagerCallbacks.getPointerDisplayId();
1930 }
1931
1932 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001933 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001934 if (!mSystemReady) {
1935 return null;
1936 }
1937
RoboErikfb290df2013-12-16 11:27:55 -08001938 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001939 if (keyboardLayoutDescriptor == null) {
1940 return null;
1941 }
1942
1943 final String[] result = new String[2];
1944 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1945 @Override
Michael Wright07483422015-10-30 16:20:13 +00001946 public void visitKeyboardLayout(Resources resources,
1947 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001948 try {
Michael Wright07483422015-10-30 16:20:13 +00001949 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001950 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001951 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001952 } catch (IOException ex) {
1953 } catch (NotFoundException ex) {
1954 }
1955 }
1956 });
1957 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001958 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001959 + keyboardLayoutDescriptor + "'.");
1960 return null;
1961 }
1962 return result;
1963 }
1964
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001965 // Native callback.
1966 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001967 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1968 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1969 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001970 }
1971 return null;
1972 }
1973
Jeff Brown4532e612012-04-05 14:27:12 -07001974 /**
1975 * Callback interface implemented by the Window Manager.
1976 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001977 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001978 public void notifyConfigurationChanged();
1979
1980 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1981
Michael Wright3818c922014-09-02 13:59:07 -07001982 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
1983
Robert Carre0a353c2018-08-02 16:38:04 -07001984 public void notifyInputChannelBroken(IBinder token);
Jeff Brown4532e612012-04-05 14:27:12 -07001985
Robert Carr679ccb02018-08-08 15:32:35 -07001986 public long notifyANR(IBinder token, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001987
Jeff Brown037c33e2014-04-09 00:31:55 -07001988 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001989
Michael Wright70af00a2014-09-03 19:30:20 -07001990 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001991
Robert Carre0a353c2018-08-02 16:38:04 -07001992 public long interceptKeyBeforeDispatching(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07001993 KeyEvent event, int policyFlags);
1994
Robert Carre0a353c2018-08-02 16:38:04 -07001995 public KeyEvent dispatchUnhandledKey(IBinder token,
Jeff Brown4532e612012-04-05 14:27:12 -07001996 KeyEvent event, int policyFlags);
1997
1998 public int getPointerLayer();
Arthur Hungb9b32002018-12-18 17:39:43 +08001999
2000 public int getPointerDisplayId();
Jeff Brown4532e612012-04-05 14:27:12 -07002001 }
2002
2003 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002004 * Callback interface implemented by WiredAccessoryObserver.
2005 */
2006 public interface WiredAccessoryCallbacks {
2007 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002008 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002009 }
2010
2011 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002012 * Private handler for the input manager.
2013 */
2014 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002015 public InputManagerHandler(Looper looper) {
2016 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002017 }
2018
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002019 @Override
2020 public void handleMessage(Message msg) {
2021 switch (msg.what) {
2022 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002023 deliverInputDevicesChanged((InputDevice[])msg.obj);
2024 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002025 case MSG_SWITCH_KEYBOARD_LAYOUT:
2026 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002027 break;
2028 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2029 reloadKeyboardLayouts();
2030 break;
2031 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2032 updateKeyboardLayouts();
2033 break;
2034 case MSG_RELOAD_DEVICE_ALIASES:
2035 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002036 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002037 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002038 SomeArgs args = (SomeArgs) msg.obj;
2039 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2040 boolean inTabletMode = (boolean) args.arg1;
2041 deliverTabletModeChanged(whenNanos, inTabletMode);
2042 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002043 }
2044 }
2045 }
2046
2047 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002048 * Hosting interface for input filters to call back into the input manager.
2049 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002050 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002051 private boolean mDisconnected;
2052
2053 public void disconnectLocked() {
2054 mDisconnected = true;
2055 }
2056
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002057 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002058 public void sendInputEvent(InputEvent event, int policyFlags) {
2059 if (event == null) {
2060 throw new IllegalArgumentException("event must not be null");
2061 }
2062
2063 synchronized (mInputFilterLock) {
2064 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002065 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002066 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002067 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2068 }
2069 }
2070 }
2071 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002072
2073 private static final class KeyboardLayoutDescriptor {
2074 public String packageName;
2075 public String receiverName;
2076 public String keyboardLayoutName;
2077
2078 public static String format(String packageName,
2079 String receiverName, String keyboardName) {
2080 return packageName + "/" + receiverName + "/" + keyboardName;
2081 }
2082
2083 public static KeyboardLayoutDescriptor parse(String descriptor) {
2084 int pos = descriptor.indexOf('/');
2085 if (pos < 0 || pos + 1 == descriptor.length()) {
2086 return null;
2087 }
2088 int pos2 = descriptor.indexOf('/', pos + 1);
2089 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2090 return null;
2091 }
2092
2093 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2094 result.packageName = descriptor.substring(0, pos);
2095 result.receiverName = descriptor.substring(pos + 1, pos2);
2096 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2097 return result;
2098 }
2099 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002100
Jeff Brown6ec6f792012-04-17 16:52:41 -07002101 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002102 void visitKeyboardLayout(Resources resources,
2103 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002104 }
2105
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002106 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2107 private final int mPid;
2108 private final IInputDevicesChangedListener mListener;
2109
2110 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2111 mPid = pid;
2112 mListener = listener;
2113 }
2114
2115 @Override
2116 public void binderDied() {
2117 if (DEBUG) {
2118 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2119 }
2120 onInputDevicesChangedListenerDied(mPid);
2121 }
2122
2123 public void notifyInputDevicesChanged(int[] info) {
2124 try {
2125 mListener.onInputDevicesChanged(info);
2126 } catch (RemoteException ex) {
2127 Slog.w(TAG, "Failed to notify process "
2128 + mPid + " that input devices changed, assuming it died.", ex);
2129 binderDied();
2130 }
2131 }
2132 }
Jeff Browna47425a2012-04-13 04:09:27 -07002133
Michael Wright39e5e942015-08-19 22:52:47 +01002134 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2135 private final int mPid;
2136 private final ITabletModeChangedListener mListener;
2137
2138 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2139 mPid = pid;
2140 mListener = listener;
2141 }
2142
2143 @Override
2144 public void binderDied() {
2145 if (DEBUG) {
2146 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2147 }
2148 onTabletModeChangedListenerDied(mPid);
2149 }
2150
2151 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2152 try {
2153 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2154 } catch (RemoteException ex) {
2155 Slog.w(TAG, "Failed to notify process " + mPid +
2156 " that tablet mode changed, assuming it died.", ex);
2157 binderDied();
2158 }
2159 }
2160 }
2161
Jeff Browna47425a2012-04-13 04:09:27 -07002162 private final class VibratorToken implements DeathRecipient {
2163 public final int mDeviceId;
2164 public final IBinder mToken;
2165 public final int mTokenValue;
2166
2167 public boolean mVibrating;
2168
2169 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2170 mDeviceId = deviceId;
2171 mToken = token;
2172 mTokenValue = tokenValue;
2173 }
2174
2175 @Override
2176 public void binderDied() {
2177 if (DEBUG) {
2178 Slog.d(TAG, "Vibrator token died.");
2179 }
2180 onVibratorTokenDied(this);
2181 }
2182 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002183
2184 private final class LocalService extends InputManagerInternal {
2185 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002186 public void setDisplayViewports(List<DisplayViewport> viewports) {
2187 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002188 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002189
2190 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002191 public boolean injectInputEvent(InputEvent event, int mode) {
2192 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002193 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002194
2195 @Override
2196 public void setInteractive(boolean interactive) {
2197 nativeSetInteractive(mPtr, interactive);
2198 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002199
2200 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002201 public void toggleCapsLock(int deviceId) {
2202 nativeToggleCapsLock(mPtr, deviceId);
2203 }
Adrian Roos99182342016-06-15 15:30:46 -07002204
2205 @Override
2206 public void setPulseGestureEnabled(boolean enabled) {
2207 if (mDoubleTouchGestureEnableFile != null) {
2208 FileWriter writer = null;
2209 try {
2210 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2211 writer.write(enabled ? "1" : "0");
2212 } catch (IOException e) {
2213 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2214 } finally {
2215 IoUtils.closeQuietly(writer);
2216 }
2217 }
2218 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002219 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002220}