blob: 5bd095d952b081a8395bac7b452a6de19b485443 [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown4532e612012-04-05 14:27:12 -070017package com.android.server.input;
Jeff Brown46b9ac02010-04-22 18:58:52 -070018
Yohei Yukawa5660fad2016-01-27 22:04:09 -080019import android.annotation.NonNull;
Andrii Kulianed76e742017-06-26 14:57:02 -070020import android.app.IInputForwarder;
Jeff Browncf39bdf2012-05-18 14:41:19 -070021import android.app.Notification;
22import android.app.NotificationManager;
23import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070024import android.bluetooth.BluetoothAdapter;
25import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070026import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070027import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070028import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070029import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070030import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070031import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070032import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070033import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070034import android.content.pm.PackageManager.NameNotFoundException;
Arthur Hung39134b22018-08-14 11:58:28 +080035import android.content.pm.ResolveInfo;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070036import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070037import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070038import android.content.res.TypedArray;
39import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070040import android.database.ContentObserver;
Andrii Kulianed76e742017-06-26 14:57:02 -070041import android.hardware.display.DisplayManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080042import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070043import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070044import android.hardware.input.IInputManager;
Arthur Hung39134b22018-08-14 11:58:28 +080045import android.hardware.input.ITabletModeChangedListener;
RoboErikfb290df2013-12-16 11:27:55 -080046import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070047import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080048import android.hardware.input.InputManagerInternal;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080050import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070051import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070052import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070053import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070054import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070055import android.os.IBinder;
Arthur Hung39134b22018-08-14 11:58:28 +080056import android.os.LocaleList;
Jeff Browna9d131c2012-09-20 16:48:17 -070057import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070058import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080059import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070061import android.os.RemoteException;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070062import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070063import android.provider.Settings;
64import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000065import android.text.TextUtils;
Arthur Hung39134b22018-08-14 11:58:28 +080066import android.util.Log;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070068import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070069import android.util.Xml;
Andrii Kulianed76e742017-06-26 14:57:02 -070070import android.view.Display;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070071import android.view.IInputFilter;
72import android.view.IInputFilterHost;
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -080073import android.view.IWindow;
Jeff Brown46b9ac02010-04-22 18:58:52 -070074import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070075import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070076import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080077import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070078import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070079import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080080import android.view.ViewConfiguration;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -080081import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070082
Arthur Hung39134b22018-08-14 11:58:28 +080083import com.android.internal.R;
84import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
85import com.android.internal.notification.SystemNotificationChannels;
86import com.android.internal.os.SomeArgs;
87import com.android.internal.util.DumpUtils;
88import com.android.internal.util.Preconditions;
89import com.android.internal.util.XmlUtils;
90import com.android.server.DisplayThread;
91import com.android.server.LocalServices;
92import com.android.server.Watchdog;
93import com.android.server.policy.WindowManagerPolicy;
94
95import libcore.io.IoUtils;
96import libcore.io.Streams;
97
98import org.xmlpull.v1.XmlPullParser;
99
Jeff Brown46b9ac02010-04-22 18:58:52 -0700100import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700101import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700102import java.io.FileNotFoundException;
103import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700104import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700105import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700106import java.io.InputStreamReader;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700107import java.io.PrintWriter;
108import java.util.ArrayList;
Michael Wright07483422015-10-30 16:20:13 +0000109import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700110import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700111import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100112import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000113import java.util.Locale;
Narayan Kamath607223f2018-02-19 14:09:02 +0000114import java.util.Objects;
Jeff Browna3bc5652012-04-17 11:42:25 -0700115
Jeff Brown46b9ac02010-04-22 18:58:52 -0700116/*
117 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700118 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700119public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800120 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700121 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700122 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700123
Jeff Brown4532e612012-04-05 14:27:12 -0700124 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
125
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700126 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700127 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
128 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
129 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
130 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100131 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700132
Jeff Brown4532e612012-04-05 14:27:12 -0700133 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000134 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700135
Jeff Brown46b9ac02010-04-22 18:58:52 -0700136 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700137 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700138
Adrian Roos99182342016-06-15 15:30:46 -0700139 private final File mDoubleTouchGestureEnableFile;
140
Jeff Browna9d131c2012-09-20 16:48:17 -0700141 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700142 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700143 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700144 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700145
Michael Wright39e5e942015-08-19 22:52:47 +0100146 private final Object mTabletModeLock = new Object();
147 // List of currently registered tablet mode changed listeners by process id
148 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
149 new SparseArray<>(); // guarded by mTabletModeLock
150 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
151 new ArrayList<>();
152
Jeff Browna3bc5652012-04-17 11:42:25 -0700153 // Persistent data store. Must be locked each time during use.
154 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700155
156 // List of currently registered input devices changed listeners by process id.
157 private Object mInputDevicesLock = new Object();
158 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
159 private InputDevice[] mInputDevices = new InputDevice[0];
160 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
161 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
162 private final ArrayList<InputDevicesChangedListenerRecord>
163 mTempInputDevicesChangedListenersToNotify =
164 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700165 private final ArrayList<InputDevice>
166 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
167 private boolean mKeyboardLayoutNotificationShown;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -0800168 private PendingIntent mKeyboardLayoutIntent;
169 private Toast mSwitchedKeyboardLayoutToast;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700170
Jeff Browna47425a2012-04-13 04:09:27 -0700171 // State for vibrator tokens.
172 private Object mVibratorLock = new Object();
173 private HashMap<IBinder, VibratorToken> mVibratorTokens =
174 new HashMap<IBinder, VibratorToken>();
175 private int mNextVibratorTokenValue;
176
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700177 // State for the currently installed input filter.
178 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700179 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700180 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700181
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800182 private IWindow mFocusedWindow;
183 private boolean mFocusedWindowHasCapture;
184
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000185 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700186 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native void nativeStart(long ptr);
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100188 private static native void nativeSetDisplayViewports(long ptr,
Santos Cordonee8931e2017-04-05 10:31:15 -0700189 DisplayViewport[] viewports);
Jeff Brownd728bf52012-09-08 18:05:28 -0700190
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000191 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700192 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000193 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700194 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000195 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700196 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000197 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700198 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000199 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800200 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000201 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
202 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800203 private static native int nativeInjectInputEvent(long ptr, InputEvent event,
Jeff Brown0029c662011-03-30 02:25:18 -0700204 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
205 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800206 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Arthur Hung39134b22018-08-14 11:58:28 +0800207 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles,
208 int displayId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000209 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
210 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
211 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700212 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000213 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700214 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000215 private static native void nativeSetPointerSpeed(long ptr, int speed);
216 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700217 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800218 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700220 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000221 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
222 private static native void nativeReloadKeyboardLayouts(long ptr);
223 private static native void nativeReloadDeviceAliases(long ptr);
224 private static native String nativeDump(long ptr);
225 private static native void nativeMonitor(long ptr);
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700226 private static native boolean nativeIsInputDeviceEnabled(long ptr, int deviceId);
227 private static native void nativeEnableInputDevice(long ptr, int deviceId);
228 private static native void nativeDisableInputDevice(long ptr, int deviceId);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100229 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800230 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700231 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -0800232 private static native void nativeSetPointerCapture(long ptr, boolean detached);
Jeff Brown4532e612012-04-05 14:27:12 -0700233
Jeff Brownac143512012-04-05 18:57:33 -0700234 // Input event injection constants defined in InputDispatcher.h.
235 private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
236 private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
237 private static final int INPUT_EVENT_INJECTION_FAILED = 2;
238 private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
239
240 // Maximum number of milliseconds to wait for input event injection.
241 private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
242
Jeff Brown6d0fec22010-07-23 21:28:06 -0700243 // Key states (may be returned by queries about the current state of a
244 // particular key code, scan code or switch).
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700245
Jeff Brown6d0fec22010-07-23 21:28:06 -0700246 /** The key state is unknown or the requested key itself is not supported. */
247 public static final int KEY_STATE_UNKNOWN = -1;
248
249 /** The key is up. /*/
250 public static final int KEY_STATE_UP = 0;
251
252 /** The key is down. */
253 public static final int KEY_STATE_DOWN = 1;
254
255 /** The key is down but is a virtual key press that is being emulated by the system. */
256 public static final int KEY_STATE_VIRTUAL = 2;
257
Jeff Brownc458ce92012-04-30 14:58:40 -0700258 /** Scan code: Mouse / trackball button. */
259 public static final int BTN_MOUSE = 0x110;
260
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700261 // Switch code values must match bionic/libc/kernel/common/linux/input.h
Jeff Brownc458ce92012-04-30 14:58:40 -0700262 /** Switch code: Lid switch. When set, lid is shut. */
263 public static final int SW_LID = 0x00;
264
Michael Wright39e5e942015-08-19 22:52:47 +0100265 /** Switch code: Tablet mode switch.
266 * When set, the device is in tablet mode (i.e. no keyboard is connected).
267 */
268 public static final int SW_TABLET_MODE = 0x01;
269
Jeff Brownc458ce92012-04-30 14:58:40 -0700270 /** Switch code: Keypad slide. When set, keyboard is exposed. */
271 public static final int SW_KEYPAD_SLIDE = 0x0a;
272
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700273 /** Switch code: Headphone. When set, headphone is inserted. */
274 public static final int SW_HEADPHONE_INSERT = 0x02;
275
276 /** Switch code: Microphone. When set, microphone is inserted. */
277 public static final int SW_MICROPHONE_INSERT = 0x04;
278
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500279 /** Switch code: Line out. When set, Line out (hi-Z) is inserted. */
280 public static final int SW_LINEOUT_INSERT = 0x06;
281
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700282 /** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
283 public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
284
Michael Wright3818c922014-09-02 13:59:07 -0700285 /** Switch code: Camera lens cover. When set the lens is covered. */
286 public static final int SW_CAMERA_LENS_COVER = 0x09;
287
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700288 public static final int SW_LID_BIT = 1 << SW_LID;
Michael Wright39e5e942015-08-19 22:52:47 +0100289 public static final int SW_TABLET_MODE_BIT = 1 << SW_TABLET_MODE;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700290 public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
291 public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
292 public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500293 public static final int SW_LINEOUT_INSERT_BIT = 1 << SW_LINEOUT_INSERT;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700294 public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
295 public static final int SW_JACK_BITS =
Jon Eklund43cc8bb2014-07-28 16:07:24 -0500296 SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT | SW_LINEOUT_INSERT_BIT;
Michael Wright3818c922014-09-02 13:59:07 -0700297 public static final int SW_CAMERA_LENS_COVER_BIT = 1 << SW_CAMERA_LENS_COVER;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700298
299 /** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
300 final boolean mUseDevInputEventForAudioJack;
301
Jeff Brown4ccb8232014-01-16 22:16:42 -0800302 public InputManagerService(Context context) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700303 this.mContext = context;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800304 this.mHandler = new InputManagerHandler(DisplayThread.get().getLooper());
Jeff Brown05dc66a2011-03-02 14:41:58 -0800305
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700306 mUseDevInputEventForAudioJack =
307 context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
308 Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
309 + mUseDevInputEventForAudioJack);
Jeff Brown4532e612012-04-05 14:27:12 -0700310 mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
Jeff Brown4ccb8232014-01-16 22:16:42 -0800311
Adrian Roos99182342016-06-15 15:30:46 -0700312 String doubleTouchGestureEnablePath = context.getResources().getString(
313 R.string.config_doubleTouchGestureEnableFile);
314 mDoubleTouchGestureEnableFile = TextUtils.isEmpty(doubleTouchGestureEnablePath) ? null :
315 new File(doubleTouchGestureEnablePath);
316
Jeff Brown4ccb8232014-01-16 22:16:42 -0800317 LocalServices.addService(InputManagerInternal.class, new LocalService());
Jeff Brown46b9ac02010-04-22 18:58:52 -0700318 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700319
Jeff Browna9d131c2012-09-20 16:48:17 -0700320 public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
321 mWindowManagerCallbacks = callbacks;
322 }
323
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700324 public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
325 mWiredAccessoryCallbacks = callbacks;
326 }
327
Jeff Brown46b9ac02010-04-22 18:58:52 -0700328 public void start() {
329 Slog.i(TAG, "Starting input manager");
Jeff Brown4532e612012-04-05 14:27:12 -0700330 nativeStart(mPtr);
331
332 // Add ourself to the Watchdog monitors.
333 Watchdog.getInstance().addMonitor(this);
Jeff Brown1a84fd12011-06-02 01:26:32 -0700334
335 registerPointerSpeedSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700336 registerShowTouchesSettingObserver();
Jun Mukai19a56012015-11-24 11:25:52 -0800337 registerAccessibilityLargePointerSettingObserver();
Jeff Browndaf4a122011-08-26 17:14:14 -0700338
Jeff Brownd4935962012-09-25 13:27:20 -0700339 mContext.registerReceiver(new BroadcastReceiver() {
340 @Override
341 public void onReceive(Context context, Intent intent) {
342 updatePointerSpeedFromSettings();
343 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800344 updateAccessibilityLargePointerFromSettings();
Jeff Brownd4935962012-09-25 13:27:20 -0700345 }
346 }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
347
Jeff Brown1a84fd12011-06-02 01:26:32 -0700348 updatePointerSpeedFromSettings();
Jeff Browndaf4a122011-08-26 17:14:14 -0700349 updateShowTouchesFromSettings();
Jun Mukaie4e75da2015-12-15 16:19:20 -0800350 updateAccessibilityLargePointerFromSettings();
Jeff Brown46b9ac02010-04-22 18:58:52 -0700351 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700352
Siarhei Vishniakouc8631852018-07-06 11:33:56 +0100353 // TODO(BT) Pass in parameter for bluetooth system
Svetoslav Ganova0027152013-06-25 14:59:53 -0700354 public void systemRunning() {
Jeff Brown6ec6f792012-04-17 16:52:41 -0700355 if (DEBUG) {
356 Slog.d(TAG, "System ready.");
357 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700358 mNotificationManager = (NotificationManager)mContext.getSystemService(
359 Context.NOTIFICATION_SERVICE);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700360 mSystemReady = true;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700361
362 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
363 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
364 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Jeff Brown69b07162013-11-07 00:30:16 -0800365 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
Jeff Brown6ec6f792012-04-17 16:52:41 -0700366 filter.addDataScheme("package");
367 mContext.registerReceiver(new BroadcastReceiver() {
368 @Override
369 public void onReceive(Context context, Intent intent) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700370 updateKeyboardLayouts();
Jeff Brown6ec6f792012-04-17 16:52:41 -0700371 }
372 }, filter, null, mHandler);
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700373
374 filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
375 mContext.registerReceiver(new BroadcastReceiver() {
376 @Override
377 public void onReceive(Context context, Intent intent) {
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700378 reloadDeviceAliases();
379 }
380 }, filter, null, mHandler);
381
Jeff Browncf39bdf2012-05-18 14:41:19 -0700382 mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
383 mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
Eric Laurent4a5eeb92014-05-06 10:49:04 -0700384
385 if (mWiredAccessoryCallbacks != null) {
386 mWiredAccessoryCallbacks.systemReady();
387 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700388 }
389
390 private void reloadKeyboardLayouts() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700391 if (DEBUG) {
392 Slog.d(TAG, "Reloading keyboard layouts.");
393 }
Jeff Brown6ec6f792012-04-17 16:52:41 -0700394 nativeReloadKeyboardLayouts(mPtr);
395 }
396
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700397 private void reloadDeviceAliases() {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700398 if (DEBUG) {
399 Slog.d(TAG, "Reloading device names.");
400 }
Jeff Brown5bbd4b42012-04-20 19:28:00 -0700401 nativeReloadDeviceAliases(mPtr);
402 }
403
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +0100404 private void setDisplayViewportsInternal(List<DisplayViewport> viewports) {
405 nativeSetDisplayViewports(mPtr, viewports.toArray(new DisplayViewport[0]));
Jeff Brown46b9ac02010-04-22 18:58:52 -0700406 }
Jeff Brownac143512012-04-05 18:57:33 -0700407
Jeff Brown6d0fec22010-07-23 21:28:06 -0700408 /**
409 * Gets the current state of a key or button by key code.
410 * @param deviceId The input device id, or -1 to consult all devices.
411 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
412 * consider all input sources. An input device is consulted if at least one of its
413 * non-class input source bits matches the specified source mask.
414 * @param keyCode The key code to check.
415 * @return The key state.
416 */
417 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700418 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700419 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700420
Jeff Brown6d0fec22010-07-23 21:28:06 -0700421 /**
422 * Gets the current state of a key or button by scan code.
423 * @param deviceId The input device id, or -1 to consult all devices.
424 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
425 * consider all input sources. An input device is consulted if at least one of its
426 * non-class input source bits matches the specified source mask.
427 * @param scanCode The scan code to check.
428 * @return The key state.
429 */
430 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700431 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700432 }
RoboErikfb290df2013-12-16 11:27:55 -0800433
Jeff Brown6d0fec22010-07-23 21:28:06 -0700434 /**
435 * Gets the current state of a switch by switch code.
436 * @param deviceId The input device id, or -1 to consult all devices.
437 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
438 * consider all input sources. An input device is consulted if at least one of its
439 * non-class input source bits matches the specified source mask.
440 * @param switchCode The switch code to check.
441 * @return The switch state.
442 */
443 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700444 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700445 }
446
Jeff Brown6d0fec22010-07-23 21:28:06 -0700447 /**
448 * Determines whether the specified key codes are supported by a particular device.
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 keyCodes The array of key codes to check.
454 * @param keyExists An array at least as large as keyCodes whose entries will be set
455 * to true or false based on the presence or absence of support for the corresponding
456 * key codes.
457 * @return True if the lookup was successful, false otherwise.
458 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700459 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700460 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700461 if (keyCodes == null) {
462 throw new IllegalArgumentException("keyCodes must not be null.");
463 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700464 if (keyExists == null || keyExists.length < keyCodes.length) {
465 throw new IllegalArgumentException("keyExists must not be null and must be at "
466 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700467 }
RoboErikfb290df2013-12-16 11:27:55 -0800468
Jeff Brown4532e612012-04-05 14:27:12 -0700469 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700470 }
RoboErikfb290df2013-12-16 11:27:55 -0800471
Jeff Browna41ca772010-08-11 14:46:32 -0700472 /**
473 * Creates an input channel that will receive all input from the input dispatcher.
474 * @param inputChannelName The input channel name.
475 * @return The input channel.
476 */
477 public InputChannel monitorInput(String inputChannelName) {
478 if (inputChannelName == null) {
479 throw new IllegalArgumentException("inputChannelName must not be null.");
480 }
RoboErikfb290df2013-12-16 11:27:55 -0800481
Jeff Browna41ca772010-08-11 14:46:32 -0700482 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700483 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700484 inputChannels[0].dispose(); // don't need to retain the Java object reference
485 return inputChannels[1];
486 }
487
488 /**
489 * Registers an input channel so that it can be used as an input event target.
490 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800491 * @param inputWindowHandle The handle of the input window associated with the
492 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700493 */
Jeff Brown928e0542011-01-10 11:17:36 -0800494 public void registerInputChannel(InputChannel inputChannel,
495 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700496 if (inputChannel == null) {
497 throw new IllegalArgumentException("inputChannel must not be null.");
498 }
RoboErikfb290df2013-12-16 11:27:55 -0800499
Jeff Brown4532e612012-04-05 14:27:12 -0700500 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700501 }
RoboErikfb290df2013-12-16 11:27:55 -0800502
Jeff Browna41ca772010-08-11 14:46:32 -0700503 /**
504 * Unregisters an input channel.
505 * @param inputChannel The input channel to unregister.
506 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700507 public void unregisterInputChannel(InputChannel inputChannel) {
508 if (inputChannel == null) {
509 throw new IllegalArgumentException("inputChannel must not be null.");
510 }
RoboErikfb290df2013-12-16 11:27:55 -0800511
Jeff Brown4532e612012-04-05 14:27:12 -0700512 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700513 }
Jeff Brown0029c662011-03-30 02:25:18 -0700514
515 /**
516 * Sets an input filter that will receive all input events before they are dispatched.
517 * The input filter may then reinterpret input events or inject new ones.
518 *
519 * To ensure consistency, the input dispatcher automatically drops all events
520 * in progress whenever an input filter is installed or uninstalled. After an input
521 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
522 * Any events it attempts to send after it has been uninstalled will be dropped.
523 *
524 * @param filter The input filter, or null to remove the current filter.
525 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700526 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700527 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700528 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700529 if (oldFilter == filter) {
530 return; // nothing to do
531 }
532
533 if (oldFilter != null) {
534 mInputFilter = null;
535 mInputFilterHost.disconnectLocked();
536 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700537 try {
538 oldFilter.uninstall();
539 } catch (RemoteException re) {
540 /* ignore */
541 }
Jeff Brown0029c662011-03-30 02:25:18 -0700542 }
543
544 if (filter != null) {
545 mInputFilter = filter;
546 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700547 try {
548 filter.install(mInputFilterHost);
549 } catch (RemoteException re) {
550 /* ignore */
551 }
Jeff Brown0029c662011-03-30 02:25:18 -0700552 }
553
Jeff Brown4532e612012-04-05 14:27:12 -0700554 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700555 }
556 }
557
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700558 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700559 public boolean injectInputEvent(InputEvent event, int mode) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800560 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -0800561 }
562
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800563 private boolean injectInputEventInternal(InputEvent event, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700564 if (event == null) {
565 throw new IllegalArgumentException("event must not be null");
566 }
Jeff Brownac143512012-04-05 18:57:33 -0700567 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
568 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
569 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
570 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700571 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700572
Jeff Brownac143512012-04-05 18:57:33 -0700573 final int pid = Binder.getCallingPid();
574 final int uid = Binder.getCallingUid();
575 final long ident = Binder.clearCallingIdentity();
576 final int result;
577 try {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -0800578 result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700579 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
580 } finally {
581 Binder.restoreCallingIdentity(ident);
582 }
583 switch (result) {
584 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
585 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
586 throw new SecurityException(
587 "Injecting to another application requires INJECT_EVENTS permission");
588 case INPUT_EVENT_INJECTION_SUCCEEDED:
589 return true;
590 case INPUT_EVENT_INJECTION_TIMED_OUT:
591 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
592 return false;
593 case INPUT_EVENT_INJECTION_FAILED:
594 default:
595 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
596 return false;
597 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700598 }
Jeff Brown0029c662011-03-30 02:25:18 -0700599
Jeff Brown8d608662010-08-30 03:02:23 -0700600 /**
601 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700602 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700603 * @return The input device or null if not found.
604 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700605 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700606 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700607 synchronized (mInputDevicesLock) {
608 final int count = mInputDevices.length;
609 for (int i = 0; i < count; i++) {
610 final InputDevice inputDevice = mInputDevices[i];
611 if (inputDevice.getId() == deviceId) {
612 return inputDevice;
613 }
614 }
615 }
616 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700617 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700618
Siarhei Vishniakoua7f99b52017-03-21 17:39:40 -0700619 // Binder call
620 @Override
621 public boolean isInputDeviceEnabled(int deviceId) {
622 return nativeIsInputDeviceEnabled(mPtr, deviceId);
623 }
624
625 // Binder call
626 @Override
627 public void enableInputDevice(int deviceId) {
628 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
629 "enableInputDevice()")) {
630 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
631 }
632 nativeEnableInputDevice(mPtr, deviceId);
633 }
634
635 // Binder call
636 @Override
637 public void disableInputDevice(int deviceId) {
638 if (!checkCallingPermission(android.Manifest.permission.DISABLE_INPUT_DEVICE,
639 "disableInputDevice()")) {
640 throw new SecurityException("Requires DISABLE_INPUT_DEVICE permission");
641 }
642 nativeDisableInputDevice(mPtr, deviceId);
643 }
644
Jeff Brown8d608662010-08-30 03:02:23 -0700645 /**
646 * Gets the ids of all input devices in the system.
647 * @return The input device ids.
648 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700649 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700650 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700651 synchronized (mInputDevicesLock) {
652 final int count = mInputDevices.length;
653 int[] ids = new int[count];
654 for (int i = 0; i < count; i++) {
655 ids[i] = mInputDevices[i].getId();
656 }
657 return ids;
658 }
659 }
660
Jeff Browndaa37532012-05-01 15:54:03 -0700661 /**
662 * Gets all input devices in the system.
663 * @return The array of input devices.
664 */
665 public InputDevice[] getInputDevices() {
666 synchronized (mInputDevicesLock) {
667 return mInputDevices;
668 }
669 }
670
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700671 @Override // Binder call
672 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
673 if (listener == null) {
674 throw new IllegalArgumentException("listener must not be null");
675 }
676
677 synchronized (mInputDevicesLock) {
678 int callingPid = Binder.getCallingPid();
679 if (mInputDevicesChangedListeners.get(callingPid) != null) {
680 throw new SecurityException("The calling process has already "
681 + "registered an InputDevicesChangedListener.");
682 }
683
684 InputDevicesChangedListenerRecord record =
685 new InputDevicesChangedListenerRecord(callingPid, listener);
686 try {
687 IBinder binder = listener.asBinder();
688 binder.linkToDeath(record, 0);
689 } catch (RemoteException ex) {
690 // give up
691 throw new RuntimeException(ex);
692 }
693
694 mInputDevicesChangedListeners.put(callingPid, record);
695 }
696 }
697
698 private void onInputDevicesChangedListenerDied(int pid) {
699 synchronized (mInputDevicesLock) {
700 mInputDevicesChangedListeners.remove(pid);
701 }
702 }
703
704 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700705 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
706 // Scan for changes.
707 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700708 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700709 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700710 final int numListeners;
711 final int[] deviceIdAndGeneration;
712 synchronized (mInputDevicesLock) {
713 if (!mInputDevicesChangedPending) {
714 return;
715 }
716 mInputDevicesChangedPending = false;
717
718 numListeners = mInputDevicesChangedListeners.size();
719 for (int i = 0; i < numListeners; i++) {
720 mTempInputDevicesChangedListenersToNotify.add(
721 mInputDevicesChangedListeners.valueAt(i));
722 }
723
724 final int numDevices = mInputDevices.length;
725 deviceIdAndGeneration = new int[numDevices * 2];
726 for (int i = 0; i < numDevices; i++) {
727 final InputDevice inputDevice = mInputDevices[i];
728 deviceIdAndGeneration[i * 2] = inputDevice.getId();
729 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700730
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700731 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700732 if (!containsInputDeviceWithDescriptor(oldInputDevices,
733 inputDevice.getDescriptor())) {
734 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
735 } else {
736 mTempFullKeyboards.add(inputDevice);
737 }
738 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700739 }
740 }
741
Jeff Browncf39bdf2012-05-18 14:41:19 -0700742 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700743 for (int i = 0; i < numListeners; i++) {
744 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
745 deviceIdAndGeneration);
746 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700747 mTempInputDevicesChangedListenersToNotify.clear();
748
749 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000750 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
751 final int numFullKeyboards = mTempFullKeyboards.size();
752 synchronized (mDataStore) {
753 for (int i = 0; i < numFullKeyboards; i++) {
754 final InputDevice inputDevice = mTempFullKeyboards.get(i);
755 String layout =
756 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
757 if (layout == null) {
758 layout = getDefaultKeyboardLayout(inputDevice);
759 if (layout != null) {
760 setCurrentKeyboardLayoutForInputDevice(
761 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700762 }
763 }
Michael Wright07483422015-10-30 16:20:13 +0000764 if (layout == null) {
765 keyboardsMissingLayout.add(inputDevice);
766 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700767 }
Michael Wright07483422015-10-30 16:20:13 +0000768 }
769
770 if (mNotificationManager != null) {
771 if (!keyboardsMissingLayout.isEmpty()) {
772 if (keyboardsMissingLayout.size() > 1) {
773 // We have more than one keyboard missing a layout, so drop the
774 // user at the generic input methods page so they can pick which
775 // one to set.
776 showMissingKeyboardLayoutNotification(null);
777 } else {
778 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700779 }
780 } else if (mKeyboardLayoutNotificationShown) {
781 hideMissingKeyboardLayoutNotification();
782 }
783 }
784 mTempFullKeyboards.clear();
785 }
786
Michael Wright07483422015-10-30 16:20:13 +0000787 private String getDefaultKeyboardLayout(final InputDevice d) {
788 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
789 // If our locale doesn't have a language for some reason, then we don't really have a
790 // reasonable default.
791 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
792 return null;
793 }
794 final List<KeyboardLayout> layouts = new ArrayList<>();
795 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
796 @Override
797 public void visitKeyboardLayout(Resources resources,
798 int keyboardLayoutResId, KeyboardLayout layout) {
799 // Only select a default when we know the layout is appropriate. For now, this
800 // means its a custom layout for a specific keyboard.
801 if (layout.getVendorId() != d.getVendorId()
802 || layout.getProductId() != d.getProductId()) {
803 return;
804 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800805 final LocaleList locales = layout.getLocales();
806 final int numLocales = locales.size();
807 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
808 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000809 layouts.add(layout);
810 break;
811 }
812 }
813 }
814 });
815
816 if (layouts.isEmpty()) {
817 return null;
818 }
819
820 // First sort so that ones with higher priority are listed at the top
821 Collections.sort(layouts);
822 // Next we want to try to find an exact match of language, country and variant.
823 final int N = layouts.size();
824 for (int i = 0; i < N; i++) {
825 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800826 final LocaleList locales = layout.getLocales();
827 final int numLocales = locales.size();
828 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
829 final Locale locale = locales.get(localeIndex);
830 if (locale.getCountry().equals(systemLocale.getCountry())
831 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000832 return layout.getDescriptor();
833 }
834 }
835 }
836 // Then try an exact match of language and country
837 for (int i = 0; i < N; i++) {
838 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800839 final LocaleList locales = layout.getLocales();
840 final int numLocales = locales.size();
841 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
842 final Locale locale = locales.get(localeIndex);
843 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000844 return layout.getDescriptor();
845 }
846 }
847 }
848
849 // Give up and just use the highest priority layout with matching language
850 return layouts.get(0).getDescriptor();
851 }
852
853 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
854 // Different languages are never compatible
855 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
856 return false;
857 }
858 // If both the system and the keyboard layout have a country specifier, they must be equal.
859 if (!TextUtils.isEmpty(systemLocale.getCountry())
860 && !TextUtils.isEmpty(keyboardLocale.getCountry())
861 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
862 return false;
863 }
864 return true;
865 }
866
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800867 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700868 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
869 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800870 if (inputDeviceDescriptor == null) {
871 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
872 }
873
874 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700875 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800876 }
877 }
878
879 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700880 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800881 TouchCalibration calibration) {
882 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
883 "setTouchCalibrationForInputDevice()")) {
884 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
885 }
886 if (inputDeviceDescriptor == null) {
887 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
888 }
889 if (calibration == null) {
890 throw new IllegalArgumentException("calibration must not be null");
891 }
Jason Gerecked5220742014-03-10 09:47:59 -0700892 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
893 throw new IllegalArgumentException("surfaceRotation value out of bounds");
894 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800895
896 synchronized (mDataStore) {
897 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700898 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
899 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800900 nativeReloadCalibration(mPtr);
901 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800902 } finally {
903 mDataStore.saveIfNeeded();
904 }
905 }
906 }
907
Michael Wright39e5e942015-08-19 22:52:47 +0100908 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100909 public int isInTabletMode() {
910 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
911 "isInTabletMode()")) {
912 throw new SecurityException("Requires TABLET_MODE permission");
913 }
914 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
915 }
916
917 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100918 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100919 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100920 "registerTabletModeChangedListener()")) {
921 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
922 }
923 if (listener == null) {
924 throw new IllegalArgumentException("listener must not be null");
925 }
926
927 synchronized (mTabletModeLock) {
928 final int callingPid = Binder.getCallingPid();
929 if (mTabletModeChangedListeners.get(callingPid) != null) {
930 throw new IllegalStateException("The calling process has already registered "
931 + "a TabletModeChangedListener.");
932 }
933 TabletModeChangedListenerRecord record =
934 new TabletModeChangedListenerRecord(callingPid, listener);
935 try {
936 IBinder binder = listener.asBinder();
937 binder.linkToDeath(record, 0);
938 } catch (RemoteException ex) {
939 throw new RuntimeException(ex);
940 }
941 mTabletModeChangedListeners.put(callingPid, record);
942 }
943 }
944
945 private void onTabletModeChangedListenerDied(int pid) {
946 synchronized (mTabletModeLock) {
947 mTabletModeChangedListeners.remove(pid);
948 }
949 }
950
951 // Must be called on handler
952 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
953 mTempTabletModeChangedListenersToNotify.clear();
954 final int numListeners;
955 synchronized (mTabletModeLock) {
956 numListeners = mTabletModeChangedListeners.size();
957 for (int i = 0; i < numListeners; i++) {
958 mTempTabletModeChangedListenersToNotify.add(
959 mTabletModeChangedListeners.valueAt(i));
960 }
961 }
962 for (int i = 0; i < numListeners; i++) {
963 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
964 whenNanos, inTabletMode);
965 }
966 }
967
Jeff Browncf39bdf2012-05-18 14:41:19 -0700968 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700969 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700970 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700971 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700972 if (device != null) {
973 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700974 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700975 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
976 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
977 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
978 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
979 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700980
981 Resources r = mContext.getResources();
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500982 Notification notification =
983 new Notification.Builder(mContext, SystemNotificationChannels.PHYSICAL_KEYBOARD)
984 .setContentTitle(r.getString(
985 R.string.select_keyboard_layout_notification_title))
986 .setContentText(r.getString(
987 R.string.select_keyboard_layout_notification_message))
988 .setContentIntent(keyboardLayoutIntent)
989 .setSmallIcon(R.drawable.ic_settings_language)
990 .setColor(mContext.getColor(
991 com.android.internal.R.color.system_notification_accent_color))
992 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700993 mNotificationManager.notifyAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -0400994 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700995 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700996 mKeyboardLayoutNotificationShown = true;
997 }
998 }
999
1000 // Must be called on handler.
1001 private void hideMissingKeyboardLayoutNotification() {
1002 if (mKeyboardLayoutNotificationShown) {
1003 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001004 mNotificationManager.cancelAsUser(null,
Chris Wren282cfef2017-03-27 15:01:44 -04001005 SystemMessage.NOTE_SELECT_KEYBOARD_LAYOUT,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07001006 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001007 }
1008 }
1009
1010 // Must be called on handler.
1011 private void updateKeyboardLayouts() {
1012 // Scan all input devices state for keyboard layouts that have been uninstalled.
1013 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1014 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1015 @Override
Michael Wright07483422015-10-30 16:20:13 +00001016 public void visitKeyboardLayout(Resources resources,
1017 int keyboardLayoutResId, KeyboardLayout layout) {
1018 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001019 }
1020 });
1021 synchronized (mDataStore) {
1022 try {
1023 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1024 } finally {
1025 mDataStore.saveIfNeeded();
1026 }
1027 }
1028
1029 // Reload keyboard layouts.
1030 reloadKeyboardLayouts();
1031 }
1032
Jeff Browncf39bdf2012-05-18 14:41:19 -07001033 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1034 String descriptor) {
1035 final int numDevices = inputDevices.length;
1036 for (int i = 0; i < numDevices; i++) {
1037 final InputDevice inputDevice = inputDevices[i];
1038 if (inputDevice.getDescriptor().equals(descriptor)) {
1039 return true;
1040 }
1041 }
1042 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001043 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001044
1045 @Override // Binder call
1046 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001047 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1048 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1049 @Override
Michael Wright07483422015-10-30 16:20:13 +00001050 public void visitKeyboardLayout(Resources resources,
1051 int keyboardLayoutResId, KeyboardLayout layout) {
1052 list.add(layout);
1053 }
1054 });
1055 return list.toArray(new KeyboardLayout[list.size()]);
1056 }
1057
Michael Wrightb0e804a2016-01-04 16:48:53 -05001058 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001059 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1060 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001061 final String[] enabledLayoutDescriptors =
1062 getEnabledKeyboardLayoutsForInputDevice(identifier);
1063 final ArrayList<KeyboardLayout> enabledLayouts =
1064 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1065 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001066 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1067 boolean mHasSeenDeviceSpecificLayout;
1068
1069 @Override
1070 public void visitKeyboardLayout(Resources resources,
1071 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001072 // First check if it's enabled. If the keyboard layout is enabled then we always
1073 // want to return it as a possible layout for the device.
1074 for (String s : enabledLayoutDescriptors) {
1075 if (s != null && s.equals(layout.getDescriptor())) {
1076 enabledLayouts.add(layout);
1077 return;
1078 }
1079 }
1080 // Next find any potential layouts that aren't yet enabled for the device. For
1081 // devices that have special layouts we assume there's a reason that the generic
1082 // layouts don't work for them so we don't want to return them since it's likely
1083 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001084 if (layout.getVendorId() == identifier.getVendorId()
1085 && layout.getProductId() == identifier.getProductId()) {
1086 if (!mHasSeenDeviceSpecificLayout) {
1087 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001088 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001089 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001090 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001091 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1092 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001093 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001094 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001095 }
1096 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001097 final int enabledLayoutSize = enabledLayouts.size();
1098 final int potentialLayoutSize = potentialLayouts.size();
1099 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1100 enabledLayouts.toArray(layouts);
1101 for (int i = 0; i < potentialLayoutSize; i++) {
1102 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1103 }
1104 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001105 }
1106
1107 @Override // Binder call
1108 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1109 if (keyboardLayoutDescriptor == null) {
1110 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1111 }
1112
Jeff Brown6ec6f792012-04-17 16:52:41 -07001113 final KeyboardLayout[] result = new KeyboardLayout[1];
1114 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1115 @Override
Michael Wright07483422015-10-30 16:20:13 +00001116 public void visitKeyboardLayout(Resources resources,
1117 int keyboardLayoutResId, KeyboardLayout layout) {
1118 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001119 }
1120 });
1121 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001122 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001123 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001124 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001125 return result[0];
1126 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001127
Jeff Brown6ec6f792012-04-17 16:52:41 -07001128 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001129 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001130 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1131 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001132 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1133 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001134 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1135 final int priority = resolveInfo.priority;
1136 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001137 }
1138 }
1139
Jeff Brown6ec6f792012-04-17 16:52:41 -07001140 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1141 KeyboardLayoutVisitor visitor) {
1142 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1143 if (d != null) {
1144 final PackageManager pm = mContext.getPackageManager();
1145 try {
1146 ActivityInfo receiver = pm.getReceiverInfo(
1147 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001148 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001149 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1150 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001151 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001152 } catch (NameNotFoundException ex) {
1153 }
1154 }
1155 }
1156
1157 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001158 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001159 Bundle metaData = receiver.metaData;
1160 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001161 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001162 }
1163
1164 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1165 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001166 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001167 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001168 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001169 }
1170
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001171 CharSequence receiverLabel = receiver.loadLabel(pm);
1172 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001173 int priority;
1174 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1175 priority = requestedPriority;
1176 } else {
1177 priority = 0;
1178 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001179
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001180 try {
1181 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1182 XmlResourceParser parser = resources.getXml(configResId);
1183 try {
1184 XmlUtils.beginDocument(parser, "keyboard-layouts");
1185
1186 for (;;) {
1187 XmlUtils.nextElement(parser);
1188 String element = parser.getName();
1189 if (element == null) {
1190 break;
1191 }
1192 if (element.equals("keyboard-layout")) {
1193 TypedArray a = resources.obtainAttributes(
1194 parser, com.android.internal.R.styleable.KeyboardLayout);
1195 try {
1196 String name = a.getString(
1197 com.android.internal.R.styleable.KeyboardLayout_name);
1198 String label = a.getString(
1199 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001200 int keyboardLayoutResId = a.getResourceId(
1201 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1202 0);
Michael Wright07483422015-10-30 16:20:13 +00001203 String languageTags = a.getString(
1204 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001205 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001206 int vid = a.getInt(
1207 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1208 int pid = a.getInt(
1209 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1210
Jeff Brown2f095762012-05-10 21:29:33 -07001211 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001212 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001213 + "attributes in keyboard layout "
1214 + "resource from receiver "
1215 + receiver.packageName + "/" + receiver.name);
1216 } else {
1217 String descriptor = KeyboardLayoutDescriptor.format(
1218 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001219 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001220 KeyboardLayout layout = new KeyboardLayout(
1221 descriptor, label, collection, priority,
1222 locales, vid, pid);
1223 visitor.visitKeyboardLayout(
1224 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001225 }
1226 }
1227 } finally {
1228 a.recycle();
1229 }
1230 } else {
Michael Wright07483422015-10-30 16:20:13 +00001231 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001232 + "' in keyboard layout resource from receiver "
1233 + receiver.packageName + "/" + receiver.name);
1234 }
1235 }
1236 } finally {
1237 parser.close();
1238 }
1239 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001240 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001241 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001242 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001243 }
1244
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001245 @NonNull
1246 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001247 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001248 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001249 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001250 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001251 }
1252
RoboErikfb290df2013-12-16 11:27:55 -08001253 /**
1254 * Builds a layout descriptor for the vendor/product. This returns the
1255 * descriptor for ids that aren't useful (such as the default 0, 0).
1256 */
1257 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1258 if (identifier == null || identifier.getDescriptor() == null) {
1259 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001260 }
1261
RoboErikfb290df2013-12-16 11:27:55 -08001262 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1263 return identifier.getDescriptor();
1264 }
1265 StringBuilder bob = new StringBuilder();
1266 bob.append("vendor:").append(identifier.getVendorId());
1267 bob.append(",product:").append(identifier.getProductId());
1268 return bob.toString();
1269 }
1270
1271 @Override // Binder call
1272 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1273
1274 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001275 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001276 String layout = null;
1277 // try loading it using the layout descriptor if we have it
1278 layout = mDataStore.getCurrentKeyboardLayout(key);
1279 if (layout == null && !key.equals(identifier.getDescriptor())) {
1280 // if it doesn't exist fall back to the device descriptor
1281 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1282 }
1283 if (DEBUG) {
1284 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1285 + layout);
1286 }
1287 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001288 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001289 }
1290
1291 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001292 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001293 String keyboardLayoutDescriptor) {
1294 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001295 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001296 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1297 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001298 if (keyboardLayoutDescriptor == null) {
1299 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1300 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001301
RoboErikfb290df2013-12-16 11:27:55 -08001302 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001303 synchronized (mDataStore) {
1304 try {
RoboErikfb290df2013-12-16 11:27:55 -08001305 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1306 if (DEBUG) {
1307 Slog.d(TAG, "Saved keyboard layout using " + key);
1308 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001309 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1310 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001311 } finally {
1312 mDataStore.saveIfNeeded();
1313 }
1314 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001315 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001316
Jeff Browncf39bdf2012-05-18 14:41:19 -07001317 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001318 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001319 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001320 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001321 String[] layouts = mDataStore.getKeyboardLayouts(key);
1322 if ((layouts == null || layouts.length == 0)
1323 && !key.equals(identifier.getDescriptor())) {
1324 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1325 }
1326 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001327 }
1328 }
1329
1330 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001331 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001332 String keyboardLayoutDescriptor) {
1333 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1334 "addKeyboardLayoutForInputDevice()")) {
1335 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 }
1340
RoboErikfb290df2013-12-16 11:27:55 -08001341 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001342 synchronized (mDataStore) {
1343 try {
RoboErikfb290df2013-12-16 11:27:55 -08001344 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1345 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1346 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1347 }
1348 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001349 && !Objects.equals(oldLayout,
1350 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001351 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1352 }
1353 } finally {
1354 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001355 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001356 }
1357 }
1358
1359 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001360 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001361 String keyboardLayoutDescriptor) {
1362 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1363 "removeKeyboardLayoutForInputDevice()")) {
1364 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1365 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001366 if (keyboardLayoutDescriptor == null) {
1367 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1368 }
1369
RoboErikfb290df2013-12-16 11:27:55 -08001370 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001371 synchronized (mDataStore) {
1372 try {
RoboErikfb290df2013-12-16 11:27:55 -08001373 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1374 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1375 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1376 }
1377 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1378 if (!key.equals(identifier.getDescriptor())) {
1379 // We need to remove from both places to ensure it is gone
1380 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1381 keyboardLayoutDescriptor);
1382 }
Narayan Kamath607223f2018-02-19 14:09:02 +00001383 if (removed && !Objects.equals(oldLayout,
RoboErikfb290df2013-12-16 11:27:55 -08001384 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001385 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1386 }
1387 } finally {
1388 mDataStore.saveIfNeeded();
1389 }
1390 }
1391 }
1392
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001393 public void switchKeyboardLayout(int deviceId, int direction) {
1394 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001395 }
1396
1397 // Must be called on handler.
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001398 private void handleSwitchKeyboardLayout(int deviceId, int direction) {
1399 final InputDevice device = getInputDevice(deviceId);
1400 if (device != null) {
1401 final boolean changed;
1402 final String keyboardLayoutDescriptor;
1403
1404 String key = getLayoutDescriptor(device.getIdentifier());
1405 synchronized (mDataStore) {
1406 try {
1407 changed = mDataStore.switchKeyboardLayout(key, direction);
1408 keyboardLayoutDescriptor = mDataStore.getCurrentKeyboardLayout(
1409 key);
1410 } finally {
1411 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001412 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001413 }
1414
1415 if (changed) {
1416 if (mSwitchedKeyboardLayoutToast != null) {
1417 mSwitchedKeyboardLayoutToast.cancel();
1418 mSwitchedKeyboardLayoutToast = null;
1419 }
1420 if (keyboardLayoutDescriptor != null) {
1421 KeyboardLayout keyboardLayout = getKeyboardLayout(keyboardLayoutDescriptor);
1422 if (keyboardLayout != null) {
1423 mSwitchedKeyboardLayoutToast = Toast.makeText(
1424 mContext, keyboardLayout.getLabel(), Toast.LENGTH_SHORT);
1425 mSwitchedKeyboardLayoutToast.show();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001426 }
1427 }
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001428
1429 reloadKeyboardLayouts();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001430 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001431 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001432 }
1433
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001434 public void setInputWindows(InputWindowHandle[] windowHandles,
Arthur Hung39134b22018-08-14 11:58:28 +08001435 InputWindowHandle focusedWindowHandle, int displayId) {
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001436 final IWindow newFocusedWindow =
1437 focusedWindowHandle != null ? focusedWindowHandle.clientWindow : null;
1438 if (mFocusedWindow != newFocusedWindow) {
1439 mFocusedWindow = newFocusedWindow;
1440 if (mFocusedWindowHasCapture) {
1441 setPointerCapture(false);
1442 }
1443 }
Arthur Hung39134b22018-08-14 11:58:28 +08001444 nativeSetInputWindows(mPtr, windowHandles, displayId);
Jeff Brown349703e2010-06-22 01:27:15 -07001445 }
RoboErikfb290df2013-12-16 11:27:55 -08001446
Jeff Brown9302c872011-07-13 22:51:29 -07001447 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001448 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001449 }
RoboErikfb290df2013-12-16 11:27:55 -08001450
Vladislav Kaznacheev3787de12016-12-21 10:36:35 -08001451 @Override
1452 public void requestPointerCapture(IBinder windowToken, boolean enabled) {
1453 if (mFocusedWindow == null || mFocusedWindow.asBinder() != windowToken) {
1454 Slog.e(TAG, "requestPointerCapture called for a window that has no focus: "
1455 + windowToken);
1456 return;
1457 }
1458 if (mFocusedWindowHasCapture == enabled) {
1459 Slog.i(TAG, "requestPointerCapture: already " + (enabled ? "enabled" : "disabled"));
1460 return;
1461 }
1462 setPointerCapture(enabled);
1463 try {
1464 mFocusedWindow.dispatchPointerCaptureChanged(enabled);
1465 } catch (RemoteException ex) {
1466 /* ignore */
1467 }
1468 }
1469
1470 private void setPointerCapture(boolean enabled) {
1471 mFocusedWindowHasCapture = enabled;
1472 nativeSetPointerCapture(mPtr, enabled);
1473 }
1474
Jeff Brown349703e2010-06-22 01:27:15 -07001475 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001476 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001477 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001478
1479 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001480 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001481 }
1482
Jeff Browne6504122010-09-27 14:52:15 -07001483 /**
1484 * Atomically transfers touch focus from one window to another as identified by
1485 * their input channels. It is possible for multiple windows to have
1486 * touch focus if they support split touch dispatch
1487 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1488 * method only transfers touch focus of the specified window without affecting
1489 * other windows that may also have touch focus at the same time.
1490 * @param fromChannel The channel of a window that currently has touch focus.
1491 * @param toChannel The channel of the window that should receive touch focus in
1492 * place of the first.
1493 * @return True if the transfer was successful. False if the window with the
1494 * specified channel did not actually have touch focus at the time of the request.
1495 */
1496 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1497 if (fromChannel == null) {
1498 throw new IllegalArgumentException("fromChannel must not be null.");
1499 }
1500 if (toChannel == null) {
1501 throw new IllegalArgumentException("toChannel must not be null.");
1502 }
Jeff Brown4532e612012-04-05 14:27:12 -07001503 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001504 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001505
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001506 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001507 public void tryPointerSpeed(int speed) {
1508 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1509 "tryPointerSpeed()")) {
1510 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1511 }
1512
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001513 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1514 throw new IllegalArgumentException("speed out of range");
1515 }
1516
Jeff Brownac143512012-04-05 18:57:33 -07001517 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001518 }
1519
1520 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001521 int speed = getPointerSpeedSetting();
1522 setPointerSpeedUnchecked(speed);
1523 }
1524
1525 private void setPointerSpeedUnchecked(int speed) {
1526 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1527 InputManager.MAX_POINTER_SPEED);
1528 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001529 }
1530
1531 private void registerPointerSpeedSettingObserver() {
1532 mContext.getContentResolver().registerContentObserver(
1533 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001534 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001535 @Override
1536 public void onChange(boolean selfChange) {
1537 updatePointerSpeedFromSettings();
1538 }
Jeff Brownd4935962012-09-25 13:27:20 -07001539 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001540 }
1541
Jeff Brownac143512012-04-05 18:57:33 -07001542 private int getPointerSpeedSetting() {
1543 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001544 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001545 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1546 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001547 } catch (SettingNotFoundException snfe) {
1548 }
1549 return speed;
1550 }
1551
Jeff Browndaf4a122011-08-26 17:14:14 -07001552 public void updateShowTouchesFromSettings() {
1553 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001554 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001555 }
1556
1557 private void registerShowTouchesSettingObserver() {
1558 mContext.getContentResolver().registerContentObserver(
1559 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001560 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001561 @Override
1562 public void onChange(boolean selfChange) {
1563 updateShowTouchesFromSettings();
1564 }
Jeff Brownd4935962012-09-25 13:27:20 -07001565 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001566 }
1567
Jun Mukaie4e75da2015-12-15 16:19:20 -08001568 public void updateAccessibilityLargePointerFromSettings() {
1569 final int accessibilityConfig = Settings.Secure.getIntForUser(
1570 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1571 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001572 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001573 nativeReloadPointerIcons(mPtr);
1574 }
1575
Jun Mukai19a56012015-11-24 11:25:52 -08001576 private void registerAccessibilityLargePointerSettingObserver() {
1577 mContext.getContentResolver().registerContentObserver(
1578 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1579 new ContentObserver(mHandler) {
1580 @Override
1581 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001582 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001583 }
1584 }, UserHandle.USER_ALL);
1585 }
1586
Jeff Browndaf4a122011-08-26 17:14:14 -07001587 private int getShowTouchesSetting(int defaultValue) {
1588 int result = defaultValue;
1589 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001590 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1591 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001592 } catch (SettingNotFoundException snfe) {
1593 }
1594 return result;
1595 }
1596
Jeff Browna47425a2012-04-13 04:09:27 -07001597 // Binder call
1598 @Override
1599 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1600 if (repeat >= pattern.length) {
1601 throw new ArrayIndexOutOfBoundsException();
1602 }
1603
1604 VibratorToken v;
1605 synchronized (mVibratorLock) {
1606 v = mVibratorTokens.get(token);
1607 if (v == null) {
1608 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1609 try {
1610 token.linkToDeath(v, 0);
1611 } catch (RemoteException ex) {
1612 // give up
1613 throw new RuntimeException(ex);
1614 }
1615 mVibratorTokens.put(token, v);
1616 }
1617 }
1618
1619 synchronized (v) {
1620 v.mVibrating = true;
1621 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1622 }
1623 }
1624
1625 // Binder call
1626 @Override
1627 public void cancelVibrate(int deviceId, IBinder token) {
1628 VibratorToken v;
1629 synchronized (mVibratorLock) {
1630 v = mVibratorTokens.get(token);
1631 if (v == null || v.mDeviceId != deviceId) {
1632 return; // nothing to cancel
1633 }
1634 }
1635
1636 cancelVibrateIfNeeded(v);
1637 }
1638
1639 void onVibratorTokenDied(VibratorToken v) {
1640 synchronized (mVibratorLock) {
1641 mVibratorTokens.remove(v.mToken);
1642 }
1643
1644 cancelVibrateIfNeeded(v);
1645 }
1646
1647 private void cancelVibrateIfNeeded(VibratorToken v) {
1648 synchronized (v) {
1649 if (v.mVibrating) {
1650 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1651 v.mVibrating = false;
1652 }
1653 }
1654 }
1655
Jun Mukai19a56012015-11-24 11:25:52 -08001656 // Binder call
1657 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001658 public void setPointerIconType(int iconId) {
1659 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001660 }
Jun Mukai1db53972015-09-11 18:08:31 -07001661
Jun Mukaid4eaef72015-10-30 15:54:33 -07001662 // Binder call
1663 @Override
1664 public void setCustomPointerIcon(PointerIcon icon) {
Michael Wrightb004b512017-01-18 18:09:29 +00001665 Preconditions.checkNotNull(icon);
Jun Mukaid4eaef72015-10-30 15:54:33 -07001666 nativeSetCustomPointerIcon(mPtr, icon);
1667 }
1668
Jeff Brown4532e612012-04-05 14:27:12 -07001669 @Override
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08001670 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001671 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown4532e612012-04-05 14:27:12 -07001672
1673 pw.println("INPUT MANAGER (dumpsys input)\n");
1674 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001675 if (dumpStr != null) {
1676 pw.println(dumpStr);
1677 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001678 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001679
Jeff Brownac143512012-04-05 18:57:33 -07001680 private boolean checkCallingPermission(String permission, String func) {
1681 // Quick check: if the calling permission is me, it's all okay.
1682 if (Binder.getCallingPid() == Process.myPid()) {
1683 return true;
1684 }
1685
1686 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1687 return true;
1688 }
1689 String msg = "Permission Denial: " + func + " from pid="
1690 + Binder.getCallingPid()
1691 + ", uid=" + Binder.getCallingUid()
1692 + " requires " + permission;
1693 Slog.w(TAG, msg);
1694 return false;
1695 }
1696
Jeff Brown4532e612012-04-05 14:27:12 -07001697 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001698 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001699 public void monitor() {
1700 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001701 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001702 }
1703
Andrii Kulianed76e742017-06-26 14:57:02 -07001704 // Binder call
1705 @Override
1706 public IInputForwarder createInputForwarder(int displayId) throws RemoteException {
1707 if (!checkCallingPermission(android.Manifest.permission.INJECT_EVENTS,
1708 "createInputForwarder()")) {
1709 throw new SecurityException("Requires INJECT_EVENTS permission");
1710 }
1711 final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
1712 final Display display = displayManager.getDisplay(displayId);
1713 if (display == null) {
1714 throw new IllegalArgumentException(
1715 "Can't create input forwarder for non-existent displayId: " + displayId);
1716 }
1717 final int callingUid = Binder.getCallingUid();
1718 final int displayOwnerUid = display.getOwnerUid();
1719 if (callingUid != displayOwnerUid) {
1720 throw new SecurityException(
1721 "Only owner of the display can forward input events to it.");
1722 }
1723
1724 return new InputForwarder(displayId);
1725 }
1726
Jeff Brown4532e612012-04-05 14:27:12 -07001727 // Native callback.
1728 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001729 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001730 }
1731
1732 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001733 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1734 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001735 if (!mInputDevicesChangedPending) {
1736 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001737 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1738 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001739 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001740
1741 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001742 }
1743 }
1744
1745 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001746 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1747 if (DEBUG) {
1748 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1749 + ", mask=" + Integer.toHexString(switchMask));
1750 }
1751
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001752 if ((switchMask & SW_LID_BIT) != 0) {
1753 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001754 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001755 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001756
Michael Wright3818c922014-09-02 13:59:07 -07001757 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001758 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001759 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1760 }
1761
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001762 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1763 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1764 switchMask);
1765 }
Michael Wright39e5e942015-08-19 22:52:47 +01001766
Michael Wright9209c9c2015-09-03 17:57:01 +01001767 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001768 SomeArgs args = SomeArgs.obtain();
1769 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1770 args.argi2 = (int) (whenNanos >> 32);
1771 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1772 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1773 args).sendToTarget();
1774 }
Jeff Brown4532e612012-04-05 14:27:12 -07001775 }
1776
1777 // Native callback.
1778 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001779 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001780 }
1781
1782 // Native callback.
1783 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001784 InputWindowHandle inputWindowHandle, String reason) {
1785 return mWindowManagerCallbacks.notifyANR(
1786 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001787 }
1788
1789 // Native callback.
1790 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1791 synchronized (mInputFilterLock) {
1792 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001793 try {
1794 mInputFilter.filterInputEvent(event, policyFlags);
1795 } catch (RemoteException e) {
1796 /* ignore */
1797 }
Jeff Brown4532e612012-04-05 14:27:12 -07001798 return false;
1799 }
1800 }
1801 event.recycle();
1802 return true;
1803 }
1804
1805 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001806 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1807 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001808 }
1809
1810 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001811 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1812 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001813 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001814 }
1815
1816 // Native callback.
1817 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1818 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001819 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001820 }
1821
1822 // Native callback.
1823 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1824 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001825 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001826 }
1827
1828 // Native callback.
1829 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1830 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1831 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1832 }
1833
1834 // Native callback.
1835 private int getVirtualKeyQuietTimeMillis() {
1836 return mContext.getResources().getInteger(
1837 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1838 }
1839
1840 // Native callback.
1841 private String[] getExcludedDeviceNames() {
1842 ArrayList<String> names = new ArrayList<String>();
1843
1844 // Read partner-provided list of excluded input devices
1845 XmlPullParser parser = null;
1846 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001847 final File[] baseDirs = {
1848 Environment.getRootDirectory(),
1849 Environment.getVendorDirectory()
1850 };
1851 for (File baseDir: baseDirs) {
1852 File confFile = new File(baseDir, EXCLUDED_DEVICES_PATH);
1853 FileReader confreader = null;
1854 try {
1855 confreader = new FileReader(confFile);
1856 parser = Xml.newPullParser();
1857 parser.setInput(confreader);
1858 XmlUtils.beginDocument(parser, "devices");
Jeff Brown4532e612012-04-05 14:27:12 -07001859
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001860 while (true) {
1861 XmlUtils.nextElement(parser);
1862 if (!"device".equals(parser.getName())) {
1863 break;
1864 }
1865 String name = parser.getAttributeValue(null, "name");
1866 if (name != null) {
1867 names.add(name);
1868 }
Jeff Brown4532e612012-04-05 14:27:12 -07001869 }
Tsukasa Hashimotoea12b552018-09-11 16:47:22 +09001870 } catch (FileNotFoundException e) {
1871 // It's ok if the file does not exist.
1872 } catch (Exception e) {
1873 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1874 } finally {
1875 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001876 }
Jeff Brown4532e612012-04-05 14:27:12 -07001877 }
1878
1879 return names.toArray(new String[names.size()]);
1880 }
1881
1882 // Native callback.
1883 private int getKeyRepeatTimeout() {
1884 return ViewConfiguration.getKeyRepeatTimeout();
1885 }
1886
1887 // Native callback.
1888 private int getKeyRepeatDelay() {
1889 return ViewConfiguration.getKeyRepeatDelay();
1890 }
1891
1892 // Native callback.
1893 private int getHoverTapTimeout() {
1894 return ViewConfiguration.getHoverTapTimeout();
1895 }
1896
1897 // Native callback.
1898 private int getHoverTapSlop() {
1899 return ViewConfiguration.getHoverTapSlop();
1900 }
1901
1902 // Native callback.
1903 private int getDoubleTapTimeout() {
1904 return ViewConfiguration.getDoubleTapTimeout();
1905 }
1906
1907 // Native callback.
1908 private int getLongPressTimeout() {
1909 return ViewConfiguration.getLongPressTimeout();
1910 }
1911
1912 // Native callback.
1913 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001914 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001915 }
1916
1917 // Native callback.
1918 private PointerIcon getPointerIcon() {
1919 return PointerIcon.getDefaultIcon(mContext);
1920 }
1921
Jeff Brown6ec6f792012-04-17 16:52:41 -07001922 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001923 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001924 if (!mSystemReady) {
1925 return null;
1926 }
1927
RoboErikfb290df2013-12-16 11:27:55 -08001928 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001929 if (keyboardLayoutDescriptor == null) {
1930 return null;
1931 }
1932
1933 final String[] result = new String[2];
1934 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1935 @Override
Michael Wright07483422015-10-30 16:20:13 +00001936 public void visitKeyboardLayout(Resources resources,
1937 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001938 try {
Michael Wright07483422015-10-30 16:20:13 +00001939 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001940 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07001941 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07001942 } catch (IOException ex) {
1943 } catch (NotFoundException ex) {
1944 }
1945 }
1946 });
1947 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001948 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001949 + keyboardLayoutDescriptor + "'.");
1950 return null;
1951 }
1952 return result;
1953 }
1954
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001955 // Native callback.
1956 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07001957 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
1958 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
1959 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07001960 }
1961 return null;
1962 }
1963
Jeff Brown4532e612012-04-05 14:27:12 -07001964 /**
1965 * Callback interface implemented by the Window Manager.
1966 */
Jeff Browna9d131c2012-09-20 16:48:17 -07001967 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07001968 public void notifyConfigurationChanged();
1969
1970 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
1971
Michael Wright3818c922014-09-02 13:59:07 -07001972 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
1973
Jeff Brown4532e612012-04-05 14:27:12 -07001974 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
1975
1976 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001977 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001978
Jeff Brown037c33e2014-04-09 00:31:55 -07001979 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001980
Michael Wright70af00a2014-09-03 19:30:20 -07001981 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001982
1983 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
1984 KeyEvent event, int policyFlags);
1985
1986 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1987 KeyEvent event, int policyFlags);
1988
1989 public int getPointerLayer();
1990 }
1991
1992 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001993 * Callback interface implemented by WiredAccessoryObserver.
1994 */
1995 public interface WiredAccessoryCallbacks {
1996 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07001997 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001998 }
1999
2000 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002001 * Private handler for the input manager.
2002 */
2003 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002004 public InputManagerHandler(Looper looper) {
2005 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002006 }
2007
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002008 @Override
2009 public void handleMessage(Message msg) {
2010 switch (msg.what) {
2011 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002012 deliverInputDevicesChanged((InputDevice[])msg.obj);
2013 break;
Yohei Yukawa2d9accb2018-03-07 19:15:15 -08002014 case MSG_SWITCH_KEYBOARD_LAYOUT:
2015 handleSwitchKeyboardLayout(msg.arg1, msg.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002016 break;
2017 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2018 reloadKeyboardLayouts();
2019 break;
2020 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2021 updateKeyboardLayouts();
2022 break;
2023 case MSG_RELOAD_DEVICE_ALIASES:
2024 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002025 break;
Yohei Yukawa19a40002018-03-07 19:15:38 -08002026 case MSG_DELIVER_TABLET_MODE_CHANGED:
Michael Wright39e5e942015-08-19 22:52:47 +01002027 SomeArgs args = (SomeArgs) msg.obj;
2028 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2029 boolean inTabletMode = (boolean) args.arg1;
2030 deliverTabletModeChanged(whenNanos, inTabletMode);
2031 break;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002032 }
2033 }
2034 }
2035
2036 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002037 * Hosting interface for input filters to call back into the input manager.
2038 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002039 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002040 private boolean mDisconnected;
2041
2042 public void disconnectLocked() {
2043 mDisconnected = true;
2044 }
2045
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002046 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002047 public void sendInputEvent(InputEvent event, int policyFlags) {
2048 if (event == null) {
2049 throw new IllegalArgumentException("event must not be null");
2050 }
2051
2052 synchronized (mInputFilterLock) {
2053 if (!mDisconnected) {
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002054 nativeInjectInputEvent(mPtr, event, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002055 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002056 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2057 }
2058 }
2059 }
2060 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002061
2062 private static final class KeyboardLayoutDescriptor {
2063 public String packageName;
2064 public String receiverName;
2065 public String keyboardLayoutName;
2066
2067 public static String format(String packageName,
2068 String receiverName, String keyboardName) {
2069 return packageName + "/" + receiverName + "/" + keyboardName;
2070 }
2071
2072 public static KeyboardLayoutDescriptor parse(String descriptor) {
2073 int pos = descriptor.indexOf('/');
2074 if (pos < 0 || pos + 1 == descriptor.length()) {
2075 return null;
2076 }
2077 int pos2 = descriptor.indexOf('/', pos + 1);
2078 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2079 return null;
2080 }
2081
2082 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2083 result.packageName = descriptor.substring(0, pos);
2084 result.receiverName = descriptor.substring(pos + 1, pos2);
2085 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2086 return result;
2087 }
2088 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002089
Jeff Brown6ec6f792012-04-17 16:52:41 -07002090 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002091 void visitKeyboardLayout(Resources resources,
2092 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002093 }
2094
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002095 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2096 private final int mPid;
2097 private final IInputDevicesChangedListener mListener;
2098
2099 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2100 mPid = pid;
2101 mListener = listener;
2102 }
2103
2104 @Override
2105 public void binderDied() {
2106 if (DEBUG) {
2107 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2108 }
2109 onInputDevicesChangedListenerDied(mPid);
2110 }
2111
2112 public void notifyInputDevicesChanged(int[] info) {
2113 try {
2114 mListener.onInputDevicesChanged(info);
2115 } catch (RemoteException ex) {
2116 Slog.w(TAG, "Failed to notify process "
2117 + mPid + " that input devices changed, assuming it died.", ex);
2118 binderDied();
2119 }
2120 }
2121 }
Jeff Browna47425a2012-04-13 04:09:27 -07002122
Michael Wright39e5e942015-08-19 22:52:47 +01002123 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2124 private final int mPid;
2125 private final ITabletModeChangedListener mListener;
2126
2127 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2128 mPid = pid;
2129 mListener = listener;
2130 }
2131
2132 @Override
2133 public void binderDied() {
2134 if (DEBUG) {
2135 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2136 }
2137 onTabletModeChangedListenerDied(mPid);
2138 }
2139
2140 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2141 try {
2142 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2143 } catch (RemoteException ex) {
2144 Slog.w(TAG, "Failed to notify process " + mPid +
2145 " that tablet mode changed, assuming it died.", ex);
2146 binderDied();
2147 }
2148 }
2149 }
2150
Jeff Browna47425a2012-04-13 04:09:27 -07002151 private final class VibratorToken implements DeathRecipient {
2152 public final int mDeviceId;
2153 public final IBinder mToken;
2154 public final int mTokenValue;
2155
2156 public boolean mVibrating;
2157
2158 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2159 mDeviceId = deviceId;
2160 mToken = token;
2161 mTokenValue = tokenValue;
2162 }
2163
2164 @Override
2165 public void binderDied() {
2166 if (DEBUG) {
2167 Slog.d(TAG, "Vibrator token died.");
2168 }
2169 onVibratorTokenDied(this);
2170 }
2171 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002172
2173 private final class LocalService extends InputManagerInternal {
2174 @Override
Siarhei Vishniakou2eb0f8f2018-07-06 23:30:12 +01002175 public void setDisplayViewports(List<DisplayViewport> viewports) {
2176 setDisplayViewportsInternal(viewports);
Jeff Brown4ccb8232014-01-16 22:16:42 -08002177 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002178
2179 @Override
Siarhei Vishniakou85ddfff2018-01-31 16:49:36 -08002180 public boolean injectInputEvent(InputEvent event, int mode) {
2181 return injectInputEventInternal(event, mode);
Jeff Brownca9bc702014-02-11 14:32:56 -08002182 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002183
2184 @Override
2185 public void setInteractive(boolean interactive) {
2186 nativeSetInteractive(mPtr, interactive);
2187 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002188
2189 @Override
Andrii Kulian112d0562016-03-08 10:44:22 -08002190 public void toggleCapsLock(int deviceId) {
2191 nativeToggleCapsLock(mPtr, deviceId);
2192 }
Adrian Roos99182342016-06-15 15:30:46 -07002193
2194 @Override
2195 public void setPulseGestureEnabled(boolean enabled) {
2196 if (mDoubleTouchGestureEnableFile != null) {
2197 FileWriter writer = null;
2198 try {
2199 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2200 writer.write(enabled ? "1" : "0");
2201 } catch (IOException e) {
2202 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2203 } finally {
2204 IoUtils.closeQuietly(writer);
2205 }
2206 }
2207 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002208 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002209}