blob: a70909ff4158c9942a68493cd74ec223a7a82546 [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;
Yohei Yukawab097b822015-12-01 10:43:08 -080020import android.annotation.Nullable;
Yohei Yukawa23cbe852016-05-17 16:42:58 -070021import android.os.LocaleList;
Dianne Hackborn354736e2016-08-22 17:00:05 -070022import android.os.ShellCallback;
Adrian Roos99182342016-06-15 15:30:46 -070023import android.util.Log;
Jeff Brownca9bc702014-02-11 14:32:56 -080024import android.view.Display;
Chris Wren282cfef2017-03-27 15:01:44 -040025import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -050026import com.android.internal.notification.SystemNotificationChannels;
Michael Wright39e5e942015-08-19 22:52:47 +010027import com.android.internal.os.SomeArgs;
Jeff Browncf39bdf2012-05-18 14:41:19 -070028import com.android.internal.R;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060029import com.android.internal.util.DumpUtils;
Michael Wrightb004b512017-01-18 18:09:29 +000030import com.android.internal.util.Preconditions;
Jeff Brown46b9ac02010-04-22 18:58:52 -070031import com.android.internal.util.XmlUtils;
Jeff Brown4ccb8232014-01-16 22:16:42 -080032import com.android.server.DisplayThread;
33import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070034import com.android.server.Watchdog;
Adrian Roose99bc052017-11-20 17:55:31 +010035import com.android.server.policy.WindowManagerPolicy;
Jeff Brown46b9ac02010-04-22 18:58:52 -070036
37import org.xmlpull.v1.XmlPullParser;
38
Jeff Browna3bc5652012-04-17 11:42:25 -070039import android.Manifest;
Andrii Kulianed76e742017-06-26 14:57:02 -070040import android.app.IInputForwarder;
Jeff Browncf39bdf2012-05-18 14:41:19 -070041import android.app.Notification;
42import android.app.NotificationManager;
43import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070044import android.bluetooth.BluetoothAdapter;
45import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070046import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070047import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070048import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070050import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070051import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070052import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070053import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070054import android.content.pm.ResolveInfo;
55import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070056import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070057import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070058import android.content.res.TypedArray;
59import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070060import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070061import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080062import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070063import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070064import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080065import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070066import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080067import android.hardware.input.InputManagerInternal;
Michael Wright39e5e942015-08-19 22:52:47 +010068import android.hardware.input.ITabletModeChangedListener;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070069import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080070import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070071import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070072import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070073import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070074import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070075import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070076import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070077import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080078import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070079import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070080import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070081import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070082import android.provider.Settings;
83import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000084import android.text.TextUtils;
Jeff Brown46b9ac02010-04-22 18:58:52 -070085import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070086import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070087import android.util.Xml;
Andrii Kulianed76e742017-06-26 14:57:02 -070088import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070089import android.view.IInputFilter;
90import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080091import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070092import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070093import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070094import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080095import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070096import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070097import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080098import android.view.ViewConfiguration;
Yohei Yukawab097b822015-12-01 10:43:08 -080099import android.view.inputmethod.InputMethodInfo;
100import android.view.inputmethod.InputMethodSubtype;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800101import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102
Jeff Brown46b9ac02010-04-22 18:58:52 -0700103import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700104import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.FileNotFoundException;
106import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700107import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700108import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700109import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700110import java.io.PrintWriter;
111import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000112import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700113import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700114import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100115import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000116import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000117import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700118
Adrian Roos99182342016-06-15 15:30:46 -0700119import libcore.io.IoUtils;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700120import libcore.io.Streams;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121
122/*
123 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700124 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700125public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800126 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700127 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700128 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700129
Jeff Brown4532e612012-04-05 14:27:12 -0700130 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
131
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700133 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
134 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
135 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
136 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100137 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Yohei Yukawab097b822015-12-01 10:43:08 -0800138 private static final int MSG_INPUT_METHOD_SUBTYPE_CHANGED = 7;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700139
Jeff Brown4532e612012-04-05 14:27:12 -0700140 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000141 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700142
Jeff Brown46b9ac02010-04-22 18:58:52 -0700143 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700144 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700145
Adrian Roos99182342016-06-15 15:30:46 -0700146 private final File mDoubleTouchGestureEnableFile;
147
Jeff Browna9d131c2012-09-20 16:48:17 -0700148 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700149 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700150 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700151 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700152
Michael Wright39e5e942015-08-19 22:52:47 +0100153 private final Object mTabletModeLock = new Object();
154 // List of currently registered tablet mode changed listeners by process id
155 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
156 new SparseArray<>(); // guarded by mTabletModeLock
157 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
158 new ArrayList<>();
159
Jeff Browna3bc5652012-04-17 11:42:25 -0700160 // Persistent data store. Must be locked each time during use.
161 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700162
163 // List of currently registered input devices changed listeners by process id.
164 private Object mInputDevicesLock = new Object();
165 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
166 private InputDevice[] mInputDevices = new InputDevice[0];
167 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
168 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
169 private final ArrayList<InputDevicesChangedListenerRecord>
170 mTempInputDevicesChangedListenersToNotify =
171 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700172 private final ArrayList<InputDevice>
173 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
174 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800175 private PendingIntent mKeyboardLayoutIntent;
176 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177
Jeff Browna47425a2012-04-13 04:09:27 -0700178 // State for vibrator tokens.
179 private Object mVibratorLock = new Object();
180 private HashMap<IBinder, VibratorToken> mVibratorTokens =
181 new HashMap<IBinder, VibratorToken>();
182 private int mNextVibratorTokenValue;
183
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700184 // State for the currently installed input filter.
185 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700186 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700187 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700188
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800189 private IWindow mFocusedWindow;
190 private boolean mFocusedWindowHasCapture;
191
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000192 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700193 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000194 private static native void nativeStart(long ptr);
Santos Cordonee8931e2017-04-05 10:31:15 -0700195 private static native void nativeSetVirtualDisplayViewports(long ptr,
196 DisplayViewport[] viewports);
197 private static native void nativeSetDisplayViewport(long ptr, int viewportType,
Jeff Brownd728bf52012-09-08 18:05:28 -0700198 int displayId, int rotation,
199 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700200 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
Santos Cordonee8931e2017-04-05 10:31:15 -0700201 int deviceWidth, int deviceHeight, String uniqueId);
Jeff Brownd728bf52012-09-08 18:05:28 -0700202
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000203 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700204 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000205 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700206 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000207 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700208 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000209 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700210 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000211 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800212 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000213 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
214 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Jeff Brownca9bc702014-02-11 14:32:56 -0800215 private static native int nativeInjectInputEvent(long ptr, InputEvent event, int displayId,
Jeff Brown0029c662011-03-30 02:25:18 -0700216 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
217 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800218 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
220 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
221 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
222 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700223 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000224 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700225 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000226 private static native void nativeSetPointerSpeed(long ptr, int speed);
227 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700228 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800229 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000230 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700231 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000232 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
233 private static native void nativeReloadKeyboardLayouts(long ptr);
234 private static native void nativeReloadDeviceAliases(long ptr);
235 private static native String nativeDump(long ptr);
236 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700237 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
238 private static native void nativeEnableInputDevice(long ptr, int deviceId);
239 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100240 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800241 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700242 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800243 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700244
Jeff Brownac143512012-04-05 18:57:33 -0700245 // Input event injection constants defined in InputDispatcher.h.
246 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
247 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
248 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
249 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
250
251 // Maximum number of milliseconds to wait for input event injection.
252 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
253
Jeff Brown6d0fec22010-07-23 21:28:06 -0700254 // Key states (may be returned by queries about the current state of a
255 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700256
Jeff Brown6d0fec22010-07-23 21:28:06 -0700257 /** The key state is unknown or the requested key itself is not supported. */
258 public static final int KEY_STATE_UNKNOWN = -1;
259
260 /** The key is up. /*/
261 public static final int KEY_STATE_UP = 0;
262
263 /** The key is down. */
264 public static final int KEY_STATE_DOWN = 1;
265
266 /** The key is down but is a virtual key press that is being emulated by the system. */
267 public static final int KEY_STATE_VIRTUAL = 2;
268
Jeff Brownc458ce92012-04-30 14:58:40 -0700269 /** Scan code: Mouse / trackball button. */
270 public static final int BTN_MOUSE = 0x110;
271
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700272 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700273 /** Switch code: Lid switch. When set, lid is shut. */
274 public static final int SW_LID = 0x00;
275
Michael Wright39e5e942015-08-19 22:52:47 +0100276 /** Switch code: Tablet mode switch.
277 * When set, the device is in tablet mode (i.e. no keyboard is connected).
278 */
279 public static final int SW_TABLET_MODE = 0x01;
280
Jeff Brownc458ce92012-04-30 14:58:40 -0700281 /** Switch code: Keypad slide. When set, keyboard is exposed. */
282 public static final int SW_KEYPAD_SLIDE = 0x0a;
283
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700284 /** Switch code: Headphone. When set, headphone is inserted. */
285 public static final int SW_HEADPHONE_INSERT = 0x02;
286
287 /** Switch code: Microphone. When set, microphone is inserted. */
288 public static final int SW_MICROPHONE_INSERT = 0x04;
289
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500290 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
291 public static final int SW_LINEOUT_INSERT = 0x06;
292
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700293 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
294 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
295
Michael Wright3818c922014-09-02 13:59:07 -0700296 /** Switch code: Camera lens cover. When set the lens is covered. */
297 public static final int SW_CAMERA_LENS_COVER = 0x09;
298
Santos Cordonee8931e2017-04-05 10:31:15 -0700299 // Viewport constants defined in InputReader.h.
300 public static final int VIEWPORT_DEFAULT = 1;
301 public static final int VIEWPORT_EXTERNAL = 2;
302 public static final int VIEWPORT_VIRTUAL = 3;
303
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700304 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100305 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700306 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
307 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
308 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500309 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700310 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
311 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500312 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700313 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700314
315 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
316 final boolean mUseDevInputEventForAudioJack;
317
Jeff Brown4ccb8232014-01-16 22:16:42 -0800318 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700319 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800320 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800321
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700322 mUseDevInputEventForAudioJack =
323 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
324 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
325 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700326 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800327
Adrian Roos99182342016-06-15 15:30:46 -0700328 String doubleTouchGestureEnablePath = context.getResources().getString(
329 R.string.config_doubleTouchGestureEnableFile);
330 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
331 new File(doubleTouchGestureEnablePath);
332
Jeff Brown4ccb8232014-01-16 22:16:42 -0800333 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700334 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700335
Jeff Browna9d131c2012-09-20 16:48:17 -0700336 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
337 mWindowManagerCallbacks = callbacks;
338 }
339
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700340 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
341 mWiredAccessoryCallbacks = callbacks;
342 }
343
Jeff Brown46b9ac02010-04-22 18:58:52 -0700344 public void start() {
345 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700346 nativeStart(mPtr);
347
348 // Add ourself to the Watchdog monitors.
349 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700350
351 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700352 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800353 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700354
Jeff Brownd4935962012-09-25 13:27:20 -0700355 mContext.registerReceiver(new BroadcastReceiver() {
356 @Override
357 public void onReceive(Context context, Intent intent) {
358 updatePointerSpeedFromSettings();
359 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800360 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700361 }
362 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
363
Jeff Brown1a84fd12011-06-02 01:26:32 -0700364 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700365 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800366 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700367 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700368
Matthew Xie96313142012-06-29 16:57:31 -0700369 // TODO(BT) Pass in paramter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700370 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700371 if (DEBUG) {
372 Slog.d(TAG, "System ready.");
373 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700374 mNotificationManager = (NotificationManager)mContext.getSystemService(
375 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700376 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700377
378 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
379 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
380 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800381 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700382 filter.addDataScheme("package");
383 mContext.registerReceiver(new BroadcastReceiver() {
384 @Override
385 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700386 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700387 }
388 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700389
390 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
391 mContext.registerReceiver(new BroadcastReceiver() {
392 @Override
393 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700394 reloadDeviceAliases();
395 }
396 }, filter, null, mHandler);
397
Jeff Browncf39bdf2012-05-18 14:41:19 -0700398 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
399 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700400
401 if (mWiredAccessoryCallbacks != null) {
402 mWiredAccessoryCallbacks.systemReady();
403 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700404 }
405
406 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700407 if (DEBUG) {
408 Slog.d(TAG, "Reloading keyboard layouts.");
409 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700410 nativeReloadKeyboardLayouts(mPtr);
411 }
412
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700413 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700414 if (DEBUG) {
415 Slog.d(TAG, "Reloading device names.");
416 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700417 nativeReloadDeviceAliases(mPtr);
418 }
419
Jeff Brown4ccb8232014-01-16 22:16:42 -0800420 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Santos Cordonee8931e2017-04-05 10:31:15 -0700421 DisplayViewport externalTouchViewport,
422 List<DisplayViewport> virtualTouchViewports) {
Jeff Brownd728bf52012-09-08 18:05:28 -0700423 if (defaultViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700424 setDisplayViewport(VIEWPORT_DEFAULT, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700426
427 if (externalTouchViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700428 setDisplayViewport(VIEWPORT_EXTERNAL, externalTouchViewport);
Jeff Brownd728bf52012-09-08 18:05:28 -0700429 } else if (defaultViewport.valid) {
Santos Cordonee8931e2017-04-05 10:31:15 -0700430 setDisplayViewport(VIEWPORT_EXTERNAL, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700431 }
Santos Cordonee8931e2017-04-05 10:31:15 -0700432
433 nativeSetVirtualDisplayViewports(mPtr,
434 virtualTouchViewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700435 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700436
Santos Cordonee8931e2017-04-05 10:31:15 -0700437 private void setDisplayViewport(int viewportType, DisplayViewport viewport) {
438 nativeSetDisplayViewport(mPtr, viewportType,
Jeff Brownd728bf52012-09-08 18:05:28 -0700439 viewport.displayId, viewport.orientation,
440 viewport.logicalFrame.left, viewport.logicalFrame.top,
441 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
442 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700443 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
Santos Cordonee8931e2017-04-05 10:31:15 -0700444 viewport.deviceWidth, viewport.deviceHeight, viewport.uniqueId);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700445 }
Jeff Brownac143512012-04-05 18:57:33 -0700446
Jeff Brown6d0fec22010-07-23 21:28:06 -0700447 /**
448 * Gets the current state of a key or button by key code.
449 * @param deviceId The input device id, or -1 to consult all devices.
450 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
451 * consider all input sources. An input device is consulted if at least one of its
452 * non-class input source bits matches the specified source mask.
453 * @param keyCode The key code to check.
454 * @return The key state.
455 */
456 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700457 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700458 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700459
Jeff Brown6d0fec22010-07-23 21:28:06 -0700460 /**
461 * Gets the current state of a key or button by scan code.
462 * @param deviceId The input device id, or -1 to consult all devices.
463 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
464 * consider all input sources. An input device is consulted if at least one of its
465 * non-class input source bits matches the specified source mask.
466 * @param scanCode The scan code to check.
467 * @return The key state.
468 */
469 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700470 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700471 }
RoboErikfb290df2013-12-16 11:27:55 -0800472
Jeff Brown6d0fec22010-07-23 21:28:06 -0700473 /**
474 * Gets the current state of a switch by switch code.
475 * @param deviceId The input device id, or -1 to consult all devices.
476 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
477 * consider all input sources. An input device is consulted if at least one of its
478 * non-class input source bits matches the specified source mask.
479 * @param switchCode The switch code to check.
480 * @return The switch state.
481 */
482 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700483 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700484 }
485
Jeff Brown6d0fec22010-07-23 21:28:06 -0700486 /**
487 * Determines whether the specified key codes are supported by a particular device.
488 * @param deviceId The input device id, or -1 to consult all devices.
489 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
490 * consider all input sources. An input device is consulted if at least one of its
491 * non-class input source bits matches the specified source mask.
492 * @param keyCodes The array of key codes to check.
493 * @param keyExists An array at least as large as keyCodes whose entries will be set
494 * to true or false based on the presence or absence of support for the corresponding
495 * key codes.
496 * @return True if the lookup was successful, false otherwise.
497 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700498 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700499 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700500 if (keyCodes == null) {
501 throw new IllegalArgumentException("keyCodes must not be null.");
502 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700503 if (keyExists == null || keyExists.length < keyCodes.length) {
504 throw new IllegalArgumentException("keyExists must not be null and must be at "
505 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700506 }
RoboErikfb290df2013-12-16 11:27:55 -0800507
Jeff Brown4532e612012-04-05 14:27:12 -0700508 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700509 }
RoboErikfb290df2013-12-16 11:27:55 -0800510
Jeff Browna41ca772010-08-11 14:46:32 -0700511 /**
512 * Creates an input channel that will receive all input from the input dispatcher.
513 * @param inputChannelName The input channel name.
514 * @return The input channel.
515 */
516 public InputChannel monitorInput(String inputChannelName) {
517 if (inputChannelName == null) {
518 throw new IllegalArgumentException("inputChannelName must not be null.");
519 }
RoboErikfb290df2013-12-16 11:27:55 -0800520
Jeff Browna41ca772010-08-11 14:46:32 -0700521 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700522 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700523 inputChannels[0].dispose(); // don't need to retain the Java object reference
524 return inputChannels[1];
525 }
526
527 /**
528 * Registers an input channel so that it can be used as an input event target.
529 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800530 * @param inputWindowHandle The handle of the input window associated with the
531 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700532 */
Jeff Brown928e0542011-01-10 11:17:36 -0800533 public void registerInputChannel(InputChannel inputChannel,
534 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700535 if (inputChannel == null) {
536 throw new IllegalArgumentException("inputChannel must not be null.");
537 }
RoboErikfb290df2013-12-16 11:27:55 -0800538
Jeff Brown4532e612012-04-05 14:27:12 -0700539 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700540 }
RoboErikfb290df2013-12-16 11:27:55 -0800541
Jeff Browna41ca772010-08-11 14:46:32 -0700542 /**
543 * Unregisters an input channel.
544 * @param inputChannel The input channel to unregister.
545 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700546 public void unregisterInputChannel(InputChannel inputChannel) {
547 if (inputChannel == null) {
548 throw new IllegalArgumentException("inputChannel must not be null.");
549 }
RoboErikfb290df2013-12-16 11:27:55 -0800550
Jeff Brown4532e612012-04-05 14:27:12 -0700551 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700552 }
Jeff Brown0029c662011-03-30 02:25:18 -0700553
554 /**
555 * Sets an input filter that will receive all input events before they are dispatched.
556 * The input filter may then reinterpret input events or inject new ones.
557 *
558 * To ensure consistency, the input dispatcher automatically drops all events
559 * in progress whenever an input filter is installed or uninstalled. After an input
560 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
561 * Any events it attempts to send after it has been uninstalled will be dropped.
562 *
563 * @param filter The input filter, or null to remove the current filter.
564 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700565 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700566 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700567 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700568 if (oldFilter == filter) {
569 return; // nothing to do
570 }
571
572 if (oldFilter != null) {
573 mInputFilter = null;
574 mInputFilterHost.disconnectLocked();
575 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700576 try {
577 oldFilter.uninstall();
578 } catch (RemoteException re) {
579 /* ignore */
580 }
Jeff Brown0029c662011-03-30 02:25:18 -0700581 }
582
583 if (filter != null) {
584 mInputFilter = filter;
585 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700586 try {
587 filter.install(mInputFilterHost);
588 } catch (RemoteException re) {
589 /* ignore */
590 }
Jeff Brown0029c662011-03-30 02:25:18 -0700591 }
592
Jeff Brown4532e612012-04-05 14:27:12 -0700593 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700594 }
595 }
596
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700597 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700598 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brownca9bc702014-02-11 14:32:56 -0800599 return injectInputEventInternal(event, Display.DEFAULT_DISPLAY, mode);
600 }
601
602 private boolean injectInputEventInternal(InputEvent event, int displayId, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700603 if (event == null) {
604 throw new IllegalArgumentException("event must not be null");
605 }
Jeff Brownac143512012-04-05 18:57:33 -0700606 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
607 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
608 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
609 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700610 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700611
Jeff Brownac143512012-04-05 18:57:33 -0700612 final int pid = Binder.getCallingPid();
613 final int uid = Binder.getCallingUid();
614 final long ident = Binder.clearCallingIdentity();
615 final int result;
616 try {
Jeff Brownca9bc702014-02-11 14:32:56 -0800617 result = nativeInjectInputEvent(mPtr, event, displayId, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700618 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
619 } finally {
620 Binder.restoreCallingIdentity(ident);
621 }
622 switch (result) {
623 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
624 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
625 throw new SecurityException(
626 "Injecting to another application requires INJECT_EVENTS permission");
627 case INPUT_EVENT_INJECTION_SUCCEEDED:
628 return true;
629 case INPUT_EVENT_INJECTION_TIMED_OUT:
630 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
631 return false;
632 case INPUT_EVENT_INJECTION_FAILED:
633 default:
634 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
635 return false;
636 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700637 }
Jeff Brown0029c662011-03-30 02:25:18 -0700638
Jeff Brown8d608662010-08-30 03:02:23 -0700639 /**
640 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700641 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700642 * @return The input device or null if not found.
643 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700644 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700645 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700646 synchronized (mInputDevicesLock) {
647 final int count = mInputDevices.length;
648 for (int i = 0; i < count; i++) {
649 final InputDevice inputDevice = mInputDevices[i];
650 if (inputDevice.getId() == deviceId) {
651 return inputDevice;
652 }
653 }
654 }
655 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700656 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700657
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700658 // Binder call
659 @Override
660 public boolean isInputDeviceEnabled(int deviceId) {
661 return nativeIsInputDeviceEnabled(mPtr, deviceId);
662 }
663
664 // Binder call
665 @Override
666 public void enableInputDevice(int deviceId) {
667 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
668 "enableInputDevice()")) {
669 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
670 }
671 nativeEnableInputDevice(mPtr, deviceId);
672 }
673
674 // Binder call
675 @Override
676 public void disableInputDevice(int deviceId) {
677 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
678 "disableInputDevice()")) {
679 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
680 }
681 nativeDisableInputDevice(mPtr, deviceId);
682 }
683
Jeff Brown8d608662010-08-30 03:02:23 -0700684 /**
685 * Gets the ids of all input devices in the system.
686 * @return The input device ids.
687 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700688 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700689 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700690 synchronized (mInputDevicesLock) {
691 final int count = mInputDevices.length;
692 int[] ids = new int[count];
693 for (int i = 0; i < count; i++) {
694 ids[i] = mInputDevices[i].getId();
695 }
696 return ids;
697 }
698 }
699
Jeff Browndaa37532012-05-01 15:54:03 -0700700 /**
701 * Gets all input devices in the system.
702 * @return The array of input devices.
703 */
704 public InputDevice[] getInputDevices() {
705 synchronized (mInputDevicesLock) {
706 return mInputDevices;
707 }
708 }
709
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700710 @Override // Binder call
711 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
712 if (listener == null) {
713 throw new IllegalArgumentException("listener must not be null");
714 }
715
716 synchronized (mInputDevicesLock) {
717 int callingPid = Binder.getCallingPid();
718 if (mInputDevicesChangedListeners.get(callingPid) != null) {
719 throw new SecurityException("The calling process has already "
720 + "registered an InputDevicesChangedListener.");
721 }
722
723 InputDevicesChangedListenerRecord record =
724 new InputDevicesChangedListenerRecord(callingPid, listener);
725 try {
726 IBinder binder = listener.asBinder();
727 binder.linkToDeath(record, 0);
728 } catch (RemoteException ex) {
729 // give up
730 throw new RuntimeException(ex);
731 }
732
733 mInputDevicesChangedListeners.put(callingPid, record);
734 }
735 }
736
737 private void onInputDevicesChangedListenerDied(int pid) {
738 synchronized (mInputDevicesLock) {
739 mInputDevicesChangedListeners.remove(pid);
740 }
741 }
742
743 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700744 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
745 // Scan for changes.
746 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700747 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700748 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700749 final int numListeners;
750 final int[] deviceIdAndGeneration;
751 synchronized (mInputDevicesLock) {
752 if (!mInputDevicesChangedPending) {
753 return;
754 }
755 mInputDevicesChangedPending = false;
756
757 numListeners = mInputDevicesChangedListeners.size();
758 for (int i = 0; i < numListeners; i++) {
759 mTempInputDevicesChangedListenersToNotify.add(
760 mInputDevicesChangedListeners.valueAt(i));
761 }
762
763 final int numDevices = mInputDevices.length;
764 deviceIdAndGeneration = new int[numDevices * 2];
765 for (int i = 0; i < numDevices; i++) {
766 final InputDevice inputDevice = mInputDevices[i];
767 deviceIdAndGeneration[i * 2] = inputDevice.getId();
768 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700769
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700770 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700771 if (!containsInputDeviceWithDescriptor(oldInputDevices,
772 inputDevice.getDescriptor())) {
773 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
774 } else {
775 mTempFullKeyboards.add(inputDevice);
776 }
777 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700778 }
779 }
780
Jeff Browncf39bdf2012-05-18 14:41:19 -0700781 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700782 for (int i = 0; i < numListeners; i++) {
783 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
784 deviceIdAndGeneration);
785 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700786 mTempInputDevicesChangedListenersToNotify.clear();
787
788 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000789 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
790 final int numFullKeyboards = mTempFullKeyboards.size();
791 synchronized (mDataStore) {
792 for (int i = 0; i < numFullKeyboards; i++) {
793 final InputDevice inputDevice = mTempFullKeyboards.get(i);
794 String layout =
795 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
796 if (layout == null) {
797 layout = getDefaultKeyboardLayout(inputDevice);
798 if (layout != null) {
799 setCurrentKeyboardLayoutForInputDevice(
800 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700801 }
802 }
Michael Wright07483422015-10-30 16:20:13 +0000803 if (layout == null) {
804 keyboardsMissingLayout.add(inputDevice);
805 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700806 }
Michael Wright07483422015-10-30 16:20:13 +0000807 }
808
809 if (mNotificationManager != null) {
810 if (!keyboardsMissingLayout.isEmpty()) {
811 if (keyboardsMissingLayout.size() > 1) {
812 // We have more than one keyboard missing a layout, so drop the
813 // user at the generic input methods page so they can pick which
814 // one to set.
815 showMissingKeyboardLayoutNotification(null);
816 } else {
817 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700818 }
819 } else if (mKeyboardLayoutNotificationShown) {
820 hideMissingKeyboardLayoutNotification();
821 }
822 }
823 mTempFullKeyboards.clear();
824 }
825
Michael Wright07483422015-10-30 16:20:13 +0000826 private String getDefaultKeyboardLayout(final InputDevice d) {
827 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
828 // If our locale doesn't have a language for some reason, then we don't really have a
829 // reasonable default.
830 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
831 return null;
832 }
833 final List<KeyboardLayout> layouts = new ArrayList<>();
834 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
835 @Override
836 public void visitKeyboardLayout(Resources resources,
837 int keyboardLayoutResId, KeyboardLayout layout) {
838 // Only select a default when we know the layout is appropriate. For now, this
839 // means its a custom layout for a specific keyboard.
840 if (layout.getVendorId() != d.getVendorId()
841 || layout.getProductId() != d.getProductId()) {
842 return;
843 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800844 final LocaleList locales = layout.getLocales();
845 final int numLocales = locales.size();
846 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
847 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000848 layouts.add(layout);
849 break;
850 }
851 }
852 }
853 });
854
855 if (layouts.isEmpty()) {
856 return null;
857 }
858
859 // First sort so that ones with higher priority are listed at the top
860 Collections.sort(layouts);
861 // Next we want to try to find an exact match of language, country and variant.
862 final int N = layouts.size();
863 for (int i = 0; i < N; i++) {
864 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800865 final LocaleList locales = layout.getLocales();
866 final int numLocales = locales.size();
867 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
868 final Locale locale = locales.get(localeIndex);
869 if (locale.getCountry().equals(systemLocale.getCountry())
870 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000871 return layout.getDescriptor();
872 }
873 }
874 }
875 // Then try an exact match of language and country
876 for (int i = 0; i < N; i++) {
877 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800878 final LocaleList locales = layout.getLocales();
879 final int numLocales = locales.size();
880 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
881 final Locale locale = locales.get(localeIndex);
882 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000883 return layout.getDescriptor();
884 }
885 }
886 }
887
888 // Give up and just use the highest priority layout with matching language
889 return layouts.get(0).getDescriptor();
890 }
891
892 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
893 // Different languages are never compatible
894 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
895 return false;
896 }
897 // If both the system and the keyboard layout have a country specifier, they must be equal.
898 if (!TextUtils.isEmpty(systemLocale.getCountry())
899 && !TextUtils.isEmpty(keyboardLocale.getCountry())
900 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
901 return false;
902 }
903 return true;
904 }
905
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800906 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700907 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
908 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800909 if (inputDeviceDescriptor == null) {
910 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
911 }
912
913 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700914 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800915 }
916 }
917
918 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700919 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800920 TouchCalibration calibration) {
921 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
922 "setTouchCalibrationForInputDevice()")) {
923 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
924 }
925 if (inputDeviceDescriptor == null) {
926 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
927 }
928 if (calibration == null) {
929 throw new IllegalArgumentException("calibration must not be null");
930 }
Jason Gerecked5220742014-03-10 09:47:59 -0700931 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
932 throw new IllegalArgumentException("surfaceRotation value out of bounds");
933 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800934
935 synchronized (mDataStore) {
936 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700937 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
938 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800939 nativeReloadCalibration(mPtr);
940 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800941 } finally {
942 mDataStore.saveIfNeeded();
943 }
944 }
945 }
946
Michael Wright39e5e942015-08-19 22:52:47 +0100947 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100948 public int isInTabletMode() {
949 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
950 "isInTabletMode()")) {
951 throw new SecurityException("Requires TABLET_MODE permission");
952 }
953 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
954 }
955
956 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100957 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100958 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100959 "registerTabletModeChangedListener()")) {
960 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
961 }
962 if (listener == null) {
963 throw new IllegalArgumentException("listener must not be null");
964 }
965
966 synchronized (mTabletModeLock) {
967 final int callingPid = Binder.getCallingPid();
968 if (mTabletModeChangedListeners.get(callingPid) != null) {
969 throw new IllegalStateException("The calling process has already registered "
970 + "a TabletModeChangedListener.");
971 }
972 TabletModeChangedListenerRecord record =
973 new TabletModeChangedListenerRecord(callingPid, listener);
974 try {
975 IBinder binder = listener.asBinder();
976 binder.linkToDeath(record, 0);
977 } catch (RemoteException ex) {
978 throw new RuntimeException(ex);
979 }
980 mTabletModeChangedListeners.put(callingPid, record);
981 }
982 }
983
984 private void onTabletModeChangedListenerDied(int pid) {
985 synchronized (mTabletModeLock) {
986 mTabletModeChangedListeners.remove(pid);
987 }
988 }
989
990 // Must be called on handler
991 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
992 mTempTabletModeChangedListenersToNotify.clear();
993 final int numListeners;
994 synchronized (mTabletModeLock) {
995 numListeners = mTabletModeChangedListeners.size();
996 for (int i = 0; i < numListeners; i++) {
997 mTempTabletModeChangedListenersToNotify.add(
998 mTabletModeChangedListeners.valueAt(i));
999 }
1000 }
1001 for (int i = 0; i < numListeners; i++) {
1002 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
1003 whenNanos, inTabletMode);
1004 }
1005 }
1006
Jeff Browncf39bdf2012-05-18 14:41:19 -07001007 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -07001008 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001009 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -07001010 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -07001011 if (device != null) {
1012 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001013 }
Michael Wrightc93fbd12014-09-22 20:07:59 -07001014 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1015 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
1016 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
1017 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
1018 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001019
1020 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001021 Notification notification =
1022 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
1023 .setContentTitle(r.getString(
1024 R.string.select_keyboard_layout_notification_title))
1025 .setContentText(r.getString(
1026 R.string.select_keyboard_layout_notification_message))
1027 .setContentIntent(keyboardLayoutIntent)
1028 .setSmallIcon(R.drawable.ic_settings_language)
1029 .setColor(mContext.getColor(
1030 com.android.internal.R.color.system_notification_accent_color))
1031 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001032 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001033 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001034 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001035 mKeyboardLayoutNotificationShown = true;
1036 }
1037 }
1038
1039 // Must be called on handler.
1040 private void hideMissingKeyboardLayoutNotification() {
1041 if (mKeyboardLayoutNotificationShown) {
1042 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001043 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001044 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001045 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001046 }
1047 }
1048
1049 // Must be called on handler.
1050 private void updateKeyboardLayouts() {
1051 // Scan all input devices state for keyboard layouts that have been uninstalled.
1052 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1053 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1054 @Override
Michael Wright07483422015-10-30 16:20:13 +00001055 public void visitKeyboardLayout(Resources resources,
1056 int keyboardLayoutResId, KeyboardLayout layout) {
1057 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001058 }
1059 });
1060 synchronized (mDataStore) {
1061 try {
1062 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1063 } finally {
1064 mDataStore.saveIfNeeded();
1065 }
1066 }
1067
1068 // Reload keyboard layouts.
1069 reloadKeyboardLayouts();
1070 }
1071
Jeff Browncf39bdf2012-05-18 14:41:19 -07001072 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1073 String descriptor) {
1074 final int numDevices = inputDevices.length;
1075 for (int i = 0; i < numDevices; i++) {
1076 final InputDevice inputDevice = inputDevices[i];
1077 if (inputDevice.getDescriptor().equals(descriptor)) {
1078 return true;
1079 }
1080 }
1081 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001082 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001083
1084 @Override // Binder call
1085 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001086 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1087 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1088 @Override
Michael Wright07483422015-10-30 16:20:13 +00001089 public void visitKeyboardLayout(Resources resources,
1090 int keyboardLayoutResId, KeyboardLayout layout) {
1091 list.add(layout);
1092 }
1093 });
1094 return list.toArray(new KeyboardLayout[list.size()]);
1095 }
1096
Michael Wrightb0e804a2016-01-04 16:48:53 -05001097 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001098 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1099 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001100 final String[] enabledLayoutDescriptors =
1101 getEnabledKeyboardLayoutsForInputDevice(identifier);
1102 final ArrayList<KeyboardLayout> enabledLayouts =
1103 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1104 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001105 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1106 boolean mHasSeenDeviceSpecificLayout;
1107
1108 @Override
1109 public void visitKeyboardLayout(Resources resources,
1110 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001111 // First check if it's enabled. If the keyboard layout is enabled then we always
1112 // want to return it as a possible layout for the device.
1113 for (String s : enabledLayoutDescriptors) {
1114 if (s != null && s.equals(layout.getDescriptor())) {
1115 enabledLayouts.add(layout);
1116 return;
1117 }
1118 }
1119 // Next find any potential layouts that aren't yet enabled for the device. For
1120 // devices that have special layouts we assume there's a reason that the generic
1121 // layouts don't work for them so we don't want to return them since it's likely
1122 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001123 if (layout.getVendorId() == identifier.getVendorId()
1124 && layout.getProductId() == identifier.getProductId()) {
1125 if (!mHasSeenDeviceSpecificLayout) {
1126 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001127 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001128 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001129 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001130 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1131 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001132 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001133 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001134 }
1135 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001136 final int enabledLayoutSize = enabledLayouts.size();
1137 final int potentialLayoutSize = potentialLayouts.size();
1138 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1139 enabledLayouts.toArray(layouts);
1140 for (int i = 0; i < potentialLayoutSize; i++) {
1141 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1142 }
1143 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001144 }
1145
1146 @Override // Binder call
1147 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1148 if (keyboardLayoutDescriptor == null) {
1149 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1150 }
1151
Jeff Brown6ec6f792012-04-17 16:52:41 -07001152 final KeyboardLayout[] result = new KeyboardLayout[1];
1153 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1154 @Override
Michael Wright07483422015-10-30 16:20:13 +00001155 public void visitKeyboardLayout(Resources resources,
1156 int keyboardLayoutResId, KeyboardLayout layout) {
1157 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001158 }
1159 });
1160 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001161 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001162 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001163 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001164 return result[0];
1165 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001166
Jeff Brown6ec6f792012-04-17 16:52:41 -07001167 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001168 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001169 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1170 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001171 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1172 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001173 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1174 final int priority = resolveInfo.priority;
1175 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001176 }
1177 }
1178
Jeff Brown6ec6f792012-04-17 16:52:41 -07001179 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1180 KeyboardLayoutVisitor visitor) {
1181 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1182 if (d != null) {
1183 final PackageManager pm = mContext.getPackageManager();
1184 try {
1185 ActivityInfo receiver = pm.getReceiverInfo(
1186 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001187 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001188 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1189 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001190 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001191 } catch (NameNotFoundException ex) {
1192 }
1193 }
1194 }
1195
1196 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001197 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001198 Bundle metaData = receiver.metaData;
1199 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001200 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001201 }
1202
1203 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1204 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001205 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001206 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001207 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001208 }
1209
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001210 CharSequence receiverLabel = receiver.loadLabel(pm);
1211 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001212 int priority;
1213 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1214 priority = requestedPriority;
1215 } else {
1216 priority = 0;
1217 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001218
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001219 try {
1220 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1221 XmlResourceParser parser = resources.getXml(configResId);
1222 try {
1223 XmlUtils.beginDocument(parser, "keyboard-layouts");
1224
1225 for (;;) {
1226 XmlUtils.nextElement(parser);
1227 String element = parser.getName();
1228 if (element == null) {
1229 break;
1230 }
1231 if (element.equals("keyboard-layout")) {
1232 TypedArray a = resources.obtainAttributes(
1233 parser, com.android.internal.R.styleable.KeyboardLayout);
1234 try {
1235 String name = a.getString(
1236 com.android.internal.R.styleable.KeyboardLayout_name);
1237 String label = a.getString(
1238 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001239 int keyboardLayoutResId = a.getResourceId(
1240 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1241 0);
Michael Wright07483422015-10-30 16:20:13 +00001242 String languageTags = a.getString(
1243 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001244 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001245 int vid = a.getInt(
1246 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1247 int pid = a.getInt(
1248 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1249
Jeff Brown2f095762012-05-10 21:29:33 -07001250 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001251 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001252 + "attributes in keyboard layout "
1253 + "resource from receiver "
1254 + receiver.packageName + "/" + receiver.name);
1255 } else {
1256 String descriptor = KeyboardLayoutDescriptor.format(
1257 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001258 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001259 KeyboardLayout layout = new KeyboardLayout(
1260 descriptor, label, collection, priority,
1261 locales, vid, pid);
1262 visitor.visitKeyboardLayout(
1263 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001264 }
1265 }
1266 } finally {
1267 a.recycle();
1268 }
1269 } else {
Michael Wright07483422015-10-30 16:20:13 +00001270 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001271 + "' in keyboard layout resource from receiver "
1272 + receiver.packageName + "/" + receiver.name);
1273 }
1274 }
1275 } finally {
1276 parser.close();
1277 }
1278 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001279 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001280 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001281 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001282 }
1283
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001284 @NonNull
1285 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001286 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001287 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001288 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001289 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001290 }
1291
RoboErikfb290df2013-12-16 11:27:55 -08001292 /**
1293 * Builds a layout descriptor for the vendor/product. This returns the
1294 * descriptor for ids that aren't useful (such as the default 0, 0).
1295 */
1296 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1297 if (identifier == null || identifier.getDescriptor() == null) {
1298 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001299 }
1300
RoboErikfb290df2013-12-16 11:27:55 -08001301 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1302 return identifier.getDescriptor();
1303 }
1304 StringBuilder bob = new StringBuilder();
1305 bob.append("vendor:").append(identifier.getVendorId());
1306 bob.append(",product:").append(identifier.getProductId());
1307 return bob.toString();
1308 }
1309
1310 @Override // Binder call
1311 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1312
1313 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001314 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001315 String layout = null;
1316 // try loading it using the layout descriptor if we have it
1317 layout = mDataStore.getCurrentKeyboardLayout(key);
1318 if (layout == null && !key.equals(identifier.getDescriptor())) {
1319 // if it doesn't exist fall back to the device descriptor
1320 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1321 }
1322 if (DEBUG) {
1323 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1324 + layout);
1325 }
1326 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001327 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001328 }
1329
1330 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001331 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001332 String keyboardLayoutDescriptor) {
1333 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001334 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001335 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1336 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001337 if (keyboardLayoutDescriptor == null) {
1338 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1339 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001340
RoboErikfb290df2013-12-16 11:27:55 -08001341 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001342 synchronized (mDataStore) {
1343 try {
RoboErikfb290df2013-12-16 11:27:55 -08001344 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1345 if (DEBUG) {
1346 Slog.d(TAG, "Saved keyboard layout using " + key);
1347 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001348 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1349 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001350 } finally {
1351 mDataStore.saveIfNeeded();
1352 }
1353 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001354 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001355
Jeff Browncf39bdf2012-05-18 14:41:19 -07001356 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001357 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001358 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001359 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001360 String[] layouts = mDataStore.getKeyboardLayouts(key);
1361 if ((layouts == null || layouts.length == 0)
1362 && !key.equals(identifier.getDescriptor())) {
1363 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1364 }
1365 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001366 }
1367 }
1368
1369 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001370 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001371 String keyboardLayoutDescriptor) {
1372 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1373 "addKeyboardLayoutForInputDevice()")) {
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 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001388 && !Objects.equals(oldLayout,
1389 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001390 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1391 }
1392 } finally {
1393 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001394 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001395 }
1396 }
1397
1398 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001399 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001400 String keyboardLayoutDescriptor) {
1401 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1402 "removeKeyboardLayoutForInputDevice()")) {
1403 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1404 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001405 if (keyboardLayoutDescriptor == null) {
1406 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1407 }
1408
RoboErikfb290df2013-12-16 11:27:55 -08001409 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001410 synchronized (mDataStore) {
1411 try {
RoboErikfb290df2013-12-16 11:27:55 -08001412 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1413 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1414 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1415 }
1416 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1417 if (!key.equals(identifier.getDescriptor())) {
1418 // We need to remove from both places to ensure it is gone
1419 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1420 keyboardLayoutDescriptor);
1421 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001422 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001423 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001424 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1425 }
1426 } finally {
1427 mDataStore.saveIfNeeded();
1428 }
1429 }
1430 }
1431
Yohei Yukawab097b822015-12-01 10:43:08 -08001432 // Must be called on handler.
1433 private void handleSwitchInputMethodSubtype(int userId,
1434 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1435 if (DEBUG) {
1436 Slog.i(TAG, "InputMethodSubtype changed: userId=" + userId
1437 + " ime=" + inputMethodInfo + " subtype=" + subtype);
1438 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001439 }
1440
1441 public void switchKeyboardLayout(int deviceId, int direction) {
1442 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001443 }
1444
1445 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001446 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1447 final InputDevice device = getInputDevice(deviceId);
1448 if (device != null) {
1449 final boolean changed;
1450 final String keyboardLayoutDescriptor;
1451
1452 String key = getLayoutDescriptor(device.getIdentifier());
1453 synchronized (mDataStore) {
1454 try {
1455 changed = mDataStore.switchKeyboardLayout(key, direction);
1456 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1457 key);
1458 } finally {
1459 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001460 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001461 }
1462
1463 if (changed) {
1464 if (mSwitchedKeyboardLayoutToast != null) {
1465 mSwitchedKeyboardLayoutToast.cancel();
1466 mSwitchedKeyboardLayoutToast = null;
1467 }
1468 if (keyboardLayoutDescriptor != null) {
1469 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1470 if (keyboardLayout != null) {
1471 mSwitchedKeyboardLayoutToast = Toast.makeText(
1472 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1473 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001474 }
1475 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001476
1477 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001478 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001479 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001480 }
1481
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001482 public void setInputWindows(InputWindowHandle[] windowHandles,
1483 InputWindowHandle focusedWindowHandle) {
1484 final IWindow newFocusedWindow =
1485 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1486 if (mFocusedWindow != newFocusedWindow) {
1487 mFocusedWindow = newFocusedWindow;
1488 if (mFocusedWindowHasCapture) {
1489 setPointerCapture(false);
1490 }
1491 }
Jeff Brown4532e612012-04-05 14:27:12 -07001492 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001493 }
RoboErikfb290df2013-12-16 11:27:55 -08001494
Jeff Brown9302c872011-07-13 22:51:29 -07001495 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001496 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001497 }
RoboErikfb290df2013-12-16 11:27:55 -08001498
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001499 @Override
1500 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1501 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1502 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1503 + windowToken);
1504 return;
1505 }
1506 if (mFocusedWindowHasCapture == enabled) {
1507 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1508 return;
1509 }
1510 setPointerCapture(enabled);
1511 try {
1512 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1513 } catch (RemoteException ex) {
1514 /* ignore */
1515 }
1516 }
1517
1518 private void setPointerCapture(boolean enabled) {
1519 mFocusedWindowHasCapture = enabled;
1520 nativeSetPointerCapture(mPtr, enabled);
1521 }
1522
Jeff Brown349703e2010-06-22 01:27:15 -07001523 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001524 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001525 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001526
1527 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001528 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001529 }
1530
Jeff Browne6504122010-09-27 14:52:15 -07001531 /**
1532 * Atomically transfers touch focus from one window to another as identified by
1533 * their input channels. It is possible for multiple windows to have
1534 * touch focus if they support split touch dispatch
1535 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1536 * method only transfers touch focus of the specified window without affecting
1537 * other windows that may also have touch focus at the same time.
1538 * @param fromChannel The channel of a window that currently has touch focus.
1539 * @param toChannel The channel of the window that should receive touch focus in
1540 * place of the first.
1541 * @return True if the transfer was successful. False if the window with the
1542 * specified channel did not actually have touch focus at the time of the request.
1543 */
1544 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1545 if (fromChannel == null) {
1546 throw new IllegalArgumentException("fromChannel must not be null.");
1547 }
1548 if (toChannel == null) {
1549 throw new IllegalArgumentException("toChannel must not be null.");
1550 }
Jeff Brown4532e612012-04-05 14:27:12 -07001551 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001552 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001553
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001554 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001555 public void tryPointerSpeed(int speed) {
1556 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1557 "tryPointerSpeed()")) {
1558 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1559 }
1560
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001561 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1562 throw new IllegalArgumentException("speed out of range");
1563 }
1564
Jeff Brownac143512012-04-05 18:57:33 -07001565 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001566 }
1567
1568 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001569 int speed = getPointerSpeedSetting();
1570 setPointerSpeedUnchecked(speed);
1571 }
1572
1573 private void setPointerSpeedUnchecked(int speed) {
1574 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1575 InputManager.MAX_POINTER_SPEED);
1576 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001577 }
1578
1579 private void registerPointerSpeedSettingObserver() {
1580 mContext.getContentResolver().registerContentObserver(
1581 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001582 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001583 @Override
1584 public void onChange(boolean selfChange) {
1585 updatePointerSpeedFromSettings();
1586 }
Jeff Brownd4935962012-09-25 13:27:20 -07001587 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001588 }
1589
Jeff Brownac143512012-04-05 18:57:33 -07001590 private int getPointerSpeedSetting() {
1591 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001592 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001593 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1594 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001595 } catch (SettingNotFoundException snfe) {
1596 }
1597 return speed;
1598 }
1599
Jeff Browndaf4a122011-08-26 17:14:14 -07001600 public void updateShowTouchesFromSettings() {
1601 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001602 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001603 }
1604
1605 private void registerShowTouchesSettingObserver() {
1606 mContext.getContentResolver().registerContentObserver(
1607 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001608 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001609 @Override
1610 public void onChange(boolean selfChange) {
1611 updateShowTouchesFromSettings();
1612 }
Jeff Brownd4935962012-09-25 13:27:20 -07001613 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001614 }
1615
Jun Mukaie4e75da2015-12-15 16:19:20 -08001616 public void updateAccessibilityLargePointerFromSettings() {
1617 final int accessibilityConfig = Settings.Secure.getIntForUser(
1618 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1619 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001620 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001621 nativeReloadPointerIcons(mPtr);
1622 }
1623
Jun Mukai19a56012015-11-24 11:25:52 -08001624 private void registerAccessibilityLargePointerSettingObserver() {
1625 mContext.getContentResolver().registerContentObserver(
1626 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1627 new ContentObserver(mHandler) {
1628 @Override
1629 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001630 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001631 }
1632 }, UserHandle.USER_ALL);
1633 }
1634
Jeff Browndaf4a122011-08-26 17:14:14 -07001635 private int getShowTouchesSetting(int defaultValue) {
1636 int result = defaultValue;
1637 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001638 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1639 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001640 } catch (SettingNotFoundException snfe) {
1641 }
1642 return result;
1643 }
1644
Jeff Browna47425a2012-04-13 04:09:27 -07001645 // Binder call
1646 @Override
1647 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1648 if (repeat >= pattern.length) {
1649 throw new ArrayIndexOutOfBoundsException();
1650 }
1651
1652 VibratorToken v;
1653 synchronized (mVibratorLock) {
1654 v = mVibratorTokens.get(token);
1655 if (v == null) {
1656 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1657 try {
1658 token.linkToDeath(v, 0);
1659 } catch (RemoteException ex) {
1660 // give up
1661 throw new RuntimeException(ex);
1662 }
1663 mVibratorTokens.put(token, v);
1664 }
1665 }
1666
1667 synchronized (v) {
1668 v.mVibrating = true;
1669 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1670 }
1671 }
1672
1673 // Binder call
1674 @Override
1675 public void cancelVibrate(int deviceId, IBinder token) {
1676 VibratorToken v;
1677 synchronized (mVibratorLock) {
1678 v = mVibratorTokens.get(token);
1679 if (v == null || v.mDeviceId != deviceId) {
1680 return; // nothing to cancel
1681 }
1682 }
1683
1684 cancelVibrateIfNeeded(v);
1685 }
1686
1687 void onVibratorTokenDied(VibratorToken v) {
1688 synchronized (mVibratorLock) {
1689 mVibratorTokens.remove(v.mToken);
1690 }
1691
1692 cancelVibrateIfNeeded(v);
1693 }
1694
1695 private void cancelVibrateIfNeeded(VibratorToken v) {
1696 synchronized (v) {
1697 if (v.mVibrating) {
1698 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1699 v.mVibrating = false;
1700 }
1701 }
1702 }
1703
Jun Mukai19a56012015-11-24 11:25:52 -08001704 // Binder call
1705 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001706 public void setPointerIconType(int iconId) {
1707 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001708 }
Jun Mukai1db53972015-09-11 18:08:31 -07001709
Jun Mukaid4eaef72015-10-30 15:54:33 -07001710 // Binder call
1711 @Override
1712 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001713 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001714 nativeSetCustomPointerIcon(mPtr, icon);
1715 }
1716
Jeff Brown4532e612012-04-05 14:27:12 -07001717 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001718 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001719 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001720
1721 pw.println("INPUT MANAGER (dumpsys input)\n");
1722 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001723 if (dumpStr != null) {
1724 pw.println(dumpStr);
1725 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001726 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001727
Jeff Brownac143512012-04-05 18:57:33 -07001728 private boolean checkCallingPermission(String permission, String func) {
1729 // Quick check: if the calling permission is me, it's all okay.
1730 if (Binder.getCallingPid() == Process.myPid()) {
1731 return true;
1732 }
1733
1734 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1735 return true;
1736 }
1737 String msg = "Permission Denial: " + func + " from pid="
1738 + Binder.getCallingPid()
1739 + ", uid=" + Binder.getCallingUid()
1740 + " requires " + permission;
1741 Slog.w(TAG, msg);
1742 return false;
1743 }
1744
Jeff Brown4532e612012-04-05 14:27:12 -07001745 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001746 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001747 public void monitor() {
1748 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001749 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001750 }
1751
Andrii Kulianed76e742017-06-26 14:57:02 -07001752 // Binder call
1753 @Override
1754 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1755 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1756 "createInputForwarder()")) {
1757 throw new SecurityException("Requires INJECT_EVENTS permission");
1758 }
1759 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1760 final Display display = displayManager.getDisplay(displayId);
1761 if (display == null) {
1762 throw new IllegalArgumentException(
1763 "Can't create input forwarder for non-existent displayId: " + displayId);
1764 }
1765 final int callingUid = Binder.getCallingUid();
1766 final int displayOwnerUid = display.getOwnerUid();
1767 if (callingUid != displayOwnerUid) {
1768 throw new SecurityException(
1769 "Only owner of the display can forward input events to it.");
1770 }
1771
1772 return new InputForwarder(displayId);
1773 }
1774
Jeff Brown4532e612012-04-05 14:27:12 -07001775 // Native callback.
1776 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001777 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001778 }
1779
1780 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001781 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1782 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001783 if (!mInputDevicesChangedPending) {
1784 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001785 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1786 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001787 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001788
1789 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001790 }
1791 }
1792
1793 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001794 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1795 if (DEBUG) {
1796 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1797 + ", mask=" + Integer.toHexString(switchMask));
1798 }
1799
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001800 if ((switchMask & SW_LID_BIT) != 0) {
1801 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001802 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001803 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001804
Michael Wright3818c922014-09-02 13:59:07 -07001805 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001806 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001807 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1808 }
1809
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001810 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1811 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1812 switchMask);
1813 }
Michael Wright39e5e942015-08-19 22:52:47 +01001814
Michael Wright9209c9c2015-09-03 17:57:01 +01001815 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001816 SomeArgs args = SomeArgs.obtain();
1817 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1818 args.argi2 = (int) (whenNanos >> 32);
1819 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1820 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1821 args).sendToTarget();
1822 }
Jeff Brown4532e612012-04-05 14:27:12 -07001823 }
1824
1825 // Native callback.
1826 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001827 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001828 }
1829
1830 // Native callback.
1831 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001832 InputWindowHandle inputWindowHandle, String reason) {
1833 return mWindowManagerCallbacks.notifyANR(
1834 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001835 }
1836
1837 // Native callback.
1838 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1839 synchronized (mInputFilterLock) {
1840 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001841 try {
1842 mInputFilter.filterInputEvent(event, policyFlags);
1843 } catch (RemoteException e) {
1844 /* ignore */
1845 }
Jeff Brown4532e612012-04-05 14:27:12 -07001846 return false;
1847 }
1848 }
1849 event.recycle();
1850 return true;
1851 }
1852
1853 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001854 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1855 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001856 }
1857
1858 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001859 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1860 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001861 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001862 }
1863
1864 // Native callback.
1865 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1866 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001867 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001868 }
1869
1870 // Native callback.
1871 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1872 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001873 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001874 }
1875
1876 // Native callback.
1877 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1878 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1879 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1880 }
1881
1882 // Native callback.
1883 private int getVirtualKeyQuietTimeMillis() {
1884 return mContext.getResources().getInteger(
1885 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1886 }
1887
1888 // Native callback.
1889 private String[] getExcludedDeviceNames() {
1890 ArrayList<String> names = new ArrayList<String>();
1891
1892 // Read partner-provided list of excluded input devices
1893 XmlPullParser parser = null;
1894 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1895 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1896 FileReader confreader = null;
1897 try {
1898 confreader = new FileReader(confFile);
1899 parser = Xml.newPullParser();
1900 parser.setInput(confreader);
1901 XmlUtils.beginDocument(parser, "devices");
1902
1903 while (true) {
1904 XmlUtils.nextElement(parser);
1905 if (!"device".equals(parser.getName())) {
1906 break;
1907 }
1908 String name = parser.getAttributeValue(null, "name");
1909 if (name != null) {
1910 names.add(name);
1911 }
1912 }
1913 } catch (FileNotFoundException e) {
1914 // It's ok if the file does not exist.
1915 } catch (Exception e) {
1916 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1917 } finally {
1918 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1919 }
1920
1921 return names.toArray(new String[names.size()]);
1922 }
1923
1924 // Native callback.
1925 private int getKeyRepeatTimeout() {
1926 return ViewConfiguration.getKeyRepeatTimeout();
1927 }
1928
1929 // Native callback.
1930 private int getKeyRepeatDelay() {
1931 return ViewConfiguration.getKeyRepeatDelay();
1932 }
1933
1934 // Native callback.
1935 private int getHoverTapTimeout() {
1936 return ViewConfiguration.getHoverTapTimeout();
1937 }
1938
1939 // Native callback.
1940 private int getHoverTapSlop() {
1941 return ViewConfiguration.getHoverTapSlop();
1942 }
1943
1944 // Native callback.
1945 private int getDoubleTapTimeout() {
1946 return ViewConfiguration.getDoubleTapTimeout();
1947 }
1948
1949 // Native callback.
1950 private int getLongPressTimeout() {
1951 return ViewConfiguration.getLongPressTimeout();
1952 }
1953
1954 // Native callback.
1955 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001956 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001957 }
1958
1959 // Native callback.
1960 private PointerIcon getPointerIcon() {
1961 return PointerIcon.getDefaultIcon(mContext);
1962 }
1963
Jeff Brown6ec6f792012-04-17 16:52:41 -07001964 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001965 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001966 if (!mSystemReady) {
1967 return null;
1968 }
1969
RoboErikfb290df2013-12-16 11:27:55 -08001970 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001971 if (keyboardLayoutDescriptor == null) {
1972 return null;
1973 }
1974
1975 final String[] result = new String[2];
1976 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1977 @Override
Michael Wright07483422015-10-30 16:20:13 +00001978 public void visitKeyboardLayout(Resources resources,
1979 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001980 try {
Michael Wright07483422015-10-30 16:20:13 +00001981 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001982 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001983 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001984 } catch (IOException ex) {
1985 } catch (NotFoundException ex) {
1986 }
1987 }
1988 });
1989 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001990 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001991 + keyboardLayoutDescriptor + "'.");
1992 return null;
1993 }
1994 return result;
1995 }
1996
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001997 // Native callback.
1998 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001999 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2000 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2001 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002002 }
2003 return null;
2004 }
2005
Jeff Brown4532e612012-04-05 14:27:12 -07002006 /**
2007 * Callback interface implemented by the Window Manager.
2008 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002009 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002010 public void notifyConfigurationChanged();
2011
2012 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2013
Michael Wright3818c922014-09-02 13:59:07 -07002014 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2015
Jeff Brown4532e612012-04-05 14:27:12 -07002016 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
2017
2018 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07002019 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002020
Jeff Brown037c33e2014-04-09 00:31:55 -07002021 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002022
Michael Wright70af00a2014-09-03 19:30:20 -07002023 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002024
2025 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2026 KeyEvent event, int policyFlags);
2027
2028 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2029 KeyEvent event, int policyFlags);
2030
2031 public int getPointerLayer();
2032 }
2033
2034 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002035 * Callback interface implemented by WiredAccessoryObserver.
2036 */
2037 public interface WiredAccessoryCallbacks {
2038 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002039 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002040 }
2041
2042 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002043 * Private handler for the input manager.
2044 */
2045 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002046 public InputManagerHandler(Looper looper) {
2047 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002048 }
2049
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002050 @Override
2051 public void handleMessage(Message msg) {
2052 switch (msg.what) {
2053 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002054 deliverInputDevicesChanged((InputDevice[])msg.obj);
2055 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002056 case MSG_SWITCH_KEYBOARD_LAYOUT:
2057 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002058 break;
2059 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2060 reloadKeyboardLayouts();
2061 break;
2062 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2063 updateKeyboardLayouts();
2064 break;
2065 case MSG_RELOAD_DEVICE_ALIASES:
2066 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002067 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002068 case MSG_DELIVER_TABLET_MODE_CHANGED: {
Michael Wright39e5e942015-08-19 22:52:47 +01002069 SomeArgs args = (SomeArgs) msg.obj;
2070 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2071 boolean inTabletMode = (boolean) args.arg1;
2072 deliverTabletModeChanged(whenNanos, inTabletMode);
2073 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002074 }
2075 case MSG_INPUT_METHOD_SUBTYPE_CHANGED: {
2076 final int userId = msg.arg1;
2077 final SomeArgs args = (SomeArgs) msg.obj;
2078 final InputMethodInfo inputMethodInfo = (InputMethodInfo) args.arg1;
2079 final InputMethodSubtype subtype = (InputMethodSubtype) args.arg2;
2080 args.recycle();
2081 handleSwitchInputMethodSubtype(userId, inputMethodInfo, subtype);
2082 break;
2083 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002084 }
2085 }
2086 }
2087
2088 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002089 * Hosting interface for input filters to call back into the input manager.
2090 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002091 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002092 private boolean mDisconnected;
2093
2094 public void disconnectLocked() {
2095 mDisconnected = true;
2096 }
2097
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002098 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002099 public void sendInputEvent(InputEvent event, int policyFlags) {
2100 if (event == null) {
2101 throw new IllegalArgumentException("event must not be null");
2102 }
2103
2104 synchronized (mInputFilterLock) {
2105 if (!mDisconnected) {
Jeff Brownca9bc702014-02-11 14:32:56 -08002106 nativeInjectInputEvent(mPtr, event, Display.DEFAULT_DISPLAY, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002107 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002108 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2109 }
2110 }
2111 }
2112 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002113
2114 private static final class KeyboardLayoutDescriptor {
2115 public String packageName;
2116 public String receiverName;
2117 public String keyboardLayoutName;
2118
2119 public static String format(String packageName,
2120 String receiverName, String keyboardName) {
2121 return packageName + "/" + receiverName + "/" + keyboardName;
2122 }
2123
2124 public static KeyboardLayoutDescriptor parse(String descriptor) {
2125 int pos = descriptor.indexOf('/');
2126 if (pos < 0 || pos + 1 == descriptor.length()) {
2127 return null;
2128 }
2129 int pos2 = descriptor.indexOf('/', pos + 1);
2130 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2131 return null;
2132 }
2133
2134 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2135 result.packageName = descriptor.substring(0, pos);
2136 result.receiverName = descriptor.substring(pos + 1, pos2);
2137 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2138 return result;
2139 }
2140 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002141
Jeff Brown6ec6f792012-04-17 16:52:41 -07002142 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002143 void visitKeyboardLayout(Resources resources,
2144 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002145 }
2146
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002147 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2148 private final int mPid;
2149 private final IInputDevicesChangedListener mListener;
2150
2151 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2152 mPid = pid;
2153 mListener = listener;
2154 }
2155
2156 @Override
2157 public void binderDied() {
2158 if (DEBUG) {
2159 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2160 }
2161 onInputDevicesChangedListenerDied(mPid);
2162 }
2163
2164 public void notifyInputDevicesChanged(int[] info) {
2165 try {
2166 mListener.onInputDevicesChanged(info);
2167 } catch (RemoteException ex) {
2168 Slog.w(TAG, "Failed to notify process "
2169 + mPid + " that input devices changed, assuming it died.", ex);
2170 binderDied();
2171 }
2172 }
2173 }
Jeff Browna47425a2012-04-13 04:09:27 -07002174
Michael Wright39e5e942015-08-19 22:52:47 +01002175 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2176 private final int mPid;
2177 private final ITabletModeChangedListener mListener;
2178
2179 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2180 mPid = pid;
2181 mListener = listener;
2182 }
2183
2184 @Override
2185 public void binderDied() {
2186 if (DEBUG) {
2187 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2188 }
2189 onTabletModeChangedListenerDied(mPid);
2190 }
2191
2192 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2193 try {
2194 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2195 } catch (RemoteException ex) {
2196 Slog.w(TAG, "Failed to notify process " + mPid +
2197 " that tablet mode changed, assuming it died.", ex);
2198 binderDied();
2199 }
2200 }
2201 }
2202
Jeff Browna47425a2012-04-13 04:09:27 -07002203 private final class VibratorToken implements DeathRecipient {
2204 public final int mDeviceId;
2205 public final IBinder mToken;
2206 public final int mTokenValue;
2207
2208 public boolean mVibrating;
2209
2210 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2211 mDeviceId = deviceId;
2212 mToken = token;
2213 mTokenValue = tokenValue;
2214 }
2215
2216 @Override
2217 public void binderDied() {
2218 if (DEBUG) {
2219 Slog.d(TAG, "Vibrator token died.");
2220 }
2221 onVibratorTokenDied(this);
2222 }
2223 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002224
2225 private final class LocalService extends InputManagerInternal {
2226 @Override
Santos Cordonee8931e2017-04-05 10:31:15 -07002227 public void setDisplayViewports(DisplayViewport defaultViewport,
2228 DisplayViewport externalTouchViewport,
2229 List<DisplayViewport> virtualTouchViewports) {
2230 setDisplayViewportsInternal(defaultViewport, externalTouchViewport,
2231 virtualTouchViewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002232 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002233
2234 @Override
2235 public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
2236 return injectInputEventInternal(event, displayId, mode);
2237 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002238
2239 @Override
2240 public void setInteractive(boolean interactive) {
2241 nativeSetInteractive(mPtr, interactive);
2242 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002243
2244 @Override
2245 public void onInputMethodSubtypeChanged(int userId,
2246 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
2247 final SomeArgs someArgs = SomeArgs.obtain();
2248 someArgs.arg1 = inputMethodInfo;
2249 someArgs.arg2 = subtype;
2250 mHandler.obtainMessage(MSG_INPUT_METHOD_SUBTYPE_CHANGED, userId, 0, someArgs)
2251 .sendToTarget();
2252 }
Andrii Kulian112d0562016-03-08 10:44:22 -08002253
2254 @Override
2255 public void toggleCapsLock(int deviceId) {
2256 nativeToggleCapsLock(mPtr, deviceId);
2257 }
Adrian Roos99182342016-06-15 15:30:46 -07002258
2259 @Override
2260 public void setPulseGestureEnabled(boolean enabled) {
2261 if (mDoubleTouchGestureEnableFile != null) {
2262 FileWriter writer = null;
2263 try {
2264 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2265 writer.write(enabled ? "1" : "0");
2266 } catch (IOException e) {
2267 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2268 } finally {
2269 IoUtils.closeQuietly(writer);
2270 }
2271 }
2272 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002273 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002274}