blob: 74095acca16a41641190969136cbb60db524a9a8 [file] [log] [blame]
Jeff Brown46b9ac02010-04-22 18:58:52 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown4532e612012-04-05 14:27:12 -070017package com.android.server.input;
Jeff Brown46b9ac02010-04-22 18:58:52 -070018
Yohei Yukawa5660fad2016-01-27 22:04:09 -080019import android.annotation.NonNull;
Yohei Yukawab097b822015-12-01 10:43:08 -080020import android.annotation.Nullable;
Adrian Roos99182342016-06-15 15:30:46 -070021import android.os.Build;
Yohei Yukawa23cbe852016-05-17 16:42:58 -070022import android.os.LocaleList;
Adrian Roos99182342016-06-15 15:30:46 -070023import android.util.Log;
Jeff Brownca9bc702014-02-11 14:32:56 -080024import android.view.Display;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080025import com.android.internal.inputmethod.InputMethodSubtypeHandle;
Michael Wright39e5e942015-08-19 22:52:47 +010026import com.android.internal.os.SomeArgs;
Jeff Browncf39bdf2012-05-18 14:41:19 -070027import com.android.internal.R;
Jeff Brown46b9ac02010-04-22 18:58:52 -070028import com.android.internal.util.XmlUtils;
Jeff Brown4ccb8232014-01-16 22:16:42 -080029import com.android.server.DisplayThread;
30import com.android.server.LocalServices;
Jeff Brown89ef0722011-08-10 16:25:21 -070031import com.android.server.Watchdog;
Jeff Brown46b9ac02010-04-22 18:58:52 -070032
33import org.xmlpull.v1.XmlPullParser;
34
Jeff Browna3bc5652012-04-17 11:42:25 -070035import android.Manifest;
Jeff Browncf39bdf2012-05-18 14:41:19 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Brown5bbd4b42012-04-20 19:28:00 -070039import android.bluetooth.BluetoothAdapter;
40import android.bluetooth.BluetoothDevice;
Jeff Brown6ec6f792012-04-17 16:52:41 -070041import android.content.BroadcastReceiver;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070042import android.content.ComponentName;
Jeff Brown46b9ac02010-04-22 18:58:52 -070043import android.content.Context;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070044import android.content.Intent;
Jeff Brown6ec6f792012-04-17 16:52:41 -070045import android.content.IntentFilter;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070046import android.content.pm.ActivityInfo;
Michael Wright8ebac232014-09-18 18:29:49 -070047import android.content.pm.ApplicationInfo;
Jeff Brown349703e2010-06-22 01:27:15 -070048import android.content.pm.PackageManager;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070049import android.content.pm.ResolveInfo;
50import android.content.pm.PackageManager.NameNotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070051import android.content.res.Resources;
Jeff Brown6ec6f792012-04-17 16:52:41 -070052import android.content.res.Resources.NotFoundException;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070053import android.content.res.TypedArray;
54import android.content.res.XmlResourceParser;
Jeff Brown1a84fd12011-06-02 01:26:32 -070055import android.database.ContentObserver;
Jeff Brown4ccb8232014-01-16 22:16:42 -080056import android.hardware.display.DisplayViewport;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070057import android.hardware.input.IInputDevicesChangedListener;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070058import android.hardware.input.IInputManager;
RoboErikfb290df2013-12-16 11:27:55 -080059import android.hardware.input.InputDeviceIdentifier;
Jeff Brownac143512012-04-05 18:57:33 -070060import android.hardware.input.InputManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080061import android.hardware.input.InputManagerInternal;
Michael Wright39e5e942015-08-19 22:52:47 +010062import android.hardware.input.ITabletModeChangedListener;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070063import android.hardware.input.KeyboardLayout;
Jason Gerecked6396d62014-01-27 18:30:37 -080064import android.hardware.input.TouchCalibration;
Jeff Brown4532e612012-04-05 14:27:12 -070065import android.os.Binder;
Jeff Brown9f25b7f2012-04-10 14:30:49 -070066import android.os.Bundle;
Jeff Brown46b9ac02010-04-22 18:58:52 -070067import android.os.Environment;
Jeff Brown4532e612012-04-05 14:27:12 -070068import android.os.Handler;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070069import android.os.IBinder;
Jeff Browna9d131c2012-09-20 16:48:17 -070070import android.os.Looper;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070071import android.os.Message;
Jeff Brown05dc66a2011-03-02 14:41:58 -080072import android.os.MessageQueue;
Jeff Brownac143512012-04-05 18:57:33 -070073import android.os.Process;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070074import android.os.RemoteException;
Michael Wrightd5f7ed92016-01-19 11:23:51 -080075import android.os.ResultReceiver;
76import android.os.ShellCommand;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070077import android.os.UserHandle;
Jeff Brown1a84fd12011-06-02 01:26:32 -070078import android.provider.Settings;
79import android.provider.Settings.SettingNotFoundException;
Michael Wright07483422015-10-30 16:20:13 +000080import android.text.TextUtils;
Jeff Brown46b9ac02010-04-22 18:58:52 -070081import android.util.Slog;
Jeff Brownaf9e8d32012-04-12 17:32:48 -070082import android.util.SparseArray;
Jeff Brown46b9ac02010-04-22 18:58:52 -070083import android.util.Xml;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -070084import android.view.IInputFilter;
85import android.view.IInputFilterHost;
Jeff Brown46b9ac02010-04-22 18:58:52 -070086import android.view.InputChannel;
Jeff Brown8d608662010-08-30 03:02:23 -070087import android.view.InputDevice;
Jeff Brown6ec402b2010-07-28 15:48:59 -070088import android.view.InputEvent;
Jeff Brown1f245102010-11-18 20:53:46 -080089import android.view.KeyEvent;
Jeff Brown2352b972011-04-12 22:39:53 -070090import android.view.PointerIcon;
Jason Gerecked5220742014-03-10 09:47:59 -070091import android.view.Surface;
Jeff Browna4547672011-03-02 21:38:11 -080092import android.view.ViewConfiguration;
Jeff Brown0029c662011-03-30 02:25:18 -070093import android.view.WindowManagerPolicy;
Yohei Yukawab097b822015-12-01 10:43:08 -080094import android.view.inputmethod.InputMethod;
95import android.view.inputmethod.InputMethodInfo;
96import android.view.inputmethod.InputMethodSubtype;
Jeff Browncf39bdf2012-05-18 14:41:19 -070097import android.widget.Toast;
Jeff Brown46b9ac02010-04-22 18:58:52 -070098
Jeff Brown46b9ac02010-04-22 18:58:52 -070099import java.io.File;
Jeff Brown4532e612012-04-05 14:27:12 -0700100import java.io.FileDescriptor;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700101import java.io.FileNotFoundException;
102import java.io.FileReader;
Adrian Roos99182342016-06-15 15:30:46 -0700103import java.io.FileWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700104import java.io.IOException;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700105import java.io.InputStreamReader;
Adrian Roos99182342016-06-15 15:30:46 -0700106import java.io.OutputStream;
107import java.io.OutputStreamWriter;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700108import java.io.PrintWriter;
109import java.util.ArrayList;
Michael Wrightd5f7ed92016-01-19 11:23:51 -0800110import java.util.Arrays;
Michael Wright07483422015-10-30 16:20:13 +0000111import java.util.Collections;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700112import java.util.HashMap;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700113import java.util.HashSet;
Michael Wright39e5e942015-08-19 22:52:47 +0100114import java.util.List;
Michael Wright07483422015-10-30 16:20:13 +0000115import java.util.Locale;
Jeff Browna3bc5652012-04-17 11:42:25 -0700116
Adrian Roos99182342016-06-15 15:30:46 -0700117import libcore.io.IoUtils;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700118import libcore.io.Streams;
Jeff Browna3bc5652012-04-17 11:42:25 -0700119import libcore.util.Objects;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700120
121/*
122 * Wraps the C++ InputManager and provides its callbacks.
Jeff Brown46b9ac02010-04-22 18:58:52 -0700123 */
Jeff Brownd728bf52012-09-08 18:05:28 -0700124public class InputManagerService extends IInputManager.Stub
Jeff Brown4ccb8232014-01-16 22:16:42 -0800125 implements Watchdog.Monitor {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700126 static final String TAG = "InputManager";
Jeff Brown1b9ba572012-05-21 10:54:18 -0700127 static final boolean DEBUG = false;
Jeff Brownb6997262010-10-08 22:31:17 -0700128
Jeff Brown4532e612012-04-05 14:27:12 -0700129 private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
130
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700131 private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700132 private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
133 private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
134 private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
135 private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
Michael Wright39e5e942015-08-19 22:52:47 +0100136 private static final int MSG_DELIVER_TABLET_MODE_CHANGED = 6;
Yohei Yukawab097b822015-12-01 10:43:08 -0800137 private static final int MSG_INPUT_METHOD_SUBTYPE_CHANGED = 7;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700138
Jeff Brown4532e612012-04-05 14:27:12 -0700139 // Pointer to native input manager service object.
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000140 private final long mPtr;
Jeff Brown4532e612012-04-05 14:27:12 -0700141
Jeff Brown46b9ac02010-04-22 18:58:52 -0700142 private final Context mContext;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700143 private final InputManagerHandler mHandler;
Jeff Browna9d131c2012-09-20 16:48:17 -0700144
Adrian Roos99182342016-06-15 15:30:46 -0700145 private final File mDoubleTouchGestureEnableFile;
146
Jeff Browna9d131c2012-09-20 16:48:17 -0700147 private WindowManagerCallbacks mWindowManagerCallbacks;
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700148 private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
Jeff Brown6ec6f792012-04-17 16:52:41 -0700149 private boolean mSystemReady;
Jeff Browncf39bdf2012-05-18 14:41:19 -0700150 private NotificationManager mNotificationManager;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700151
Michael Wright39e5e942015-08-19 22:52:47 +0100152 private final Object mTabletModeLock = new Object();
153 // List of currently registered tablet mode changed listeners by process id
154 private final SparseArray<TabletModeChangedListenerRecord> mTabletModeChangedListeners =
155 new SparseArray<>(); // guarded by mTabletModeLock
156 private final List<TabletModeChangedListenerRecord> mTempTabletModeChangedListenersToNotify =
157 new ArrayList<>();
158
Jeff Browna3bc5652012-04-17 11:42:25 -0700159 // Persistent data store. Must be locked each time during use.
160 private final PersistentDataStore mDataStore = new PersistentDataStore();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700161
162 // List of currently registered input devices changed listeners by process id.
163 private Object mInputDevicesLock = new Object();
164 private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
165 private InputDevice[] mInputDevices = new InputDevice[0];
166 private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
167 new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
168 private final ArrayList<InputDevicesChangedListenerRecord>
169 mTempInputDevicesChangedListenersToNotify =
170 new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
Jeff Browncf39bdf2012-05-18 14:41:19 -0700171 private final ArrayList<InputDevice>
172 mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
173 private boolean mKeyboardLayoutNotificationShown;
Michael Wrightd5f7ed92016-01-19 11:23:51 -0800174 private InputMethodSubtypeHandle mCurrentImeHandle;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700175
Jeff Browna47425a2012-04-13 04:09:27 -0700176 // State for vibrator tokens.
177 private Object mVibratorLock = new Object();
178 private HashMap<IBinder, VibratorToken> mVibratorTokens =
179 new HashMap<IBinder, VibratorToken>();
180 private int mNextVibratorTokenValue;
181
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700182 // State for the currently installed input filter.
183 final Object mInputFilterLock = new Object();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700184 IInputFilter mInputFilter; // guarded by mInputFilterLock
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700185 InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
Jeff Brown1a84fd12011-06-02 01:26:32 -0700186
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000187 private static native long nativeInit(InputManagerService service,
Jeff Brown4532e612012-04-05 14:27:12 -0700188 Context context, MessageQueue messageQueue);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000189 private static native void nativeStart(long ptr);
190 private static native void nativeSetDisplayViewport(long ptr, boolean external,
Jeff Brownd728bf52012-09-08 18:05:28 -0700191 int displayId, int rotation,
192 int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
Jeff Brown83d616a2012-09-09 20:33:43 -0700193 int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
194 int deviceWidth, int deviceHeight);
Jeff Brownd728bf52012-09-08 18:05:28 -0700195
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000196 private static native int nativeGetScanCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700197 int deviceId, int sourceMask, int scanCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000198 private static native int nativeGetKeyCodeState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700199 int deviceId, int sourceMask, int keyCode);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000200 private static native int nativeGetSwitchState(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700201 int deviceId, int sourceMask, int sw);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000202 private static native boolean nativeHasKeys(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700203 int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000204 private static native void nativeRegisterInputChannel(long ptr, InputChannel inputChannel,
Jeff Brown928e0542011-01-10 11:17:36 -0800205 InputWindowHandle inputWindowHandle, boolean monitor);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000206 private static native void nativeUnregisterInputChannel(long ptr, InputChannel inputChannel);
207 private static native void nativeSetInputFilterEnabled(long ptr, boolean enable);
Jeff Brownca9bc702014-02-11 14:32:56 -0800208 private static native int nativeInjectInputEvent(long ptr, InputEvent event, int displayId,
Jeff Brown0029c662011-03-30 02:25:18 -0700209 int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
210 int policyFlags);
Andrii Kulian112d0562016-03-08 10:44:22 -0800211 private static native void nativeToggleCapsLock(long ptr, int deviceId);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000212 private static native void nativeSetInputWindows(long ptr, InputWindowHandle[] windowHandles);
213 private static native void nativeSetInputDispatchMode(long ptr, boolean enabled, boolean frozen);
214 private static native void nativeSetSystemUiVisibility(long ptr, int visibility);
215 private static native void nativeSetFocusedApplication(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700216 InputApplicationHandle application);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000217 private static native boolean nativeTransferTouchFocus(long ptr,
Jeff Brown4532e612012-04-05 14:27:12 -0700218 InputChannel fromChannel, InputChannel toChannel);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000219 private static native void nativeSetPointerSpeed(long ptr, int speed);
220 private static native void nativeSetShowTouches(long ptr, boolean enabled);
Jeff Brown037c33e2014-04-09 00:31:55 -0700221 private static native void nativeSetInteractive(long ptr, boolean interactive);
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800222 private static native void nativeReloadCalibration(long ptr);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000223 private static native void nativeVibrate(long ptr, int deviceId, long[] pattern,
Jeff Browna47425a2012-04-13 04:09:27 -0700224 int repeat, int token);
Ashok Bhat7e2a9dc2014-01-02 19:43:30 +0000225 private static native void nativeCancelVibrate(long ptr, int deviceId, int token);
226 private static native void nativeReloadKeyboardLayouts(long ptr);
227 private static native void nativeReloadDeviceAliases(long ptr);
228 private static native String nativeDump(long ptr);
229 private static native void nativeMonitor(long ptr);
Michael Wrightf9d9ce772016-05-13 17:44:16 +0100230 private static native void nativeSetPointerIconType(long ptr, int iconId);
Jun Mukai19a56012015-11-24 11:25:52 -0800231 private static native void nativeReloadPointerIcons(long ptr);
Jun Mukaid4eaef72015-10-30 15:54:33 -0700232 private static native void nativeSetCustomPointerIcon(long ptr, PointerIcon icon);
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
Matthew Xie96313142012-06-29 16:57:31 -0700353 // TODO(BT) Pass in paramter 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
Jeff Brown4ccb8232014-01-16 22:16:42 -0800404 private void setDisplayViewportsInternal(DisplayViewport defaultViewport,
Jeff Brownd728bf52012-09-08 18:05:28 -0700405 DisplayViewport externalTouchViewport) {
406 if (defaultViewport.valid) {
407 setDisplayViewport(false, defaultViewport);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700408 }
Jeff Brownd728bf52012-09-08 18:05:28 -0700409
410 if (externalTouchViewport.valid) {
411 setDisplayViewport(true, externalTouchViewport);
412 } else if (defaultViewport.valid) {
413 setDisplayViewport(true, defaultViewport);
Jeff Brownb6997262010-10-08 22:31:17 -0700414 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700415 }
Jeff Brown4ed8fe72012-08-30 18:18:29 -0700416
Jeff Brownd728bf52012-09-08 18:05:28 -0700417 private void setDisplayViewport(boolean external, DisplayViewport viewport) {
418 nativeSetDisplayViewport(mPtr, external,
419 viewport.displayId, viewport.orientation,
420 viewport.logicalFrame.left, viewport.logicalFrame.top,
421 viewport.logicalFrame.right, viewport.logicalFrame.bottom,
422 viewport.physicalFrame.left, viewport.physicalFrame.top,
Jeff Brown83d616a2012-09-09 20:33:43 -0700423 viewport.physicalFrame.right, viewport.physicalFrame.bottom,
424 viewport.deviceWidth, viewport.deviceHeight);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700425 }
Jeff Brownac143512012-04-05 18:57:33 -0700426
Jeff Brown6d0fec22010-07-23 21:28:06 -0700427 /**
428 * Gets the current state of a key or button by key code.
429 * @param deviceId The input device id, or -1 to consult all devices.
430 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
431 * consider all input sources. An input device is consulted if at least one of its
432 * non-class input source bits matches the specified source mask.
433 * @param keyCode The key code to check.
434 * @return The key state.
435 */
436 public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700437 return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700438 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700439
Jeff Brown6d0fec22010-07-23 21:28:06 -0700440 /**
441 * Gets the current state of a key or button by scan code.
442 * @param deviceId The input device id, or -1 to consult all devices.
443 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
444 * consider all input sources. An input device is consulted if at least one of its
445 * non-class input source bits matches the specified source mask.
446 * @param scanCode The scan code to check.
447 * @return The key state.
448 */
449 public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700450 return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700451 }
RoboErikfb290df2013-12-16 11:27:55 -0800452
Jeff Brown6d0fec22010-07-23 21:28:06 -0700453 /**
454 * Gets the current state of a switch by switch code.
455 * @param deviceId The input device id, or -1 to consult all devices.
456 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
457 * consider all input sources. An input device is consulted if at least one of its
458 * non-class input source bits matches the specified source mask.
459 * @param switchCode The switch code to check.
460 * @return The switch state.
461 */
462 public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
Jeff Brown4532e612012-04-05 14:27:12 -0700463 return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700464 }
465
Jeff Brown6d0fec22010-07-23 21:28:06 -0700466 /**
467 * Determines whether the specified key codes are supported by a particular device.
468 * @param deviceId The input device id, or -1 to consult all devices.
469 * @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
470 * consider all input sources. An input device is consulted if at least one of its
471 * non-class input source bits matches the specified source mask.
472 * @param keyCodes The array of key codes to check.
473 * @param keyExists An array at least as large as keyCodes whose entries will be set
474 * to true or false based on the presence or absence of support for the corresponding
475 * key codes.
476 * @return True if the lookup was successful, false otherwise.
477 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700478 @Override // Binder call
Jeff Brown6d0fec22010-07-23 21:28:06 -0700479 public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700480 if (keyCodes == null) {
481 throw new IllegalArgumentException("keyCodes must not be null.");
482 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700483 if (keyExists == null || keyExists.length < keyCodes.length) {
484 throw new IllegalArgumentException("keyExists must not be null and must be at "
485 + "least as large as keyCodes.");
Jeff Brown46b9ac02010-04-22 18:58:52 -0700486 }
RoboErikfb290df2013-12-16 11:27:55 -0800487
Jeff Brown4532e612012-04-05 14:27:12 -0700488 return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700489 }
RoboErikfb290df2013-12-16 11:27:55 -0800490
Jeff Browna41ca772010-08-11 14:46:32 -0700491 /**
492 * Creates an input channel that will receive all input from the input dispatcher.
493 * @param inputChannelName The input channel name.
494 * @return The input channel.
495 */
496 public InputChannel monitorInput(String inputChannelName) {
497 if (inputChannelName == null) {
498 throw new IllegalArgumentException("inputChannelName must not be null.");
499 }
RoboErikfb290df2013-12-16 11:27:55 -0800500
Jeff Browna41ca772010-08-11 14:46:32 -0700501 InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
Jeff Brown4532e612012-04-05 14:27:12 -0700502 nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
Jeff Browna41ca772010-08-11 14:46:32 -0700503 inputChannels[0].dispose(); // don't need to retain the Java object reference
504 return inputChannels[1];
505 }
506
507 /**
508 * Registers an input channel so that it can be used as an input event target.
509 * @param inputChannel The input channel to register.
Jeff Brown928e0542011-01-10 11:17:36 -0800510 * @param inputWindowHandle The handle of the input window associated with the
511 * input channel, or null if none.
Jeff Browna41ca772010-08-11 14:46:32 -0700512 */
Jeff Brown928e0542011-01-10 11:17:36 -0800513 public void registerInputChannel(InputChannel inputChannel,
514 InputWindowHandle inputWindowHandle) {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700515 if (inputChannel == null) {
516 throw new IllegalArgumentException("inputChannel must not be null.");
517 }
RoboErikfb290df2013-12-16 11:27:55 -0800518
Jeff Brown4532e612012-04-05 14:27:12 -0700519 nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700520 }
RoboErikfb290df2013-12-16 11:27:55 -0800521
Jeff Browna41ca772010-08-11 14:46:32 -0700522 /**
523 * Unregisters an input channel.
524 * @param inputChannel The input channel to unregister.
525 */
Jeff Brown46b9ac02010-04-22 18:58:52 -0700526 public void unregisterInputChannel(InputChannel inputChannel) {
527 if (inputChannel == null) {
528 throw new IllegalArgumentException("inputChannel must not be null.");
529 }
RoboErikfb290df2013-12-16 11:27:55 -0800530
Jeff Brown4532e612012-04-05 14:27:12 -0700531 nativeUnregisterInputChannel(mPtr, inputChannel);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700532 }
Jeff Brown0029c662011-03-30 02:25:18 -0700533
534 /**
535 * Sets an input filter that will receive all input events before they are dispatched.
536 * The input filter may then reinterpret input events or inject new ones.
537 *
538 * To ensure consistency, the input dispatcher automatically drops all events
539 * in progress whenever an input filter is installed or uninstalled. After an input
540 * filter is uninstalled, it can no longer send input events unless it is reinstalled.
541 * Any events it attempts to send after it has been uninstalled will be dropped.
542 *
543 * @param filter The input filter, or null to remove the current filter.
544 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700545 public void setInputFilter(IInputFilter filter) {
Jeff Brown0029c662011-03-30 02:25:18 -0700546 synchronized (mInputFilterLock) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700547 final IInputFilter oldFilter = mInputFilter;
Jeff Brown0029c662011-03-30 02:25:18 -0700548 if (oldFilter == filter) {
549 return; // nothing to do
550 }
551
552 if (oldFilter != null) {
553 mInputFilter = null;
554 mInputFilterHost.disconnectLocked();
555 mInputFilterHost = null;
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700556 try {
557 oldFilter.uninstall();
558 } catch (RemoteException re) {
559 /* ignore */
560 }
Jeff Brown0029c662011-03-30 02:25:18 -0700561 }
562
563 if (filter != null) {
564 mInputFilter = filter;
565 mInputFilterHost = new InputFilterHost();
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -0700566 try {
567 filter.install(mInputFilterHost);
568 } catch (RemoteException re) {
569 /* ignore */
570 }
Jeff Brown0029c662011-03-30 02:25:18 -0700571 }
572
Jeff Brown4532e612012-04-05 14:27:12 -0700573 nativeSetInputFilterEnabled(mPtr, filter != null);
Jeff Brown0029c662011-03-30 02:25:18 -0700574 }
575 }
576
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700577 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -0700578 public boolean injectInputEvent(InputEvent event, int mode) {
Jeff Brownca9bc702014-02-11 14:32:56 -0800579 return injectInputEventInternal(event, Display.DEFAULT_DISPLAY, mode);
580 }
581
582 private boolean injectInputEventInternal(InputEvent event, int displayId, int mode) {
Jeff Brown7fbdc842010-06-17 20:52:56 -0700583 if (event == null) {
584 throw new IllegalArgumentException("event must not be null");
585 }
Jeff Brownac143512012-04-05 18:57:33 -0700586 if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
587 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
588 && mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
589 throw new IllegalArgumentException("mode is invalid");
Jeff Brown7fbdc842010-06-17 20:52:56 -0700590 }
Jeff Brown6ec402b2010-07-28 15:48:59 -0700591
Jeff Brownac143512012-04-05 18:57:33 -0700592 final int pid = Binder.getCallingPid();
593 final int uid = Binder.getCallingUid();
594 final long ident = Binder.clearCallingIdentity();
595 final int result;
596 try {
Jeff Brownca9bc702014-02-11 14:32:56 -0800597 result = nativeInjectInputEvent(mPtr, event, displayId, pid, uid, mode,
Jeff Brownac143512012-04-05 18:57:33 -0700598 INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
599 } finally {
600 Binder.restoreCallingIdentity(ident);
601 }
602 switch (result) {
603 case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
604 Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
605 throw new SecurityException(
606 "Injecting to another application requires INJECT_EVENTS permission");
607 case INPUT_EVENT_INJECTION_SUCCEEDED:
608 return true;
609 case INPUT_EVENT_INJECTION_TIMED_OUT:
610 Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
611 return false;
612 case INPUT_EVENT_INJECTION_FAILED:
613 default:
614 Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
615 return false;
616 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700617 }
Jeff Brown0029c662011-03-30 02:25:18 -0700618
Jeff Brown8d608662010-08-30 03:02:23 -0700619 /**
620 * Gets information about the input device with the specified id.
Craig Mautner2f39e9f2012-09-21 11:39:54 -0700621 * @param deviceId The device id.
Jeff Brown8d608662010-08-30 03:02:23 -0700622 * @return The input device or null if not found.
623 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700624 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700625 public InputDevice getInputDevice(int deviceId) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700626 synchronized (mInputDevicesLock) {
627 final int count = mInputDevices.length;
628 for (int i = 0; i < count; i++) {
629 final InputDevice inputDevice = mInputDevices[i];
630 if (inputDevice.getId() == deviceId) {
631 return inputDevice;
632 }
633 }
634 }
635 return null;
Jeff Brown8d608662010-08-30 03:02:23 -0700636 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700637
Jeff Brown8d608662010-08-30 03:02:23 -0700638 /**
639 * Gets the ids of all input devices in the system.
640 * @return The input device ids.
641 */
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700642 @Override // Binder call
Jeff Brown8d608662010-08-30 03:02:23 -0700643 public int[] getInputDeviceIds() {
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700644 synchronized (mInputDevicesLock) {
645 final int count = mInputDevices.length;
646 int[] ids = new int[count];
647 for (int i = 0; i < count; i++) {
648 ids[i] = mInputDevices[i].getId();
649 }
650 return ids;
651 }
652 }
653
Jeff Browndaa37532012-05-01 15:54:03 -0700654 /**
655 * Gets all input devices in the system.
656 * @return The array of input devices.
657 */
658 public InputDevice[] getInputDevices() {
659 synchronized (mInputDevicesLock) {
660 return mInputDevices;
661 }
662 }
663
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700664 @Override // Binder call
665 public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
666 if (listener == null) {
667 throw new IllegalArgumentException("listener must not be null");
668 }
669
670 synchronized (mInputDevicesLock) {
671 int callingPid = Binder.getCallingPid();
672 if (mInputDevicesChangedListeners.get(callingPid) != null) {
673 throw new SecurityException("The calling process has already "
674 + "registered an InputDevicesChangedListener.");
675 }
676
677 InputDevicesChangedListenerRecord record =
678 new InputDevicesChangedListenerRecord(callingPid, listener);
679 try {
680 IBinder binder = listener.asBinder();
681 binder.linkToDeath(record, 0);
682 } catch (RemoteException ex) {
683 // give up
684 throw new RuntimeException(ex);
685 }
686
687 mInputDevicesChangedListeners.put(callingPid, record);
688 }
689 }
690
691 private void onInputDevicesChangedListenerDied(int pid) {
692 synchronized (mInputDevicesLock) {
693 mInputDevicesChangedListeners.remove(pid);
694 }
695 }
696
697 // Must be called on handler.
Jeff Browncf39bdf2012-05-18 14:41:19 -0700698 private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
699 // Scan for changes.
700 int numFullKeyboardsAdded = 0;
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700701 mTempInputDevicesChangedListenersToNotify.clear();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700702 mTempFullKeyboards.clear();
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700703 final int numListeners;
704 final int[] deviceIdAndGeneration;
705 synchronized (mInputDevicesLock) {
706 if (!mInputDevicesChangedPending) {
707 return;
708 }
709 mInputDevicesChangedPending = false;
710
711 numListeners = mInputDevicesChangedListeners.size();
712 for (int i = 0; i < numListeners; i++) {
713 mTempInputDevicesChangedListenersToNotify.add(
714 mInputDevicesChangedListeners.valueAt(i));
715 }
716
717 final int numDevices = mInputDevices.length;
718 deviceIdAndGeneration = new int[numDevices * 2];
719 for (int i = 0; i < numDevices; i++) {
720 final InputDevice inputDevice = mInputDevices[i];
721 deviceIdAndGeneration[i * 2] = inputDevice.getId();
722 deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
Jeff Browncf39bdf2012-05-18 14:41:19 -0700723
Jeff Brown7e4ff4b2012-05-30 14:32:16 -0700724 if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700725 if (!containsInputDeviceWithDescriptor(oldInputDevices,
726 inputDevice.getDescriptor())) {
727 mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
728 } else {
729 mTempFullKeyboards.add(inputDevice);
730 }
731 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700732 }
733 }
734
Jeff Browncf39bdf2012-05-18 14:41:19 -0700735 // Notify listeners.
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700736 for (int i = 0; i < numListeners; i++) {
737 mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
738 deviceIdAndGeneration);
739 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700740 mTempInputDevicesChangedListenersToNotify.clear();
741
742 // Check for missing keyboard layouts.
Michael Wright07483422015-10-30 16:20:13 +0000743 List<InputDevice> keyboardsMissingLayout = new ArrayList<>();
744 final int numFullKeyboards = mTempFullKeyboards.size();
745 synchronized (mDataStore) {
746 for (int i = 0; i < numFullKeyboards; i++) {
747 final InputDevice inputDevice = mTempFullKeyboards.get(i);
748 String layout =
749 getCurrentKeyboardLayoutForInputDevice(inputDevice.getIdentifier());
750 if (layout == null) {
751 layout = getDefaultKeyboardLayout(inputDevice);
752 if (layout != null) {
753 setCurrentKeyboardLayoutForInputDevice(
754 inputDevice.getIdentifier(), layout);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700755 }
756 }
Michael Wright07483422015-10-30 16:20:13 +0000757 if (layout == null) {
758 keyboardsMissingLayout.add(inputDevice);
759 }
Jeff Browncf39bdf2012-05-18 14:41:19 -0700760 }
Michael Wright07483422015-10-30 16:20:13 +0000761 }
762
763 if (mNotificationManager != null) {
764 if (!keyboardsMissingLayout.isEmpty()) {
765 if (keyboardsMissingLayout.size() > 1) {
766 // We have more than one keyboard missing a layout, so drop the
767 // user at the generic input methods page so they can pick which
768 // one to set.
769 showMissingKeyboardLayoutNotification(null);
770 } else {
771 showMissingKeyboardLayoutNotification(keyboardsMissingLayout.get(0));
Jeff Browncf39bdf2012-05-18 14:41:19 -0700772 }
773 } else if (mKeyboardLayoutNotificationShown) {
774 hideMissingKeyboardLayoutNotification();
775 }
776 }
777 mTempFullKeyboards.clear();
778 }
779
Michael Wright07483422015-10-30 16:20:13 +0000780 private String getDefaultKeyboardLayout(final InputDevice d) {
781 final Locale systemLocale = mContext.getResources().getConfiguration().locale;
782 // If our locale doesn't have a language for some reason, then we don't really have a
783 // reasonable default.
784 if (TextUtils.isEmpty(systemLocale.getLanguage())) {
785 return null;
786 }
787 final List<KeyboardLayout> layouts = new ArrayList<>();
788 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
789 @Override
790 public void visitKeyboardLayout(Resources resources,
791 int keyboardLayoutResId, KeyboardLayout layout) {
792 // Only select a default when we know the layout is appropriate. For now, this
793 // means its a custom layout for a specific keyboard.
794 if (layout.getVendorId() != d.getVendorId()
795 || layout.getProductId() != d.getProductId()) {
796 return;
797 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800798 final LocaleList locales = layout.getLocales();
799 final int numLocales = locales.size();
800 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
801 if (isCompatibleLocale(systemLocale, locales.get(localeIndex))) {
Michael Wright07483422015-10-30 16:20:13 +0000802 layouts.add(layout);
803 break;
804 }
805 }
806 }
807 });
808
809 if (layouts.isEmpty()) {
810 return null;
811 }
812
813 // First sort so that ones with higher priority are listed at the top
814 Collections.sort(layouts);
815 // Next we want to try to find an exact match of language, country and variant.
816 final int N = layouts.size();
817 for (int i = 0; i < N; i++) {
818 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800819 final LocaleList locales = layout.getLocales();
820 final int numLocales = locales.size();
821 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
822 final Locale locale = locales.get(localeIndex);
823 if (locale.getCountry().equals(systemLocale.getCountry())
824 && locale.getVariant().equals(systemLocale.getVariant())) {
Michael Wright07483422015-10-30 16:20:13 +0000825 return layout.getDescriptor();
826 }
827 }
828 }
829 // Then try an exact match of language and country
830 for (int i = 0; i < N; i++) {
831 KeyboardLayout layout = layouts.get(i);
Yohei Yukawa5660fad2016-01-27 22:04:09 -0800832 final LocaleList locales = layout.getLocales();
833 final int numLocales = locales.size();
834 for (int localeIndex = 0; localeIndex < numLocales; ++localeIndex) {
835 final Locale locale = locales.get(localeIndex);
836 if (locale.getCountry().equals(systemLocale.getCountry())) {
Michael Wright07483422015-10-30 16:20:13 +0000837 return layout.getDescriptor();
838 }
839 }
840 }
841
842 // Give up and just use the highest priority layout with matching language
843 return layouts.get(0).getDescriptor();
844 }
845
846 private static boolean isCompatibleLocale(Locale systemLocale, Locale keyboardLocale) {
847 // Different languages are never compatible
848 if (!systemLocale.getLanguage().equals(keyboardLocale.getLanguage())) {
849 return false;
850 }
851 // If both the system and the keyboard layout have a country specifier, they must be equal.
852 if (!TextUtils.isEmpty(systemLocale.getCountry())
853 && !TextUtils.isEmpty(keyboardLocale.getCountry())
854 && !systemLocale.getCountry().equals(keyboardLocale.getCountry())) {
855 return false;
856 }
857 return true;
858 }
859
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800860 @Override // Binder call & native callback
Jason Gerecked5220742014-03-10 09:47:59 -0700861 public TouchCalibration getTouchCalibrationForInputDevice(String inputDeviceDescriptor,
862 int surfaceRotation) {
Jason Gerecked6396d62014-01-27 18:30:37 -0800863 if (inputDeviceDescriptor == null) {
864 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
865 }
866
867 synchronized (mDataStore) {
Jason Gerecked5220742014-03-10 09:47:59 -0700868 return mDataStore.getTouchCalibration(inputDeviceDescriptor, surfaceRotation);
Jason Gerecked6396d62014-01-27 18:30:37 -0800869 }
870 }
871
872 @Override // Binder call
Jason Gerecked5220742014-03-10 09:47:59 -0700873 public void setTouchCalibrationForInputDevice(String inputDeviceDescriptor, int surfaceRotation,
Jason Gerecked6396d62014-01-27 18:30:37 -0800874 TouchCalibration calibration) {
875 if (!checkCallingPermission(android.Manifest.permission.SET_INPUT_CALIBRATION,
876 "setTouchCalibrationForInputDevice()")) {
877 throw new SecurityException("Requires SET_INPUT_CALIBRATION permission");
878 }
879 if (inputDeviceDescriptor == null) {
880 throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
881 }
882 if (calibration == null) {
883 throw new IllegalArgumentException("calibration must not be null");
884 }
Jason Gerecked5220742014-03-10 09:47:59 -0700885 if (surfaceRotation < Surface.ROTATION_0 || surfaceRotation > Surface.ROTATION_270) {
886 throw new IllegalArgumentException("surfaceRotation value out of bounds");
887 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800888
889 synchronized (mDataStore) {
890 try {
Jason Gerecked5220742014-03-10 09:47:59 -0700891 if (mDataStore.setTouchCalibration(inputDeviceDescriptor, surfaceRotation,
892 calibration)) {
Jason Gerecke857aa7b2014-01-27 18:34:20 -0800893 nativeReloadCalibration(mPtr);
894 }
Jason Gerecked6396d62014-01-27 18:30:37 -0800895 } finally {
896 mDataStore.saveIfNeeded();
897 }
898 }
899 }
900
Michael Wright39e5e942015-08-19 22:52:47 +0100901 @Override // Binder call
Michael Wright9209c9c2015-09-03 17:57:01 +0100902 public int isInTabletMode() {
903 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
904 "isInTabletMode()")) {
905 throw new SecurityException("Requires TABLET_MODE permission");
906 }
907 return getSwitchState(-1, InputDevice.SOURCE_ANY, SW_TABLET_MODE);
908 }
909
910 @Override // Binder call
Michael Wright39e5e942015-08-19 22:52:47 +0100911 public void registerTabletModeChangedListener(ITabletModeChangedListener listener) {
Michael Wright9209c9c2015-09-03 17:57:01 +0100912 if (!checkCallingPermission(android.Manifest.permission.TABLET_MODE,
Michael Wright39e5e942015-08-19 22:52:47 +0100913 "registerTabletModeChangedListener()")) {
914 throw new SecurityException("Requires TABLET_MODE_LISTENER permission");
915 }
916 if (listener == null) {
917 throw new IllegalArgumentException("listener must not be null");
918 }
919
920 synchronized (mTabletModeLock) {
921 final int callingPid = Binder.getCallingPid();
922 if (mTabletModeChangedListeners.get(callingPid) != null) {
923 throw new IllegalStateException("The calling process has already registered "
924 + "a TabletModeChangedListener.");
925 }
926 TabletModeChangedListenerRecord record =
927 new TabletModeChangedListenerRecord(callingPid, listener);
928 try {
929 IBinder binder = listener.asBinder();
930 binder.linkToDeath(record, 0);
931 } catch (RemoteException ex) {
932 throw new RuntimeException(ex);
933 }
934 mTabletModeChangedListeners.put(callingPid, record);
935 }
936 }
937
938 private void onTabletModeChangedListenerDied(int pid) {
939 synchronized (mTabletModeLock) {
940 mTabletModeChangedListeners.remove(pid);
941 }
942 }
943
944 // Must be called on handler
945 private void deliverTabletModeChanged(long whenNanos, boolean inTabletMode) {
946 mTempTabletModeChangedListenersToNotify.clear();
947 final int numListeners;
948 synchronized (mTabletModeLock) {
949 numListeners = mTabletModeChangedListeners.size();
950 for (int i = 0; i < numListeners; i++) {
951 mTempTabletModeChangedListenersToNotify.add(
952 mTabletModeChangedListeners.valueAt(i));
953 }
954 }
955 for (int i = 0; i < numListeners; i++) {
956 mTempTabletModeChangedListenersToNotify.get(i).notifyTabletModeChanged(
957 whenNanos, inTabletMode);
958 }
959 }
960
Jeff Browncf39bdf2012-05-18 14:41:19 -0700961 // Must be called on handler.
Michael Wrightc93fbd12014-09-22 20:07:59 -0700962 private void showMissingKeyboardLayoutNotification(InputDevice device) {
Jeff Browncf39bdf2012-05-18 14:41:19 -0700963 if (!mKeyboardLayoutNotificationShown) {
Yohei Yukawa2bff4902016-03-30 01:06:37 -0700964 final Intent intent = new Intent(Settings.ACTION_HARD_KEYBOARD_SETTINGS);
Michael Wrightc93fbd12014-09-22 20:07:59 -0700965 if (device != null) {
966 intent.putExtra(Settings.EXTRA_INPUT_DEVICE_IDENTIFIER, device.getIdentifier());
Jeff Browncf39bdf2012-05-18 14:41:19 -0700967 }
Michael Wrightc93fbd12014-09-22 20:07:59 -0700968 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
969 | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
970 | Intent.FLAG_ACTIVITY_CLEAR_TOP);
971 final PendingIntent keyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
972 intent, 0, null, UserHandle.CURRENT);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700973
974 Resources r = mContext.getResources();
975 Notification notification = new Notification.Builder(mContext)
976 .setContentTitle(r.getString(
977 R.string.select_keyboard_layout_notification_title))
978 .setContentText(r.getString(
979 R.string.select_keyboard_layout_notification_message))
Michael Wrightc93fbd12014-09-22 20:07:59 -0700980 .setContentIntent(keyboardLayoutIntent)
Jeff Browncf39bdf2012-05-18 14:41:19 -0700981 .setSmallIcon(R.drawable.ic_settings_language)
982 .setPriority(Notification.PRIORITY_LOW)
Alan Viverette4a357cd2015-03-18 18:37:18 -0700983 .setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200984 com.android.internal.R.color.system_notification_accent_color))
Jeff Browncf39bdf2012-05-18 14:41:19 -0700985 .build();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700986 mNotificationManager.notifyAsUser(null,
987 R.string.select_keyboard_layout_notification_title,
988 notification, UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -0700989 mKeyboardLayoutNotificationShown = true;
990 }
991 }
992
993 // Must be called on handler.
994 private void hideMissingKeyboardLayoutNotification() {
995 if (mKeyboardLayoutNotificationShown) {
996 mKeyboardLayoutNotificationShown = false;
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -0700997 mNotificationManager.cancelAsUser(null,
998 R.string.select_keyboard_layout_notification_title,
999 UserHandle.ALL);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001000 }
1001 }
1002
1003 // Must be called on handler.
1004 private void updateKeyboardLayouts() {
1005 // Scan all input devices state for keyboard layouts that have been uninstalled.
1006 final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
1007 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1008 @Override
Michael Wright07483422015-10-30 16:20:13 +00001009 public void visitKeyboardLayout(Resources resources,
1010 int keyboardLayoutResId, KeyboardLayout layout) {
1011 availableKeyboardLayouts.add(layout.getDescriptor());
Jeff Browncf39bdf2012-05-18 14:41:19 -07001012 }
1013 });
1014 synchronized (mDataStore) {
1015 try {
1016 mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
1017 } finally {
1018 mDataStore.saveIfNeeded();
1019 }
1020 }
1021
1022 // Reload keyboard layouts.
1023 reloadKeyboardLayouts();
1024 }
1025
Jeff Browncf39bdf2012-05-18 14:41:19 -07001026 private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
1027 String descriptor) {
1028 final int numDevices = inputDevices.length;
1029 for (int i = 0; i < numDevices; i++) {
1030 final InputDevice inputDevice = inputDevices[i];
1031 if (inputDevice.getDescriptor().equals(descriptor)) {
1032 return true;
1033 }
1034 }
1035 return false;
Jeff Brown8d608662010-08-30 03:02:23 -07001036 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001037
1038 @Override // Binder call
1039 public KeyboardLayout[] getKeyboardLayouts() {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001040 final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
1041 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1042 @Override
Michael Wright07483422015-10-30 16:20:13 +00001043 public void visitKeyboardLayout(Resources resources,
1044 int keyboardLayoutResId, KeyboardLayout layout) {
1045 list.add(layout);
1046 }
1047 });
1048 return list.toArray(new KeyboardLayout[list.size()]);
1049 }
1050
Michael Wrightb0e804a2016-01-04 16:48:53 -05001051 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001052 public KeyboardLayout[] getKeyboardLayoutsForInputDevice(
1053 final InputDeviceIdentifier identifier) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001054 final String[] enabledLayoutDescriptors =
1055 getEnabledKeyboardLayoutsForInputDevice(identifier);
1056 final ArrayList<KeyboardLayout> enabledLayouts =
1057 new ArrayList<KeyboardLayout>(enabledLayoutDescriptors.length);
1058 final ArrayList<KeyboardLayout> potentialLayouts = new ArrayList<KeyboardLayout>();
Michael Wright07483422015-10-30 16:20:13 +00001059 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1060 boolean mHasSeenDeviceSpecificLayout;
1061
1062 @Override
1063 public void visitKeyboardLayout(Resources resources,
1064 int keyboardLayoutResId, KeyboardLayout layout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001065 // First check if it's enabled. If the keyboard layout is enabled then we always
1066 // want to return it as a possible layout for the device.
1067 for (String s : enabledLayoutDescriptors) {
1068 if (s != null && s.equals(layout.getDescriptor())) {
1069 enabledLayouts.add(layout);
1070 return;
1071 }
1072 }
1073 // Next find any potential layouts that aren't yet enabled for the device. For
1074 // devices that have special layouts we assume there's a reason that the generic
1075 // layouts don't work for them so we don't want to return them since it's likely
1076 // to result in a poor user experience.
Michael Wright07483422015-10-30 16:20:13 +00001077 if (layout.getVendorId() == identifier.getVendorId()
1078 && layout.getProductId() == identifier.getProductId()) {
1079 if (!mHasSeenDeviceSpecificLayout) {
1080 mHasSeenDeviceSpecificLayout = true;
Michael Wrightb0e804a2016-01-04 16:48:53 -05001081 potentialLayouts.clear();
Michael Wright07483422015-10-30 16:20:13 +00001082 }
Michael Wrightb0e804a2016-01-04 16:48:53 -05001083 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001084 } else if (layout.getVendorId() == -1 && layout.getProductId() == -1
1085 && !mHasSeenDeviceSpecificLayout) {
Michael Wrightb0e804a2016-01-04 16:48:53 -05001086 potentialLayouts.add(layout);
Michael Wright07483422015-10-30 16:20:13 +00001087 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001088 }
1089 });
Michael Wrightb0e804a2016-01-04 16:48:53 -05001090 final int enabledLayoutSize = enabledLayouts.size();
1091 final int potentialLayoutSize = potentialLayouts.size();
1092 KeyboardLayout[] layouts = new KeyboardLayout[enabledLayoutSize + potentialLayoutSize];
1093 enabledLayouts.toArray(layouts);
1094 for (int i = 0; i < potentialLayoutSize; i++) {
1095 layouts[enabledLayoutSize + i] = potentialLayouts.get(i);
1096 }
1097 return layouts;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001098 }
1099
1100 @Override // Binder call
1101 public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
1102 if (keyboardLayoutDescriptor == null) {
1103 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1104 }
1105
Jeff Brown6ec6f792012-04-17 16:52:41 -07001106 final KeyboardLayout[] result = new KeyboardLayout[1];
1107 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1108 @Override
Michael Wright07483422015-10-30 16:20:13 +00001109 public void visitKeyboardLayout(Resources resources,
1110 int keyboardLayoutResId, KeyboardLayout layout) {
1111 result[0] = layout;
Jeff Brown6ec6f792012-04-17 16:52:41 -07001112 }
1113 });
1114 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00001115 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07001116 + keyboardLayoutDescriptor + "'.");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001117 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001118 return result[0];
1119 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001120
Jeff Brown6ec6f792012-04-17 16:52:41 -07001121 private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001122 final PackageManager pm = mContext.getPackageManager();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001123 Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
1124 for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001125 PackageManager.GET_META_DATA | PackageManager.MATCH_DIRECT_BOOT_AWARE
1126 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE)) {
Michael Wright8ebac232014-09-18 18:29:49 -07001127 final ActivityInfo activityInfo = resolveInfo.activityInfo;
1128 final int priority = resolveInfo.priority;
1129 visitKeyboardLayoutsInPackage(pm, activityInfo, null, priority, visitor);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001130 }
1131 }
1132
Jeff Brown6ec6f792012-04-17 16:52:41 -07001133 private void visitKeyboardLayout(String keyboardLayoutDescriptor,
1134 KeyboardLayoutVisitor visitor) {
1135 KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
1136 if (d != null) {
1137 final PackageManager pm = mContext.getPackageManager();
1138 try {
1139 ActivityInfo receiver = pm.getReceiverInfo(
1140 new ComponentName(d.packageName, d.receiverName),
Jeff Sharkey5217cac2015-12-20 15:34:01 -07001141 PackageManager.GET_META_DATA
Jeff Sharkey8a372a02016-03-16 16:25:45 -06001142 | PackageManager.MATCH_DIRECT_BOOT_AWARE
1143 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Michael Wright8ebac232014-09-18 18:29:49 -07001144 visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, 0, visitor);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001145 } catch (NameNotFoundException ex) {
1146 }
1147 }
1148 }
1149
1150 private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
Michael Wright8ebac232014-09-18 18:29:49 -07001151 String keyboardName, int requestedPriority, KeyboardLayoutVisitor visitor) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001152 Bundle metaData = receiver.metaData;
1153 if (metaData == null) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001154 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001155 }
1156
1157 int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
1158 if (configResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001159 Slog.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001160 + "' on receiver " + receiver.packageName + "/" + receiver.name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001161 return;
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001162 }
1163
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001164 CharSequence receiverLabel = receiver.loadLabel(pm);
1165 String collection = receiverLabel != null ? receiverLabel.toString() : "";
Michael Wright8ebac232014-09-18 18:29:49 -07001166 int priority;
1167 if ((receiver.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
1168 priority = requestedPriority;
1169 } else {
1170 priority = 0;
1171 }
Jeff Brownd9fec5d2012-05-17 16:01:54 -07001172
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001173 try {
1174 Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
1175 XmlResourceParser parser = resources.getXml(configResId);
1176 try {
1177 XmlUtils.beginDocument(parser, "keyboard-layouts");
1178
1179 for (;;) {
1180 XmlUtils.nextElement(parser);
1181 String element = parser.getName();
1182 if (element == null) {
1183 break;
1184 }
1185 if (element.equals("keyboard-layout")) {
1186 TypedArray a = resources.obtainAttributes(
1187 parser, com.android.internal.R.styleable.KeyboardLayout);
1188 try {
1189 String name = a.getString(
1190 com.android.internal.R.styleable.KeyboardLayout_name);
1191 String label = a.getString(
1192 com.android.internal.R.styleable.KeyboardLayout_label);
Jeff Brown2f095762012-05-10 21:29:33 -07001193 int keyboardLayoutResId = a.getResourceId(
1194 com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
1195 0);
Michael Wright07483422015-10-30 16:20:13 +00001196 String languageTags = a.getString(
1197 com.android.internal.R.styleable.KeyboardLayout_locale);
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001198 LocaleList locales = getLocalesFromLanguageTags(languageTags);
Michael Wright07483422015-10-30 16:20:13 +00001199 int vid = a.getInt(
1200 com.android.internal.R.styleable.KeyboardLayout_vendorId, -1);
1201 int pid = a.getInt(
1202 com.android.internal.R.styleable.KeyboardLayout_productId, -1);
1203
Jeff Brown2f095762012-05-10 21:29:33 -07001204 if (name == null || label == null || keyboardLayoutResId == 0) {
Michael Wright07483422015-10-30 16:20:13 +00001205 Slog.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001206 + "attributes in keyboard layout "
1207 + "resource from receiver "
1208 + receiver.packageName + "/" + receiver.name);
1209 } else {
1210 String descriptor = KeyboardLayoutDescriptor.format(
1211 receiver.packageName, receiver.name, name);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001212 if (keyboardName == null || name.equals(keyboardName)) {
Michael Wright07483422015-10-30 16:20:13 +00001213 KeyboardLayout layout = new KeyboardLayout(
1214 descriptor, label, collection, priority,
1215 locales, vid, pid);
1216 visitor.visitKeyboardLayout(
1217 resources, keyboardLayoutResId, layout);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001218 }
1219 }
1220 } finally {
1221 a.recycle();
1222 }
1223 } else {
Michael Wright07483422015-10-30 16:20:13 +00001224 Slog.w(TAG, "Skipping unrecognized element '" + element
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001225 + "' in keyboard layout resource from receiver "
1226 + receiver.packageName + "/" + receiver.name);
1227 }
1228 }
1229 } finally {
1230 parser.close();
1231 }
1232 } catch (Exception ex) {
Michael Wright07483422015-10-30 16:20:13 +00001233 Slog.w(TAG, "Could not parse keyboard layout resource from receiver "
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001234 + receiver.packageName + "/" + receiver.name, ex);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001235 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001236 }
1237
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001238 @NonNull
1239 private static LocaleList getLocalesFromLanguageTags(String languageTags) {
Michael Wright07483422015-10-30 16:20:13 +00001240 if (TextUtils.isEmpty(languageTags)) {
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001241 return LocaleList.getEmptyLocaleList();
Michael Wright07483422015-10-30 16:20:13 +00001242 }
Yohei Yukawa5660fad2016-01-27 22:04:09 -08001243 return LocaleList.forLanguageTags(languageTags.replace('|', ','));
Michael Wright07483422015-10-30 16:20:13 +00001244 }
1245
RoboErikfb290df2013-12-16 11:27:55 -08001246 /**
1247 * Builds a layout descriptor for the vendor/product. This returns the
1248 * descriptor for ids that aren't useful (such as the default 0, 0).
1249 */
1250 private String getLayoutDescriptor(InputDeviceIdentifier identifier) {
1251 if (identifier == null || identifier.getDescriptor() == null) {
1252 throw new IllegalArgumentException("identifier and descriptor must not be null");
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001253 }
1254
RoboErikfb290df2013-12-16 11:27:55 -08001255 if (identifier.getVendorId() == 0 && identifier.getProductId() == 0) {
1256 return identifier.getDescriptor();
1257 }
1258 StringBuilder bob = new StringBuilder();
1259 bob.append("vendor:").append(identifier.getVendorId());
1260 bob.append(",product:").append(identifier.getProductId());
1261 return bob.toString();
1262 }
1263
1264 @Override // Binder call
1265 public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
1266
1267 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001268 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001269 String layout = null;
1270 // try loading it using the layout descriptor if we have it
1271 layout = mDataStore.getCurrentKeyboardLayout(key);
1272 if (layout == null && !key.equals(identifier.getDescriptor())) {
1273 // if it doesn't exist fall back to the device descriptor
1274 layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1275 }
1276 if (DEBUG) {
1277 Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
1278 + layout);
1279 }
1280 return layout;
Jeff Browna3bc5652012-04-17 11:42:25 -07001281 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001282 }
1283
1284 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001285 public void setCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001286 String keyboardLayoutDescriptor) {
1287 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001288 "setCurrentKeyboardLayoutForInputDevice()")) {
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001289 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1290 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001291 if (keyboardLayoutDescriptor == null) {
1292 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1293 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001294
RoboErikfb290df2013-12-16 11:27:55 -08001295 String key = getLayoutDescriptor(identifier);
Jeff Browna3bc5652012-04-17 11:42:25 -07001296 synchronized (mDataStore) {
1297 try {
RoboErikfb290df2013-12-16 11:27:55 -08001298 if (mDataStore.setCurrentKeyboardLayout(key, keyboardLayoutDescriptor)) {
1299 if (DEBUG) {
1300 Slog.d(TAG, "Saved keyboard layout using " + key);
1301 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001302 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1303 }
Jeff Browna3bc5652012-04-17 11:42:25 -07001304 } finally {
1305 mDataStore.saveIfNeeded();
1306 }
1307 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001308 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001309
Jeff Browncf39bdf2012-05-18 14:41:19 -07001310 @Override // Binder call
Michael Wright07483422015-10-30 16:20:13 +00001311 public String[] getEnabledKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier) {
RoboErikfb290df2013-12-16 11:27:55 -08001312 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001313 synchronized (mDataStore) {
RoboErikfb290df2013-12-16 11:27:55 -08001314 String[] layouts = mDataStore.getKeyboardLayouts(key);
1315 if ((layouts == null || layouts.length == 0)
1316 && !key.equals(identifier.getDescriptor())) {
1317 layouts = mDataStore.getKeyboardLayouts(identifier.getDescriptor());
1318 }
1319 return layouts;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001320 }
1321 }
1322
1323 @Override // Binder call
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001324 @Nullable
1325 public KeyboardLayout getKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1326 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype) {
1327 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1328 String key = getLayoutDescriptor(identifier);
1329 final String keyboardLayoutDescriptor;
1330 synchronized (mDataStore) {
1331 keyboardLayoutDescriptor = mDataStore.getKeyboardLayout(key, handle);
1332 }
1333
1334 if (keyboardLayoutDescriptor == null) {
1335 return null;
1336 }
1337
1338 final KeyboardLayout[] result = new KeyboardLayout[1];
1339 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1340 @Override
1341 public void visitKeyboardLayout(Resources resources,
1342 int keyboardLayoutResId, KeyboardLayout layout) {
1343 result[0] = layout;
1344 }
1345 });
1346 if (result[0] == null) {
1347 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
1348 + keyboardLayoutDescriptor + "'.");
1349 }
1350 return result[0];
1351 }
1352
1353 @Override
1354 public void setKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
1355 InputMethodInfo imeInfo, InputMethodSubtype imeSubtype,
1356 String keyboardLayoutDescriptor) {
1357 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1358 "setKeyboardLayoutForInputDevice()")) {
1359 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1360 }
1361 if (keyboardLayoutDescriptor == null) {
1362 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1363 }
Yohei Yukawa46ac35d2016-04-20 16:59:45 -07001364 if (imeInfo == null) {
1365 throw new IllegalArgumentException("imeInfo must not be null");
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001366 }
1367 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(imeInfo, imeSubtype);
1368 setKeyboardLayoutForInputDeviceInner(identifier, handle, keyboardLayoutDescriptor);
1369 }
1370
1371 private void setKeyboardLayoutForInputDeviceInner(InputDeviceIdentifier identifier,
1372 InputMethodSubtypeHandle imeHandle, String keyboardLayoutDescriptor) {
1373 String key = getLayoutDescriptor(identifier);
1374 synchronized (mDataStore) {
1375 try {
1376 if (mDataStore.setKeyboardLayout(key, imeHandle, keyboardLayoutDescriptor)) {
1377 if (DEBUG) {
1378 Slog.d(TAG, "Set keyboard layout " + keyboardLayoutDescriptor +
1379 " for subtype " + imeHandle + " and device " + identifier +
1380 " using key " + key);
1381 }
1382 if (imeHandle.equals(mCurrentImeHandle)) {
1383 if (DEBUG) {
1384 Slog.d(TAG, "Layout for current subtype changed, switching layout");
1385 }
1386 SomeArgs args = SomeArgs.obtain();
1387 args.arg1 = identifier;
1388 args.arg2 = imeHandle;
1389 mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, args).sendToTarget();
1390 }
1391 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1392 }
1393 } finally {
1394 mDataStore.saveIfNeeded();
1395 }
1396 }
1397 }
1398
1399 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001400 public void addKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001401 String keyboardLayoutDescriptor) {
1402 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1403 "addKeyboardLayoutForInputDevice()")) {
1404 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1405 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001406 if (keyboardLayoutDescriptor == null) {
1407 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1408 }
1409
RoboErikfb290df2013-12-16 11:27:55 -08001410 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001411 synchronized (mDataStore) {
1412 try {
RoboErikfb290df2013-12-16 11:27:55 -08001413 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1414 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1415 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1416 }
1417 if (mDataStore.addKeyboardLayout(key, keyboardLayoutDescriptor)
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001418 && !Objects.equal(oldLayout, mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001419 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1420 }
1421 } finally {
1422 mDataStore.saveIfNeeded();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001423 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001424 }
1425 }
1426
1427 @Override // Binder call
RoboErikfb290df2013-12-16 11:27:55 -08001428 public void removeKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier,
Jeff Browncf39bdf2012-05-18 14:41:19 -07001429 String keyboardLayoutDescriptor) {
1430 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1431 "removeKeyboardLayoutForInputDevice()")) {
1432 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1433 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001434 if (keyboardLayoutDescriptor == null) {
1435 throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
1436 }
1437
RoboErikfb290df2013-12-16 11:27:55 -08001438 String key = getLayoutDescriptor(identifier);
Jeff Browncf39bdf2012-05-18 14:41:19 -07001439 synchronized (mDataStore) {
1440 try {
RoboErikfb290df2013-12-16 11:27:55 -08001441 String oldLayout = mDataStore.getCurrentKeyboardLayout(key);
1442 if (oldLayout == null && !key.equals(identifier.getDescriptor())) {
1443 oldLayout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
1444 }
1445 boolean removed = mDataStore.removeKeyboardLayout(key, keyboardLayoutDescriptor);
1446 if (!key.equals(identifier.getDescriptor())) {
1447 // We need to remove from both places to ensure it is gone
1448 removed |= mDataStore.removeKeyboardLayout(identifier.getDescriptor(),
1449 keyboardLayoutDescriptor);
1450 }
1451 if (removed && !Objects.equal(oldLayout,
1452 mDataStore.getCurrentKeyboardLayout(key))) {
Jeff Browncf39bdf2012-05-18 14:41:19 -07001453 mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
1454 }
1455 } finally {
1456 mDataStore.saveIfNeeded();
1457 }
1458 }
1459 }
1460
Yohei Yukawab097b822015-12-01 10:43:08 -08001461 // Must be called on handler.
1462 private void handleSwitchInputMethodSubtype(int userId,
1463 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
1464 if (DEBUG) {
1465 Slog.i(TAG, "InputMethodSubtype changed: userId=" + userId
1466 + " ime=" + inputMethodInfo + " subtype=" + subtype);
1467 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001468 if (inputMethodInfo == null) {
1469 Slog.d(TAG, "No InputMethod is running, ignoring change");
1470 return;
1471 }
1472 if (subtype != null && !"keyboard".equals(subtype.getMode())) {
1473 Slog.d(TAG, "InputMethodSubtype changed to non-keyboard subtype, ignoring change");
1474 return;
1475 }
1476 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(inputMethodInfo, subtype);
1477 if (!handle.equals(mCurrentImeHandle)) {
1478 mCurrentImeHandle = handle;
1479 handleSwitchKeyboardLayout(null, handle);
1480 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001481 }
1482
1483 // Must be called on handler.
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001484 private void handleSwitchKeyboardLayout(@Nullable InputDeviceIdentifier identifier,
1485 InputMethodSubtypeHandle handle) {
1486 synchronized (mInputDevicesLock) {
1487 for (InputDevice device : mInputDevices) {
1488 if (identifier != null && !device.getIdentifier().equals(identifier) ||
1489 !device.isFullKeyboard()) {
1490 continue;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001491 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001492 String key = getLayoutDescriptor(device.getIdentifier());
1493 boolean changed = false;
1494 synchronized (mDataStore) {
1495 try {
1496 if (mDataStore.switchKeyboardLayout(key, handle)) {
1497 changed = true;
1498 }
1499 } finally {
1500 mDataStore.saveIfNeeded();
Jeff Browncf39bdf2012-05-18 14:41:19 -07001501 }
1502 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001503 if (changed) {
1504 reloadKeyboardLayouts();
1505 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001506 }
Jeff Brown6ec6f792012-04-17 16:52:41 -07001507 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001508 }
1509
Jeff Brown9302c872011-07-13 22:51:29 -07001510 public void setInputWindows(InputWindowHandle[] windowHandles) {
Jeff Brown4532e612012-04-05 14:27:12 -07001511 nativeSetInputWindows(mPtr, windowHandles);
Jeff Brown349703e2010-06-22 01:27:15 -07001512 }
RoboErikfb290df2013-12-16 11:27:55 -08001513
Jeff Brown9302c872011-07-13 22:51:29 -07001514 public void setFocusedApplication(InputApplicationHandle application) {
Jeff Brown4532e612012-04-05 14:27:12 -07001515 nativeSetFocusedApplication(mPtr, application);
Jeff Brown349703e2010-06-22 01:27:15 -07001516 }
RoboErikfb290df2013-12-16 11:27:55 -08001517
Jeff Brown349703e2010-06-22 01:27:15 -07001518 public void setInputDispatchMode(boolean enabled, boolean frozen) {
Jeff Brown4532e612012-04-05 14:27:12 -07001519 nativeSetInputDispatchMode(mPtr, enabled, frozen);
Jeff Brown349703e2010-06-22 01:27:15 -07001520 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001521
1522 public void setSystemUiVisibility(int visibility) {
Jeff Brown4532e612012-04-05 14:27:12 -07001523 nativeSetSystemUiVisibility(mPtr, visibility);
Jeff Brown05dc66a2011-03-02 14:41:58 -08001524 }
1525
Jeff Browne6504122010-09-27 14:52:15 -07001526 /**
1527 * Atomically transfers touch focus from one window to another as identified by
1528 * their input channels. It is possible for multiple windows to have
1529 * touch focus if they support split touch dispatch
1530 * {@link android.view.WindowManager.LayoutParams#FLAG_SPLIT_TOUCH} but this
1531 * method only transfers touch focus of the specified window without affecting
1532 * other windows that may also have touch focus at the same time.
1533 * @param fromChannel The channel of a window that currently has touch focus.
1534 * @param toChannel The channel of the window that should receive touch focus in
1535 * place of the first.
1536 * @return True if the transfer was successful. False if the window with the
1537 * specified channel did not actually have touch focus at the time of the request.
1538 */
1539 public boolean transferTouchFocus(InputChannel fromChannel, InputChannel toChannel) {
1540 if (fromChannel == null) {
1541 throw new IllegalArgumentException("fromChannel must not be null.");
1542 }
1543 if (toChannel == null) {
1544 throw new IllegalArgumentException("toChannel must not be null.");
1545 }
Jeff Brown4532e612012-04-05 14:27:12 -07001546 return nativeTransferTouchFocus(mPtr, fromChannel, toChannel);
Jeff Browne6504122010-09-27 14:52:15 -07001547 }
Jeff Brown05dc66a2011-03-02 14:41:58 -08001548
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001549 @Override // Binder call
Jeff Brownac143512012-04-05 18:57:33 -07001550 public void tryPointerSpeed(int speed) {
1551 if (!checkCallingPermission(android.Manifest.permission.SET_POINTER_SPEED,
1552 "tryPointerSpeed()")) {
1553 throw new SecurityException("Requires SET_POINTER_SPEED permission");
1554 }
1555
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001556 if (speed < InputManager.MIN_POINTER_SPEED || speed > InputManager.MAX_POINTER_SPEED) {
1557 throw new IllegalArgumentException("speed out of range");
1558 }
1559
Jeff Brownac143512012-04-05 18:57:33 -07001560 setPointerSpeedUnchecked(speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001561 }
1562
1563 public void updatePointerSpeedFromSettings() {
Jeff Brownac143512012-04-05 18:57:33 -07001564 int speed = getPointerSpeedSetting();
1565 setPointerSpeedUnchecked(speed);
1566 }
1567
1568 private void setPointerSpeedUnchecked(int speed) {
1569 speed = Math.min(Math.max(speed, InputManager.MIN_POINTER_SPEED),
1570 InputManager.MAX_POINTER_SPEED);
1571 nativeSetPointerSpeed(mPtr, speed);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001572 }
1573
1574 private void registerPointerSpeedSettingObserver() {
1575 mContext.getContentResolver().registerContentObserver(
1576 Settings.System.getUriFor(Settings.System.POINTER_SPEED), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001577 new ContentObserver(mHandler) {
Jeff Brown1a84fd12011-06-02 01:26:32 -07001578 @Override
1579 public void onChange(boolean selfChange) {
1580 updatePointerSpeedFromSettings();
1581 }
Jeff Brownd4935962012-09-25 13:27:20 -07001582 }, UserHandle.USER_ALL);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001583 }
1584
Jeff Brownac143512012-04-05 18:57:33 -07001585 private int getPointerSpeedSetting() {
1586 int speed = InputManager.DEFAULT_POINTER_SPEED;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001587 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001588 speed = Settings.System.getIntForUser(mContext.getContentResolver(),
1589 Settings.System.POINTER_SPEED, UserHandle.USER_CURRENT);
Jeff Brown1a84fd12011-06-02 01:26:32 -07001590 } catch (SettingNotFoundException snfe) {
1591 }
1592 return speed;
1593 }
1594
Jeff Browndaf4a122011-08-26 17:14:14 -07001595 public void updateShowTouchesFromSettings() {
1596 int setting = getShowTouchesSetting(0);
Jeff Brown4532e612012-04-05 14:27:12 -07001597 nativeSetShowTouches(mPtr, setting != 0);
Jeff Browndaf4a122011-08-26 17:14:14 -07001598 }
1599
1600 private void registerShowTouchesSettingObserver() {
1601 mContext.getContentResolver().registerContentObserver(
1602 Settings.System.getUriFor(Settings.System.SHOW_TOUCHES), true,
Jeff Brown4532e612012-04-05 14:27:12 -07001603 new ContentObserver(mHandler) {
Jeff Browndaf4a122011-08-26 17:14:14 -07001604 @Override
1605 public void onChange(boolean selfChange) {
1606 updateShowTouchesFromSettings();
1607 }
Jeff Brownd4935962012-09-25 13:27:20 -07001608 }, UserHandle.USER_ALL);
Jeff Browndaf4a122011-08-26 17:14:14 -07001609 }
1610
Jun Mukaie4e75da2015-12-15 16:19:20 -08001611 public void updateAccessibilityLargePointerFromSettings() {
1612 final int accessibilityConfig = Settings.Secure.getIntForUser(
1613 mContext.getContentResolver(), Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON,
1614 0, UserHandle.USER_CURRENT);
Jun Mukai1f3dbff2015-12-16 14:41:25 -08001615 PointerIcon.setUseLargeIcons(accessibilityConfig == 1);
Jun Mukaie4e75da2015-12-15 16:19:20 -08001616 nativeReloadPointerIcons(mPtr);
1617 }
1618
Jun Mukai19a56012015-11-24 11:25:52 -08001619 private void registerAccessibilityLargePointerSettingObserver() {
1620 mContext.getContentResolver().registerContentObserver(
1621 Settings.Secure.getUriFor(Settings.Secure.ACCESSIBILITY_LARGE_POINTER_ICON), true,
1622 new ContentObserver(mHandler) {
1623 @Override
1624 public void onChange(boolean selfChange) {
Jun Mukaie4e75da2015-12-15 16:19:20 -08001625 updateAccessibilityLargePointerFromSettings();
Jun Mukai19a56012015-11-24 11:25:52 -08001626 }
1627 }, UserHandle.USER_ALL);
1628 }
1629
Jeff Browndaf4a122011-08-26 17:14:14 -07001630 private int getShowTouchesSetting(int defaultValue) {
1631 int result = defaultValue;
1632 try {
Jeff Brownd4935962012-09-25 13:27:20 -07001633 result = Settings.System.getIntForUser(mContext.getContentResolver(),
1634 Settings.System.SHOW_TOUCHES, UserHandle.USER_CURRENT);
Jeff Browndaf4a122011-08-26 17:14:14 -07001635 } catch (SettingNotFoundException snfe) {
1636 }
1637 return result;
1638 }
1639
Jeff Browna47425a2012-04-13 04:09:27 -07001640 // Binder call
1641 @Override
1642 public void vibrate(int deviceId, long[] pattern, int repeat, IBinder token) {
1643 if (repeat >= pattern.length) {
1644 throw new ArrayIndexOutOfBoundsException();
1645 }
1646
1647 VibratorToken v;
1648 synchronized (mVibratorLock) {
1649 v = mVibratorTokens.get(token);
1650 if (v == null) {
1651 v = new VibratorToken(deviceId, token, mNextVibratorTokenValue++);
1652 try {
1653 token.linkToDeath(v, 0);
1654 } catch (RemoteException ex) {
1655 // give up
1656 throw new RuntimeException(ex);
1657 }
1658 mVibratorTokens.put(token, v);
1659 }
1660 }
1661
1662 synchronized (v) {
1663 v.mVibrating = true;
1664 nativeVibrate(mPtr, deviceId, pattern, repeat, v.mTokenValue);
1665 }
1666 }
1667
1668 // Binder call
1669 @Override
1670 public void cancelVibrate(int deviceId, IBinder token) {
1671 VibratorToken v;
1672 synchronized (mVibratorLock) {
1673 v = mVibratorTokens.get(token);
1674 if (v == null || v.mDeviceId != deviceId) {
1675 return; // nothing to cancel
1676 }
1677 }
1678
1679 cancelVibrateIfNeeded(v);
1680 }
1681
1682 void onVibratorTokenDied(VibratorToken v) {
1683 synchronized (mVibratorLock) {
1684 mVibratorTokens.remove(v.mToken);
1685 }
1686
1687 cancelVibrateIfNeeded(v);
1688 }
1689
1690 private void cancelVibrateIfNeeded(VibratorToken v) {
1691 synchronized (v) {
1692 if (v.mVibrating) {
1693 nativeCancelVibrate(mPtr, v.mDeviceId, v.mTokenValue);
1694 v.mVibrating = false;
1695 }
1696 }
1697 }
1698
Jun Mukai19a56012015-11-24 11:25:52 -08001699 // Binder call
1700 @Override
Michael Wrightf9d9ce772016-05-13 17:44:16 +01001701 public void setPointerIconType(int iconId) {
1702 nativeSetPointerIconType(mPtr, iconId);
Jun Mukai19a56012015-11-24 11:25:52 -08001703 }
Jun Mukai1db53972015-09-11 18:08:31 -07001704
Jun Mukaid4eaef72015-10-30 15:54:33 -07001705 // Binder call
1706 @Override
1707 public void setCustomPointerIcon(PointerIcon icon) {
1708 nativeSetCustomPointerIcon(mPtr, icon);
1709 }
1710
Jeff Brown4532e612012-04-05 14:27:12 -07001711 @Override
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001712 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Browna3bc5652012-04-17 11:42:25 -07001713 if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
Jeff Brown4532e612012-04-05 14:27:12 -07001714 != PackageManager.PERMISSION_GRANTED) {
1715 pw.println("Permission Denial: can't dump InputManager from from pid="
1716 + Binder.getCallingPid()
1717 + ", uid=" + Binder.getCallingUid());
1718 return;
1719 }
1720
1721 pw.println("INPUT MANAGER (dumpsys input)\n");
1722 String dumpStr = nativeDump(mPtr);
Jeff Browne33348b2010-07-15 23:54:05 -07001723 if (dumpStr != null) {
1724 pw.println(dumpStr);
1725 }
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001726 pw.println(" Keyboard Layouts:");
1727 visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
1728 @Override
1729 public void visitKeyboardLayout(Resources resources,
1730 int keyboardLayoutResId, KeyboardLayout layout) {
1731 pw.println(" \"" + layout + "\": " + layout.getDescriptor());
1732 }
1733 });
1734 pw.println();
1735 synchronized(mDataStore) {
1736 mDataStore.dump(pw, " ");
1737 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07001738 }
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001739
Michael Wrightd5f7ed92016-01-19 11:23:51 -08001740 @Override
1741 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1742 FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
1743 (new Shell()).exec(this, in, out, err, args, resultReceiver);
1744 }
1745
1746 public int onShellCommand(Shell shell, String cmd) {
1747 if (TextUtils.isEmpty(cmd)) {
1748 shell.onHelp();
1749 return 1;
1750 }
1751 if (cmd.equals("setlayout")) {
1752 if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
1753 "onShellCommand()")) {
1754 throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
1755 }
1756 InputMethodSubtypeHandle handle = new InputMethodSubtypeHandle(
1757 shell.getNextArgRequired(), Integer.parseInt(shell.getNextArgRequired()));
1758 String descriptor = shell.getNextArgRequired();
1759 int vid = Integer.decode(shell.getNextArgRequired());
1760 int pid = Integer.decode(shell.getNextArgRequired());
1761 InputDeviceIdentifier id = new InputDeviceIdentifier(descriptor, vid, pid);
1762 setKeyboardLayoutForInputDeviceInner(id, handle, shell.getNextArgRequired());
1763 }
1764 return 0;
1765 }
1766
1767
Jeff Brownac143512012-04-05 18:57:33 -07001768 private boolean checkCallingPermission(String permission, String func) {
1769 // Quick check: if the calling permission is me, it's all okay.
1770 if (Binder.getCallingPid() == Process.myPid()) {
1771 return true;
1772 }
1773
1774 if (mContext.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
1775 return true;
1776 }
1777 String msg = "Permission Denial: " + func + " from pid="
1778 + Binder.getCallingPid()
1779 + ", uid=" + Binder.getCallingUid()
1780 + " requires " + permission;
1781 Slog.w(TAG, msg);
1782 return false;
1783 }
1784
Jeff Brown4532e612012-04-05 14:27:12 -07001785 // Called by the heartbeat to ensure locks are not held indefinitely (for deadlock detection).
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001786 @Override
Jeff Brown89ef0722011-08-10 16:25:21 -07001787 public void monitor() {
1788 synchronized (mInputFilterLock) { }
Jeff Brown4532e612012-04-05 14:27:12 -07001789 nativeMonitor(mPtr);
Jeff Brown89ef0722011-08-10 16:25:21 -07001790 }
1791
Jeff Brown4532e612012-04-05 14:27:12 -07001792 // Native callback.
1793 private void notifyConfigurationChanged(long whenNanos) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001794 mWindowManagerCallbacks.notifyConfigurationChanged();
Jeff Brown4532e612012-04-05 14:27:12 -07001795 }
1796
1797 // Native callback.
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001798 private void notifyInputDevicesChanged(InputDevice[] inputDevices) {
1799 synchronized (mInputDevicesLock) {
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001800 if (!mInputDevicesChangedPending) {
1801 mInputDevicesChangedPending = true;
Jeff Browncf39bdf2012-05-18 14:41:19 -07001802 mHandler.obtainMessage(MSG_DELIVER_INPUT_DEVICES_CHANGED,
1803 mInputDevices).sendToTarget();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001804 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07001805
1806 mInputDevices = inputDevices;
Jeff Brownaf9e8d32012-04-12 17:32:48 -07001807 }
1808 }
1809
1810 // Native callback.
Jeff Brownbcc046a2012-09-27 20:46:43 -07001811 private void notifySwitch(long whenNanos, int switchValues, int switchMask) {
1812 if (DEBUG) {
1813 Slog.d(TAG, "notifySwitch: values=" + Integer.toHexString(switchValues)
1814 + ", mask=" + Integer.toHexString(switchMask));
1815 }
1816
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001817 if ((switchMask & SW_LID_BIT) != 0) {
1818 final boolean lidOpen = ((switchValues & SW_LID_BIT) == 0);
Jeff Brownbcc046a2012-09-27 20:46:43 -07001819 mWindowManagerCallbacks.notifyLidSwitchChanged(whenNanos, lidOpen);
Jeff Brown53384282012-08-20 20:16:01 -07001820 }
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001821
Michael Wright3818c922014-09-02 13:59:07 -07001822 if ((switchMask & SW_CAMERA_LENS_COVER_BIT) != 0) {
Michael Wright9e10d252014-09-13 19:41:20 -07001823 final boolean lensCovered = ((switchValues & SW_CAMERA_LENS_COVER_BIT) != 0);
Michael Wright3818c922014-09-02 13:59:07 -07001824 mWindowManagerCallbacks.notifyCameraLensCoverSwitchChanged(whenNanos, lensCovered);
1825 }
1826
Craig Mautner2f39e9f2012-09-21 11:39:54 -07001827 if (mUseDevInputEventForAudioJack && (switchMask & SW_JACK_BITS) != 0) {
1828 mWiredAccessoryCallbacks.notifyWiredAccessoryChanged(whenNanos, switchValues,
1829 switchMask);
1830 }
Michael Wright39e5e942015-08-19 22:52:47 +01001831
Michael Wright9209c9c2015-09-03 17:57:01 +01001832 if ((switchMask & SW_TABLET_MODE_BIT) != 0) {
Michael Wright39e5e942015-08-19 22:52:47 +01001833 SomeArgs args = SomeArgs.obtain();
1834 args.argi1 = (int) (whenNanos & 0xFFFFFFFF);
1835 args.argi2 = (int) (whenNanos >> 32);
1836 args.arg1 = Boolean.valueOf((switchValues & SW_TABLET_MODE_BIT) != 0);
1837 mHandler.obtainMessage(MSG_DELIVER_TABLET_MODE_CHANGED,
1838 args).sendToTarget();
1839 }
Jeff Brown4532e612012-04-05 14:27:12 -07001840 }
1841
1842 // Native callback.
1843 private void notifyInputChannelBroken(InputWindowHandle inputWindowHandle) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001844 mWindowManagerCallbacks.notifyInputChannelBroken(inputWindowHandle);
Jeff Brown4532e612012-04-05 14:27:12 -07001845 }
1846
1847 // Native callback.
1848 private long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07001849 InputWindowHandle inputWindowHandle, String reason) {
1850 return mWindowManagerCallbacks.notifyANR(
1851 inputApplicationHandle, inputWindowHandle, reason);
Jeff Brown4532e612012-04-05 14:27:12 -07001852 }
1853
1854 // Native callback.
1855 final boolean filterInputEvent(InputEvent event, int policyFlags) {
1856 synchronized (mInputFilterLock) {
1857 if (mInputFilter != null) {
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07001858 try {
1859 mInputFilter.filterInputEvent(event, policyFlags);
1860 } catch (RemoteException e) {
1861 /* ignore */
1862 }
Jeff Brown4532e612012-04-05 14:27:12 -07001863 return false;
1864 }
1865 }
1866 event.recycle();
1867 return true;
1868 }
1869
1870 // Native callback.
Jeff Brown037c33e2014-04-09 00:31:55 -07001871 private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags) {
1872 return mWindowManagerCallbacks.interceptKeyBeforeQueueing(event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001873 }
1874
1875 // Native callback.
Michael Wright70af00a2014-09-03 19:30:20 -07001876 private int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags) {
1877 return mWindowManagerCallbacks.interceptMotionBeforeQueueingNonInteractive(
Jeff Brown26875502014-01-30 21:47:47 -08001878 whenNanos, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001879 }
1880
1881 // Native callback.
1882 private long interceptKeyBeforeDispatching(InputWindowHandle focus,
1883 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001884 return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001885 }
1886
1887 // Native callback.
1888 private KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
1889 KeyEvent event, int policyFlags) {
Jeff Browna9d131c2012-09-20 16:48:17 -07001890 return mWindowManagerCallbacks.dispatchUnhandledKey(focus, event, policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07001891 }
1892
1893 // Native callback.
1894 private boolean checkInjectEventsPermission(int injectorPid, int injectorUid) {
1895 return mContext.checkPermission(android.Manifest.permission.INJECT_EVENTS,
1896 injectorPid, injectorUid) == PackageManager.PERMISSION_GRANTED;
1897 }
1898
1899 // Native callback.
1900 private int getVirtualKeyQuietTimeMillis() {
1901 return mContext.getResources().getInteger(
1902 com.android.internal.R.integer.config_virtualKeyQuietTimeMillis);
1903 }
1904
1905 // Native callback.
1906 private String[] getExcludedDeviceNames() {
1907 ArrayList<String> names = new ArrayList<String>();
1908
1909 // Read partner-provided list of excluded input devices
1910 XmlPullParser parser = null;
1911 // Environment.getRootDirectory() is a fancy way of saying ANDROID_ROOT or "/system".
1912 File confFile = new File(Environment.getRootDirectory(), EXCLUDED_DEVICES_PATH);
1913 FileReader confreader = null;
1914 try {
1915 confreader = new FileReader(confFile);
1916 parser = Xml.newPullParser();
1917 parser.setInput(confreader);
1918 XmlUtils.beginDocument(parser, "devices");
1919
1920 while (true) {
1921 XmlUtils.nextElement(parser);
1922 if (!"device".equals(parser.getName())) {
1923 break;
1924 }
1925 String name = parser.getAttributeValue(null, "name");
1926 if (name != null) {
1927 names.add(name);
1928 }
1929 }
1930 } catch (FileNotFoundException e) {
1931 // It's ok if the file does not exist.
1932 } catch (Exception e) {
1933 Slog.e(TAG, "Exception while parsing '" + confFile.getAbsolutePath() + "'", e);
1934 } finally {
1935 try { if (confreader != null) confreader.close(); } catch (IOException e) { }
1936 }
1937
1938 return names.toArray(new String[names.size()]);
1939 }
1940
1941 // Native callback.
1942 private int getKeyRepeatTimeout() {
1943 return ViewConfiguration.getKeyRepeatTimeout();
1944 }
1945
1946 // Native callback.
1947 private int getKeyRepeatDelay() {
1948 return ViewConfiguration.getKeyRepeatDelay();
1949 }
1950
1951 // Native callback.
1952 private int getHoverTapTimeout() {
1953 return ViewConfiguration.getHoverTapTimeout();
1954 }
1955
1956 // Native callback.
1957 private int getHoverTapSlop() {
1958 return ViewConfiguration.getHoverTapSlop();
1959 }
1960
1961 // Native callback.
1962 private int getDoubleTapTimeout() {
1963 return ViewConfiguration.getDoubleTapTimeout();
1964 }
1965
1966 // Native callback.
1967 private int getLongPressTimeout() {
1968 return ViewConfiguration.getLongPressTimeout();
1969 }
1970
1971 // Native callback.
1972 private int getPointerLayer() {
Jeff Browna9d131c2012-09-20 16:48:17 -07001973 return mWindowManagerCallbacks.getPointerLayer();
Jeff Brown4532e612012-04-05 14:27:12 -07001974 }
1975
1976 // Native callback.
1977 private PointerIcon getPointerIcon() {
1978 return PointerIcon.getDefaultIcon(mContext);
1979 }
1980
Jeff Brown6ec6f792012-04-17 16:52:41 -07001981 // Native callback.
RoboErikfb290df2013-12-16 11:27:55 -08001982 private String[] getKeyboardLayoutOverlay(InputDeviceIdentifier identifier) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001983 if (!mSystemReady) {
1984 return null;
1985 }
1986
RoboErikfb290df2013-12-16 11:27:55 -08001987 String keyboardLayoutDescriptor = getCurrentKeyboardLayoutForInputDevice(identifier);
Jeff Brown6ec6f792012-04-17 16:52:41 -07001988 if (keyboardLayoutDescriptor == null) {
1989 return null;
1990 }
1991
1992 final String[] result = new String[2];
1993 visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
1994 @Override
Michael Wright07483422015-10-30 16:20:13 +00001995 public void visitKeyboardLayout(Resources resources,
1996 int keyboardLayoutResId, KeyboardLayout layout) {
Jeff Brown6ec6f792012-04-17 16:52:41 -07001997 try {
Michael Wright07483422015-10-30 16:20:13 +00001998 result[0] = layout.getDescriptor();
Jeff Brown6ec6f792012-04-17 16:52:41 -07001999 result[1] = Streams.readFully(new InputStreamReader(
Jeff Brown2f095762012-05-10 21:29:33 -07002000 resources.openRawResource(keyboardLayoutResId)));
Jeff Brown6ec6f792012-04-17 16:52:41 -07002001 } catch (IOException ex) {
2002 } catch (NotFoundException ex) {
2003 }
2004 }
2005 });
2006 if (result[0] == null) {
Michael Wright07483422015-10-30 16:20:13 +00002007 Slog.w(TAG, "Could not get keyboard layout with descriptor '"
Jeff Brown6ec6f792012-04-17 16:52:41 -07002008 + keyboardLayoutDescriptor + "'.");
2009 return null;
2010 }
2011 return result;
2012 }
2013
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002014 // Native callback.
2015 private String getDeviceAlias(String uniqueId) {
Matthew Xie96313142012-06-29 16:57:31 -07002016 if (BluetoothAdapter.checkBluetoothAddress(uniqueId)) {
2017 // TODO(BT) mBluetoothService.getRemoteAlias(uniqueId)
2018 return null;
Jeff Brown5bbd4b42012-04-20 19:28:00 -07002019 }
2020 return null;
2021 }
2022
Jeff Brown4532e612012-04-05 14:27:12 -07002023 /**
2024 * Callback interface implemented by the Window Manager.
2025 */
Jeff Browna9d131c2012-09-20 16:48:17 -07002026 public interface WindowManagerCallbacks {
Jeff Brown4532e612012-04-05 14:27:12 -07002027 public void notifyConfigurationChanged();
2028
2029 public void notifyLidSwitchChanged(long whenNanos, boolean lidOpen);
2030
Michael Wright3818c922014-09-02 13:59:07 -07002031 public void notifyCameraLensCoverSwitchChanged(long whenNanos, boolean lensCovered);
2032
Jeff Brown4532e612012-04-05 14:27:12 -07002033 public void notifyInputChannelBroken(InputWindowHandle inputWindowHandle);
2034
2035 public long notifyANR(InputApplicationHandle inputApplicationHandle,
Jeff Brownbd181bb2013-09-10 16:44:24 -07002036 InputWindowHandle inputWindowHandle, String reason);
Jeff Brown4532e612012-04-05 14:27:12 -07002037
Jeff Brown037c33e2014-04-09 00:31:55 -07002038 public int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002039
Michael Wright70af00a2014-09-03 19:30:20 -07002040 public int interceptMotionBeforeQueueingNonInteractive(long whenNanos, int policyFlags);
Jeff Brown4532e612012-04-05 14:27:12 -07002041
2042 public long interceptKeyBeforeDispatching(InputWindowHandle focus,
2043 KeyEvent event, int policyFlags);
2044
2045 public KeyEvent dispatchUnhandledKey(InputWindowHandle focus,
2046 KeyEvent event, int policyFlags);
2047
2048 public int getPointerLayer();
2049 }
2050
2051 /**
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002052 * Callback interface implemented by WiredAccessoryObserver.
2053 */
2054 public interface WiredAccessoryCallbacks {
2055 public void notifyWiredAccessoryChanged(long whenNanos, int switchValues, int switchMask);
Eric Laurent4a5eeb92014-05-06 10:49:04 -07002056 public void systemReady();
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002057 }
2058
2059 /**
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002060 * Private handler for the input manager.
2061 */
2062 private final class InputManagerHandler extends Handler {
Jeff Browna9d131c2012-09-20 16:48:17 -07002063 public InputManagerHandler(Looper looper) {
2064 super(looper, null, true /*async*/);
Jeff Browna2910d02012-08-25 12:29:46 -07002065 }
2066
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002067 @Override
2068 public void handleMessage(Message msg) {
2069 switch (msg.what) {
2070 case MSG_DELIVER_INPUT_DEVICES_CHANGED:
Jeff Browncf39bdf2012-05-18 14:41:19 -07002071 deliverInputDevicesChanged((InputDevice[])msg.obj);
2072 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002073 case MSG_SWITCH_KEYBOARD_LAYOUT: {
2074 SomeArgs args = (SomeArgs)msg.obj;
2075 handleSwitchKeyboardLayout((InputDeviceIdentifier)args.arg1,
2076 (InputMethodSubtypeHandle)args.arg2);
Jeff Browncf39bdf2012-05-18 14:41:19 -07002077 break;
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002078 }
Jeff Browncf39bdf2012-05-18 14:41:19 -07002079 case MSG_RELOAD_KEYBOARD_LAYOUTS:
2080 reloadKeyboardLayouts();
2081 break;
2082 case MSG_UPDATE_KEYBOARD_LAYOUTS:
2083 updateKeyboardLayouts();
2084 break;
2085 case MSG_RELOAD_DEVICE_ALIASES:
2086 reloadDeviceAliases();
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002087 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002088 case MSG_DELIVER_TABLET_MODE_CHANGED: {
Michael Wright39e5e942015-08-19 22:52:47 +01002089 SomeArgs args = (SomeArgs) msg.obj;
2090 long whenNanos = (args.argi1 & 0xFFFFFFFFl) | ((long) args.argi2 << 32);
2091 boolean inTabletMode = (boolean) args.arg1;
2092 deliverTabletModeChanged(whenNanos, inTabletMode);
2093 break;
Yohei Yukawab097b822015-12-01 10:43:08 -08002094 }
2095 case MSG_INPUT_METHOD_SUBTYPE_CHANGED: {
2096 final int userId = msg.arg1;
2097 final SomeArgs args = (SomeArgs) msg.obj;
2098 final InputMethodInfo inputMethodInfo = (InputMethodInfo) args.arg1;
2099 final InputMethodSubtype subtype = (InputMethodSubtype) args.arg2;
2100 args.recycle();
2101 handleSwitchInputMethodSubtype(userId, inputMethodInfo, subtype);
2102 break;
2103 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002104 }
2105 }
2106 }
2107
2108 /**
Jeff Brown4532e612012-04-05 14:27:12 -07002109 * Hosting interface for input filters to call back into the input manager.
2110 */
Svetoslav Ganovc9c9a482012-07-16 08:46:07 -07002111 private final class InputFilterHost extends IInputFilterHost.Stub {
Jeff Brown0029c662011-03-30 02:25:18 -07002112 private boolean mDisconnected;
2113
2114 public void disconnectLocked() {
2115 mDisconnected = true;
2116 }
2117
Craig Mautner2f39e9f2012-09-21 11:39:54 -07002118 @Override
Jeff Brown0029c662011-03-30 02:25:18 -07002119 public void sendInputEvent(InputEvent event, int policyFlags) {
2120 if (event == null) {
2121 throw new IllegalArgumentException("event must not be null");
2122 }
2123
2124 synchronized (mInputFilterLock) {
2125 if (!mDisconnected) {
Jeff Brownca9bc702014-02-11 14:32:56 -08002126 nativeInjectInputEvent(mPtr, event, Display.DEFAULT_DISPLAY, 0, 0,
Jeff Brownac143512012-04-05 18:57:33 -07002127 InputManager.INJECT_INPUT_EVENT_MODE_ASYNC, 0,
Jeff Brown0029c662011-03-30 02:25:18 -07002128 policyFlags | WindowManagerPolicy.FLAG_FILTERED);
2129 }
2130 }
2131 }
2132 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -07002133
2134 private static final class KeyboardLayoutDescriptor {
2135 public String packageName;
2136 public String receiverName;
2137 public String keyboardLayoutName;
2138
2139 public static String format(String packageName,
2140 String receiverName, String keyboardName) {
2141 return packageName + "/" + receiverName + "/" + keyboardName;
2142 }
2143
2144 public static KeyboardLayoutDescriptor parse(String descriptor) {
2145 int pos = descriptor.indexOf('/');
2146 if (pos < 0 || pos + 1 == descriptor.length()) {
2147 return null;
2148 }
2149 int pos2 = descriptor.indexOf('/', pos + 1);
2150 if (pos2 < pos + 2 || pos2 + 1 == descriptor.length()) {
2151 return null;
2152 }
2153
2154 KeyboardLayoutDescriptor result = new KeyboardLayoutDescriptor();
2155 result.packageName = descriptor.substring(0, pos);
2156 result.receiverName = descriptor.substring(pos + 1, pos2);
2157 result.keyboardLayoutName = descriptor.substring(pos2 + 1);
2158 return result;
2159 }
2160 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002161
Jeff Brown6ec6f792012-04-17 16:52:41 -07002162 private interface KeyboardLayoutVisitor {
Michael Wright07483422015-10-30 16:20:13 +00002163 void visitKeyboardLayout(Resources resources,
2164 int keyboardLayoutResId, KeyboardLayout layout);
Jeff Brown6ec6f792012-04-17 16:52:41 -07002165 }
2166
Jeff Brownaf9e8d32012-04-12 17:32:48 -07002167 private final class InputDevicesChangedListenerRecord implements DeathRecipient {
2168 private final int mPid;
2169 private final IInputDevicesChangedListener mListener;
2170
2171 public InputDevicesChangedListenerRecord(int pid, IInputDevicesChangedListener listener) {
2172 mPid = pid;
2173 mListener = listener;
2174 }
2175
2176 @Override
2177 public void binderDied() {
2178 if (DEBUG) {
2179 Slog.d(TAG, "Input devices changed listener for pid " + mPid + " died.");
2180 }
2181 onInputDevicesChangedListenerDied(mPid);
2182 }
2183
2184 public void notifyInputDevicesChanged(int[] info) {
2185 try {
2186 mListener.onInputDevicesChanged(info);
2187 } catch (RemoteException ex) {
2188 Slog.w(TAG, "Failed to notify process "
2189 + mPid + " that input devices changed, assuming it died.", ex);
2190 binderDied();
2191 }
2192 }
2193 }
Jeff Browna47425a2012-04-13 04:09:27 -07002194
Michael Wright39e5e942015-08-19 22:52:47 +01002195 private final class TabletModeChangedListenerRecord implements DeathRecipient {
2196 private final int mPid;
2197 private final ITabletModeChangedListener mListener;
2198
2199 public TabletModeChangedListenerRecord(int pid, ITabletModeChangedListener listener) {
2200 mPid = pid;
2201 mListener = listener;
2202 }
2203
2204 @Override
2205 public void binderDied() {
2206 if (DEBUG) {
2207 Slog.d(TAG, "Tablet mode changed listener for pid " + mPid + " died.");
2208 }
2209 onTabletModeChangedListenerDied(mPid);
2210 }
2211
2212 public void notifyTabletModeChanged(long whenNanos, boolean inTabletMode) {
2213 try {
2214 mListener.onTabletModeChanged(whenNanos, inTabletMode);
2215 } catch (RemoteException ex) {
2216 Slog.w(TAG, "Failed to notify process " + mPid +
2217 " that tablet mode changed, assuming it died.", ex);
2218 binderDied();
2219 }
2220 }
2221 }
2222
Jeff Browna47425a2012-04-13 04:09:27 -07002223 private final class VibratorToken implements DeathRecipient {
2224 public final int mDeviceId;
2225 public final IBinder mToken;
2226 public final int mTokenValue;
2227
2228 public boolean mVibrating;
2229
2230 public VibratorToken(int deviceId, IBinder token, int tokenValue) {
2231 mDeviceId = deviceId;
2232 mToken = token;
2233 mTokenValue = tokenValue;
2234 }
2235
2236 @Override
2237 public void binderDied() {
2238 if (DEBUG) {
2239 Slog.d(TAG, "Vibrator token died.");
2240 }
2241 onVibratorTokenDied(this);
2242 }
2243 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002244
Michael Wrightd5f7ed92016-01-19 11:23:51 -08002245 private class Shell extends ShellCommand {
2246 @Override
2247 public int onCommand(String cmd) {
2248 return onShellCommand(this, cmd);
2249 }
2250
2251 @Override
2252 public void onHelp() {
2253 final PrintWriter pw = getOutPrintWriter();
2254 pw.println("Input manager commands:");
2255 pw.println(" help");
2256 pw.println(" Print this help text.");
2257 pw.println("");
2258 pw.println(" setlayout IME_ID IME_SUPTYPE_HASH_CODE"
2259 + " DEVICE_DESCRIPTOR VENDOR_ID PRODUCT_ID KEYBOARD_DESCRIPTOR");
2260 pw.println(" Sets a keyboard layout for a given IME subtype and input device pair");
2261 }
2262 }
2263
Jeff Brown4ccb8232014-01-16 22:16:42 -08002264 private final class LocalService extends InputManagerInternal {
2265 @Override
2266 public void setDisplayViewports(
2267 DisplayViewport defaultViewport, DisplayViewport externalTouchViewport) {
2268 setDisplayViewportsInternal(defaultViewport, externalTouchViewport);
2269 }
Jeff Brownca9bc702014-02-11 14:32:56 -08002270
2271 @Override
2272 public boolean injectInputEvent(InputEvent event, int displayId, int mode) {
2273 return injectInputEventInternal(event, displayId, mode);
2274 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002275
2276 @Override
2277 public void setInteractive(boolean interactive) {
2278 nativeSetInteractive(mPtr, interactive);
2279 }
Yohei Yukawab097b822015-12-01 10:43:08 -08002280
2281 @Override
2282 public void onInputMethodSubtypeChanged(int userId,
2283 @Nullable InputMethodInfo inputMethodInfo, @Nullable InputMethodSubtype subtype) {
2284 final SomeArgs someArgs = SomeArgs.obtain();
2285 someArgs.arg1 = inputMethodInfo;
2286 someArgs.arg2 = subtype;
2287 mHandler.obtainMessage(MSG_INPUT_METHOD_SUBTYPE_CHANGED, userId, 0, someArgs)
2288 .sendToTarget();
2289 }
Andrii Kulian112d0562016-03-08 10:44:22 -08002290
2291 @Override
2292 public void toggleCapsLock(int deviceId) {
2293 nativeToggleCapsLock(mPtr, deviceId);
2294 }
Adrian Roos99182342016-06-15 15:30:46 -07002295
2296 @Override
2297 public void setPulseGestureEnabled(boolean enabled) {
2298 if (mDoubleTouchGestureEnableFile != null) {
2299 FileWriter writer = null;
2300 try {
2301 writer = new FileWriter(mDoubleTouchGestureEnableFile);
2302 writer.write(enabled ? "1" : "0");
2303 } catch (IOException e) {
2304 Log.wtf(TAG, "Unable to setPulseGestureEnabled", e);
2305 } finally {
2306 IoUtils.closeQuietly(writer);
2307 }
2308 }
2309 }
Jeff Brown4ccb8232014-01-16 22:16:42 -08002310 }
Jeff Brown46b9ac02010-04-22 18:58:52 -07002311}