-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInputManagerService.java
More file actions
1638 lines (1438 loc) · 64.1 KB
/
InputManagerService.java
File metadata and controls
1638 lines (1438 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.input;
import com.android.internal.R;
import com.android.internal.util.XmlUtils;
import com.android.server.Watchdog;
import com.android.server.display.DisplayManagerService;
import com.android.server.display.DisplayViewport;
import org.xmlpull.v1.XmlPullParser;
import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.database.ContentObserver;
import android.hardware.input.IInputDevicesChangedListener;
import android.hardware.input.IInputManager;
import android.hardware.input.InputManager;
import android.hardware.input.KeyboardLayout;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.os.Process;
import android.os.RemoteException;
import android.os.UserHandle;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.util.Slog;
import android.util.SparseArray;
import android.util.Xml;
import android.view.IInputFilter;
import android.view.IInputFilterHost;
import android.view.InputChannel;
import android.view.InputDevice;
import android.view.InputEvent;
import android.view.KeyEvent;
import android.view.PointerIcon;
import android.view.ViewConfiguration;
import android.view.WindowManagerPolicy;
import android.widget.Toast;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import libcore.io.Streams;
import libcore.util.Objects;
//和输入相关的一些东西
public class InputManagerService extends IInputManager.Stub
implements Watchdog.Monitor, DisplayManagerService.InputManagerFuncs {
static final String TAG = "InputManager";
static final boolean DEBUG = false;
private static final String EXCLUDED_DEVICES_PATH = "etc/excluded-input-devices.xml";
private static final int MSG_DELIVER_INPUT_DEVICES_CHANGED = 1;
private static final int MSG_SWITCH_KEYBOARD_LAYOUT = 2;
private static final int MSG_RELOAD_KEYBOARD_LAYOUTS = 3;
private static final int MSG_UPDATE_KEYBOARD_LAYOUTS = 4;
private static final int MSG_RELOAD_DEVICE_ALIASES = 5;
// Pointer to native input manager service object.
private final int mPtr;
private final Context mContext;
private final InputManagerHandler mHandler;
private WindowManagerCallbacks mWindowManagerCallbacks;
private WiredAccessoryCallbacks mWiredAccessoryCallbacks;
private boolean mSystemReady;
private NotificationManager mNotificationManager;
// Persistent data store. Must be locked each time during use.
private final PersistentDataStore mDataStore = new PersistentDataStore();
// List of currently registered input devices changed listeners by process id.
private Object mInputDevicesLock = new Object();
private boolean mInputDevicesChangedPending; // guarded by mInputDevicesLock
private InputDevice[] mInputDevices = new InputDevice[0];
private final SparseArray<InputDevicesChangedListenerRecord> mInputDevicesChangedListeners =
new SparseArray<InputDevicesChangedListenerRecord>(); // guarded by mInputDevicesLock
private final ArrayList<InputDevicesChangedListenerRecord>
mTempInputDevicesChangedListenersToNotify =
new ArrayList<InputDevicesChangedListenerRecord>(); // handler thread only
private final ArrayList<InputDevice>
mTempFullKeyboards = new ArrayList<InputDevice>(); // handler thread only
private boolean mKeyboardLayoutNotificationShown;
private PendingIntent mKeyboardLayoutIntent;
private Toast mSwitchedKeyboardLayoutToast;
// State for vibrator tokens.
private Object mVibratorLock = new Object();
private HashMap<IBinder, VibratorToken> mVibratorTokens =
new HashMap<IBinder, VibratorToken>();
private int mNextVibratorTokenValue;
// State for the currently installed input filter.
final Object mInputFilterLock = new Object();
IInputFilter mInputFilter; // guarded by mInputFilterLock
InputFilterHost mInputFilterHost; // guarded by mInputFilterLock
private static native int nativeInit(InputManagerService service,
Context context, MessageQueue messageQueue);
private static native void nativeStart(int ptr);
private static native void nativeSetDisplayViewport(int ptr, boolean external,
int displayId, int rotation,
int logicalLeft, int logicalTop, int logicalRight, int logicalBottom,
int physicalLeft, int physicalTop, int physicalRight, int physicalBottom,
int deviceWidth, int deviceHeight);
private static native int nativeGetScanCodeState(int ptr,
int deviceId, int sourceMask, int scanCode);
private static native int nativeGetKeyCodeState(int ptr,
int deviceId, int sourceMask, int keyCode);
private static native int nativeGetSwitchState(int ptr,
int deviceId, int sourceMask, int sw);
private static native boolean nativeHasKeys(int ptr,
int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists);
private static native void nativeRegisterInputChannel(int ptr, InputChannel inputChannel,
InputWindowHandle inputWindowHandle, boolean monitor);
private static native void nativeUnregisterInputChannel(int ptr, InputChannel inputChannel);
private static native void nativeSetInputFilterEnabled(int ptr, boolean enable);
private static native int nativeInjectInputEvent(int ptr, InputEvent event,
int injectorPid, int injectorUid, int syncMode, int timeoutMillis,
int policyFlags);
private static native void nativeSetInputWindows(int ptr, InputWindowHandle[] windowHandles);
private static native void nativeSetInputDispatchMode(int ptr, boolean enabled, boolean frozen);
private static native void nativeSetSystemUiVisibility(int ptr, int visibility);
private static native void nativeSetFocusedApplication(int ptr,
InputApplicationHandle application);
private static native boolean nativeTransferTouchFocus(int ptr,
InputChannel fromChannel, InputChannel toChannel);
private static native void nativeSetPointerSpeed(int ptr, int speed);
private static native void nativeSetShowTouches(int ptr, boolean enabled);
private static native void nativeVibrate(int ptr, int deviceId, long[] pattern,
int repeat, int token);
private static native void nativeCancelVibrate(int ptr, int deviceId, int token);
private static native void nativeReloadKeyboardLayouts(int ptr);
private static native void nativeReloadDeviceAliases(int ptr);
private static native String nativeDump(int ptr);
private static native void nativeMonitor(int ptr);
// Input event injection constants defined in InputDispatcher.h.
private static final int INPUT_EVENT_INJECTION_SUCCEEDED = 0;
private static final int INPUT_EVENT_INJECTION_PERMISSION_DENIED = 1;
private static final int INPUT_EVENT_INJECTION_FAILED = 2;
private static final int INPUT_EVENT_INJECTION_TIMED_OUT = 3;
// Maximum number of milliseconds to wait for input event injection.
private static final int INJECTION_TIMEOUT_MILLIS = 30 * 1000;
// Key states (may be returned by queries about the current state of a
// particular key code, scan code or switch).
/** The key state is unknown or the requested key itself is not supported. */
public static final int KEY_STATE_UNKNOWN = -1;
/** The key is up. /*/
public static final int KEY_STATE_UP = 0;
/** The key is down. */
public static final int KEY_STATE_DOWN = 1;
/** The key is down but is a virtual key press that is being emulated by the system. */
public static final int KEY_STATE_VIRTUAL = 2;
/** Scan code: Mouse / trackball button. */
public static final int BTN_MOUSE = 0x110;
// Switch code values must match bionic/libc/kernel/common/linux/input.h
/** Switch code: Lid switch. When set, lid is shut. */
public static final int SW_LID = 0x00;
/** Switch code: Keypad slide. When set, keyboard is exposed. */
public static final int SW_KEYPAD_SLIDE = 0x0a;
/** Switch code: Headphone. When set, headphone is inserted. */
public static final int SW_HEADPHONE_INSERT = 0x02;
/** Switch code: Microphone. When set, microphone is inserted. */
public static final int SW_MICROPHONE_INSERT = 0x04;
/** Switch code: Headphone/Microphone Jack. When set, something is inserted. */
public static final int SW_JACK_PHYSICAL_INSERT = 0x07;
public static final int SW_LID_BIT = 1 << SW_LID;
public static final int SW_KEYPAD_SLIDE_BIT = 1 << SW_KEYPAD_SLIDE;
public static final int SW_HEADPHONE_INSERT_BIT = 1 << SW_HEADPHONE_INSERT;
public static final int SW_MICROPHONE_INSERT_BIT = 1 << SW_MICROPHONE_INSERT;
public static final int SW_JACK_PHYSICAL_INSERT_BIT = 1 << SW_JACK_PHYSICAL_INSERT;
public static final int SW_JACK_BITS =
SW_HEADPHONE_INSERT_BIT | SW_MICROPHONE_INSERT_BIT | SW_JACK_PHYSICAL_INSERT_BIT;
/** Whether to use the dev/input/event or uevent subsystem for the audio jack. */
final boolean mUseDevInputEventForAudioJack;
public InputManagerService(Context context, Handler handler) {
this.mContext = context;
this.mHandler = new InputManagerHandler(handler.getLooper());
mUseDevInputEventForAudioJack =
context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);
Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="
+ mUseDevInputEventForAudioJack);
mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());
}
public void setWindowManagerCallbacks(WindowManagerCallbacks callbacks) {
mWindowManagerCallbacks = callbacks;
}
public void setWiredAccessoryCallbacks(WiredAccessoryCallbacks callbacks) {
mWiredAccessoryCallbacks = callbacks;
}
public void start() {
Slog.i(TAG, "Starting input manager");
nativeStart(mPtr);
// Add ourself to the Watchdog monitors.
Watchdog.getInstance().addMonitor(this);
registerPointerSpeedSettingObserver();
registerShowTouchesSettingObserver();
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updatePointerSpeedFromSettings();
updateShowTouchesFromSettings();
}
}, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
updatePointerSpeedFromSettings();
updateShowTouchesFromSettings();
}
// TODO(BT) Pass in paramter for bluetooth system
public void systemReady() {
if (DEBUG) {
Slog.d(TAG, "System ready.");
}
mNotificationManager = (NotificationManager)mContext.getSystemService(
Context.NOTIFICATION_SERVICE);
mSystemReady = true;
IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addDataScheme("package");
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateKeyboardLayouts();
}
}, filter, null, mHandler);
filter = new IntentFilter(BluetoothDevice.ACTION_ALIAS_CHANGED);
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
reloadDeviceAliases();
}
}, filter, null, mHandler);
mHandler.sendEmptyMessage(MSG_RELOAD_DEVICE_ALIASES);
mHandler.sendEmptyMessage(MSG_UPDATE_KEYBOARD_LAYOUTS);
}
private void reloadKeyboardLayouts() {
if (DEBUG) {
Slog.d(TAG, "Reloading keyboard layouts.");
}
nativeReloadKeyboardLayouts(mPtr);
}
private void reloadDeviceAliases() {
if (DEBUG) {
Slog.d(TAG, "Reloading device names.");
}
nativeReloadDeviceAliases(mPtr);
}
@Override
public void setDisplayViewports(DisplayViewport defaultViewport,
DisplayViewport externalTouchViewport) {
if (defaultViewport.valid) {
setDisplayViewport(false, defaultViewport);
}
if (externalTouchViewport.valid) {
setDisplayViewport(true, externalTouchViewport);
} else if (defaultViewport.valid) {
setDisplayViewport(true, defaultViewport);
}
}
private void setDisplayViewport(boolean external, DisplayViewport viewport) {
nativeSetDisplayViewport(mPtr, external,
viewport.displayId, viewport.orientation,
viewport.logicalFrame.left, viewport.logicalFrame.top,
viewport.logicalFrame.right, viewport.logicalFrame.bottom,
viewport.physicalFrame.left, viewport.physicalFrame.top,
viewport.physicalFrame.right, viewport.physicalFrame.bottom,
viewport.deviceWidth, viewport.deviceHeight);
}
/**
* Gets the current state of a key or button by key code.
* @param deviceId The input device id, or -1 to consult all devices.
* @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
* consider all input sources. An input device is consulted if at least one of its
* non-class input source bits matches the specified source mask.
* @param keyCode The key code to check.
* @return The key state.
*/
public int getKeyCodeState(int deviceId, int sourceMask, int keyCode) {
return nativeGetKeyCodeState(mPtr, deviceId, sourceMask, keyCode);
}
/**
* Gets the current state of a key or button by scan code.
* @param deviceId The input device id, or -1 to consult all devices.
* @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
* consider all input sources. An input device is consulted if at least one of its
* non-class input source bits matches the specified source mask.
* @param scanCode The scan code to check.
* @return The key state.
*/
public int getScanCodeState(int deviceId, int sourceMask, int scanCode) {
return nativeGetScanCodeState(mPtr, deviceId, sourceMask, scanCode);
}
/**
* Gets the current state of a switch by switch code.
* @param deviceId The input device id, or -1 to consult all devices.
* @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
* consider all input sources. An input device is consulted if at least one of its
* non-class input source bits matches the specified source mask.
* @param switchCode The switch code to check.
* @return The switch state.
*/
public int getSwitchState(int deviceId, int sourceMask, int switchCode) {
return nativeGetSwitchState(mPtr, deviceId, sourceMask, switchCode);
}
/**
* Determines whether the specified key codes are supported by a particular device.
* @param deviceId The input device id, or -1 to consult all devices.
* @param sourceMask The input sources to consult, or {@link InputDevice#SOURCE_ANY} to
* consider all input sources. An input device is consulted if at least one of its
* non-class input source bits matches the specified source mask.
* @param keyCodes The array of key codes to check.
* @param keyExists An array at least as large as keyCodes whose entries will be set
* to true or false based on the presence or absence of support for the corresponding
* key codes.
* @return True if the lookup was successful, false otherwise.
*/
@Override // Binder call
public boolean hasKeys(int deviceId, int sourceMask, int[] keyCodes, boolean[] keyExists) {
if (keyCodes == null) {
throw new IllegalArgumentException("keyCodes must not be null.");
}
if (keyExists == null || keyExists.length < keyCodes.length) {
throw new IllegalArgumentException("keyExists must not be null and must be at "
+ "least as large as keyCodes.");
}
return nativeHasKeys(mPtr, deviceId, sourceMask, keyCodes, keyExists);
}
/**
* Creates an input channel that will receive all input from the input dispatcher.
* @param inputChannelName The input channel name.
* @return The input channel.
*/
public InputChannel monitorInput(String inputChannelName) {
if (inputChannelName == null) {
throw new IllegalArgumentException("inputChannelName must not be null.");
}
InputChannel[] inputChannels = InputChannel.openInputChannelPair(inputChannelName);
nativeRegisterInputChannel(mPtr, inputChannels[0], null, true);
inputChannels[0].dispose(); // don't need to retain the Java object reference
return inputChannels[1];
}
/**
* Registers an input channel so that it can be used as an input event target.
* @param inputChannel The input channel to register.
* @param inputWindowHandle The handle of the input window associated with the
* input channel, or null if none.
*/
public void registerInputChannel(InputChannel inputChannel,
InputWindowHandle inputWindowHandle) {
if (inputChannel == null) {
throw new IllegalArgumentException("inputChannel must not be null.");
}
nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);
}
/**
* Unregisters an input channel.
* @param inputChannel The input channel to unregister.
*/
public void unregisterInputChannel(InputChannel inputChannel) {
if (inputChannel == null) {
throw new IllegalArgumentException("inputChannel must not be null.");
}
nativeUnregisterInputChannel(mPtr, inputChannel);
}
/**
* Sets an input filter that will receive all input events before they are dispatched.
* The input filter may then reinterpret input events or inject new ones.
*
* To ensure consistency, the input dispatcher automatically drops all events
* in progress whenever an input filter is installed or uninstalled. After an input
* filter is uninstalled, it can no longer send input events unless it is reinstalled.
* Any events it attempts to send after it has been uninstalled will be dropped.
*
* @param filter The input filter, or null to remove the current filter.
*/
public void setInputFilter(IInputFilter filter) {
synchronized (mInputFilterLock) {
final IInputFilter oldFilter = mInputFilter;
if (oldFilter == filter) {
return; // nothing to do
}
if (oldFilter != null) {
mInputFilter = null;
mInputFilterHost.disconnectLocked();
mInputFilterHost = null;
try {
oldFilter.uninstall();
} catch (RemoteException re) {
/* ignore */
}
}
if (filter != null) {
mInputFilter = filter;
mInputFilterHost = new InputFilterHost();
try {
filter.install(mInputFilterHost);
} catch (RemoteException re) {
/* ignore */
}
}
nativeSetInputFilterEnabled(mPtr, filter != null);
}
}
@Override // Binder call
public boolean injectInputEvent(InputEvent event, int mode) {
if (event == null) {
throw new IllegalArgumentException("event must not be null");
}
if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
&& mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
&& mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
throw new IllegalArgumentException("mode is invalid");
}
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
final long ident = Binder.clearCallingIdentity();
final int result;
try {
result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
} finally {
Binder.restoreCallingIdentity(ident);
}
switch (result) {
case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
throw new SecurityException(
"Injecting to another application requires INJECT_EVENTS permission");
case INPUT_EVENT_INJECTION_SUCCEEDED:
return true;
case INPUT_EVENT_INJECTION_TIMED_OUT:
Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
return false;
case INPUT_EVENT_INJECTION_FAILED:
default:
Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
return false;
}
}
/**
* Gets information about the input device with the specified id.
* @param deviceId The device id.
* @return The input device or null if not found.
*/
@Override // Binder call
public InputDevice getInputDevice(int deviceId) {
synchronized (mInputDevicesLock) {
final int count = mInputDevices.length;
for (int i = 0; i < count; i++) {
final InputDevice inputDevice = mInputDevices[i];
if (inputDevice.getId() == deviceId) {
return inputDevice;
}
}
}
return null;
}
/**
* Gets the ids of all input devices in the system.
* @return The input device ids.
*/
@Override // Binder call
public int[] getInputDeviceIds() {
synchronized (mInputDevicesLock) {
final int count = mInputDevices.length;
int[] ids = new int[count];
for (int i = 0; i < count; i++) {
ids[i] = mInputDevices[i].getId();
}
return ids;
}
}
/**
* Gets all input devices in the system.
* @return The array of input devices.
*/
public InputDevice[] getInputDevices() {
synchronized (mInputDevicesLock) {
return mInputDevices;
}
}
@Override // Binder call
public void registerInputDevicesChangedListener(IInputDevicesChangedListener listener) {
if (listener == null) {
throw new IllegalArgumentException("listener must not be null");
}
synchronized (mInputDevicesLock) {
int callingPid = Binder.getCallingPid();
if (mInputDevicesChangedListeners.get(callingPid) != null) {
throw new SecurityException("The calling process has already "
+ "registered an InputDevicesChangedListener.");
}
InputDevicesChangedListenerRecord record =
new InputDevicesChangedListenerRecord(callingPid, listener);
try {
IBinder binder = listener.asBinder();
binder.linkToDeath(record, 0);
} catch (RemoteException ex) {
// give up
throw new RuntimeException(ex);
}
mInputDevicesChangedListeners.put(callingPid, record);
}
}
private void onInputDevicesChangedListenerDied(int pid) {
synchronized (mInputDevicesLock) {
mInputDevicesChangedListeners.remove(pid);
}
}
// Must be called on handler.
private void deliverInputDevicesChanged(InputDevice[] oldInputDevices) {
// Scan for changes.
int numFullKeyboardsAdded = 0;
mTempInputDevicesChangedListenersToNotify.clear();
mTempFullKeyboards.clear();
final int numListeners;
final int[] deviceIdAndGeneration;
synchronized (mInputDevicesLock) {
if (!mInputDevicesChangedPending) {
return;
}
mInputDevicesChangedPending = false;
numListeners = mInputDevicesChangedListeners.size();
for (int i = 0; i < numListeners; i++) {
mTempInputDevicesChangedListenersToNotify.add(
mInputDevicesChangedListeners.valueAt(i));
}
final int numDevices = mInputDevices.length;
deviceIdAndGeneration = new int[numDevices * 2];
for (int i = 0; i < numDevices; i++) {
final InputDevice inputDevice = mInputDevices[i];
deviceIdAndGeneration[i * 2] = inputDevice.getId();
deviceIdAndGeneration[i * 2 + 1] = inputDevice.getGeneration();
if (!inputDevice.isVirtual() && inputDevice.isFullKeyboard()) {
if (!containsInputDeviceWithDescriptor(oldInputDevices,
inputDevice.getDescriptor())) {
mTempFullKeyboards.add(numFullKeyboardsAdded++, inputDevice);
} else {
mTempFullKeyboards.add(inputDevice);
}
}
}
}
// Notify listeners.
for (int i = 0; i < numListeners; i++) {
mTempInputDevicesChangedListenersToNotify.get(i).notifyInputDevicesChanged(
deviceIdAndGeneration);
}
mTempInputDevicesChangedListenersToNotify.clear();
// Check for missing keyboard layouts.
if (mNotificationManager != null) {
final int numFullKeyboards = mTempFullKeyboards.size();
boolean missingLayoutForExternalKeyboard = false;
boolean missingLayoutForExternalKeyboardAdded = false;
synchronized (mDataStore) {
for (int i = 0; i < numFullKeyboards; i++) {
final InputDevice inputDevice = mTempFullKeyboards.get(i);
if (mDataStore.getCurrentKeyboardLayout(inputDevice.getDescriptor()) == null) {
missingLayoutForExternalKeyboard = true;
if (i < numFullKeyboardsAdded) {
missingLayoutForExternalKeyboardAdded = true;
}
}
}
}
if (missingLayoutForExternalKeyboard) {
if (missingLayoutForExternalKeyboardAdded) {
showMissingKeyboardLayoutNotification();
}
} else if (mKeyboardLayoutNotificationShown) {
hideMissingKeyboardLayoutNotification();
}
}
mTempFullKeyboards.clear();
}
// Must be called on handler.
private void showMissingKeyboardLayoutNotification() {
if (!mKeyboardLayoutNotificationShown) {
if (mKeyboardLayoutIntent == null) {
final Intent intent = new Intent("android.settings.INPUT_METHOD_SETTINGS");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
mKeyboardLayoutIntent = PendingIntent.getActivityAsUser(mContext, 0,
intent, 0, null, UserHandle.CURRENT);
}
Resources r = mContext.getResources();
Notification notification = new Notification.Builder(mContext)
.setContentTitle(r.getString(
R.string.select_keyboard_layout_notification_title))
.setContentText(r.getString(
R.string.select_keyboard_layout_notification_message))
.setContentIntent(mKeyboardLayoutIntent)
.setSmallIcon(R.drawable.ic_settings_language)
.setPriority(Notification.PRIORITY_LOW)
.build();
mNotificationManager.notifyAsUser(null,
R.string.select_keyboard_layout_notification_title,
notification, UserHandle.ALL);
mKeyboardLayoutNotificationShown = true;
}
}
// Must be called on handler.
private void hideMissingKeyboardLayoutNotification() {
if (mKeyboardLayoutNotificationShown) {
mKeyboardLayoutNotificationShown = false;
mNotificationManager.cancelAsUser(null,
R.string.select_keyboard_layout_notification_title,
UserHandle.ALL);
}
}
// Must be called on handler.
private void updateKeyboardLayouts() {
// Scan all input devices state for keyboard layouts that have been uninstalled.
final HashSet<String> availableKeyboardLayouts = new HashSet<String>();
visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
@Override
public void visitKeyboardLayout(Resources resources,
String descriptor, String label, String collection, int keyboardLayoutResId) {
availableKeyboardLayouts.add(descriptor);
}
});
synchronized (mDataStore) {
try {
mDataStore.removeUninstalledKeyboardLayouts(availableKeyboardLayouts);
} finally {
mDataStore.saveIfNeeded();
}
}
// Reload keyboard layouts.
reloadKeyboardLayouts();
}
private static boolean containsInputDeviceWithDescriptor(InputDevice[] inputDevices,
String descriptor) {
final int numDevices = inputDevices.length;
for (int i = 0; i < numDevices; i++) {
final InputDevice inputDevice = inputDevices[i];
if (inputDevice.getDescriptor().equals(descriptor)) {
return true;
}
}
return false;
}
@Override // Binder call
public KeyboardLayout[] getKeyboardLayouts() {
final ArrayList<KeyboardLayout> list = new ArrayList<KeyboardLayout>();
visitAllKeyboardLayouts(new KeyboardLayoutVisitor() {
@Override
public void visitKeyboardLayout(Resources resources,
String descriptor, String label, String collection, int keyboardLayoutResId) {
list.add(new KeyboardLayout(descriptor, label, collection));
}
});
return list.toArray(new KeyboardLayout[list.size()]);
}
@Override // Binder call
public KeyboardLayout getKeyboardLayout(String keyboardLayoutDescriptor) {
if (keyboardLayoutDescriptor == null) {
throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
}
final KeyboardLayout[] result = new KeyboardLayout[1];
visitKeyboardLayout(keyboardLayoutDescriptor, new KeyboardLayoutVisitor() {
@Override
public void visitKeyboardLayout(Resources resources,
String descriptor, String label, String collection, int keyboardLayoutResId) {
result[0] = new KeyboardLayout(descriptor, label, collection);
}
});
if (result[0] == null) {
Log.w(TAG, "Could not get keyboard layout with descriptor '"
+ keyboardLayoutDescriptor + "'.");
}
return result[0];
}
private void visitAllKeyboardLayouts(KeyboardLayoutVisitor visitor) {
final PackageManager pm = mContext.getPackageManager();
Intent intent = new Intent(InputManager.ACTION_QUERY_KEYBOARD_LAYOUTS);
for (ResolveInfo resolveInfo : pm.queryBroadcastReceivers(intent,
PackageManager.GET_META_DATA)) {
visitKeyboardLayoutsInPackage(pm, resolveInfo.activityInfo, null, visitor);
}
}
private void visitKeyboardLayout(String keyboardLayoutDescriptor,
KeyboardLayoutVisitor visitor) {
KeyboardLayoutDescriptor d = KeyboardLayoutDescriptor.parse(keyboardLayoutDescriptor);
if (d != null) {
final PackageManager pm = mContext.getPackageManager();
try {
ActivityInfo receiver = pm.getReceiverInfo(
new ComponentName(d.packageName, d.receiverName),
PackageManager.GET_META_DATA);
visitKeyboardLayoutsInPackage(pm, receiver, d.keyboardLayoutName, visitor);
} catch (NameNotFoundException ex) {
}
}
}
private void visitKeyboardLayoutsInPackage(PackageManager pm, ActivityInfo receiver,
String keyboardName, KeyboardLayoutVisitor visitor) {
Bundle metaData = receiver.metaData;
if (metaData == null) {
return;
}
int configResId = metaData.getInt(InputManager.META_DATA_KEYBOARD_LAYOUTS);
if (configResId == 0) {
Log.w(TAG, "Missing meta-data '" + InputManager.META_DATA_KEYBOARD_LAYOUTS
+ "' on receiver " + receiver.packageName + "/" + receiver.name);
return;
}
CharSequence receiverLabel = receiver.loadLabel(pm);
String collection = receiverLabel != null ? receiverLabel.toString() : "";
try {
Resources resources = pm.getResourcesForApplication(receiver.applicationInfo);
XmlResourceParser parser = resources.getXml(configResId);
try {
XmlUtils.beginDocument(parser, "keyboard-layouts");
for (;;) {
XmlUtils.nextElement(parser);
String element = parser.getName();
if (element == null) {
break;
}
if (element.equals("keyboard-layout")) {
TypedArray a = resources.obtainAttributes(
parser, com.android.internal.R.styleable.KeyboardLayout);
try {
String name = a.getString(
com.android.internal.R.styleable.KeyboardLayout_name);
String label = a.getString(
com.android.internal.R.styleable.KeyboardLayout_label);
int keyboardLayoutResId = a.getResourceId(
com.android.internal.R.styleable.KeyboardLayout_keyboardLayout,
0);
if (name == null || label == null || keyboardLayoutResId == 0) {
Log.w(TAG, "Missing required 'name', 'label' or 'keyboardLayout' "
+ "attributes in keyboard layout "
+ "resource from receiver "
+ receiver.packageName + "/" + receiver.name);
} else {
String descriptor = KeyboardLayoutDescriptor.format(
receiver.packageName, receiver.name, name);
if (keyboardName == null || name.equals(keyboardName)) {
visitor.visitKeyboardLayout(resources, descriptor,
label, collection, keyboardLayoutResId);
}
}
} finally {
a.recycle();
}
} else {
Log.w(TAG, "Skipping unrecognized element '" + element
+ "' in keyboard layout resource from receiver "
+ receiver.packageName + "/" + receiver.name);
}
}
} finally {
parser.close();
}
} catch (Exception ex) {
Log.w(TAG, "Could not parse keyboard layout resource from receiver "
+ receiver.packageName + "/" + receiver.name, ex);
}
}
@Override // Binder call
public String getCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor) {
if (inputDeviceDescriptor == null) {
throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
}
synchronized (mDataStore) {
return mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
}
}
@Override // Binder call
public void setCurrentKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
String keyboardLayoutDescriptor) {
if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
"setCurrentKeyboardLayoutForInputDevice()")) {
throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
}
if (inputDeviceDescriptor == null) {
throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
}
if (keyboardLayoutDescriptor == null) {
throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
}
synchronized (mDataStore) {
try {
if (mDataStore.setCurrentKeyboardLayout(
inputDeviceDescriptor, keyboardLayoutDescriptor)) {
mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
}
} finally {
mDataStore.saveIfNeeded();
}
}
}
@Override // Binder call
public String[] getKeyboardLayoutsForInputDevice(String inputDeviceDescriptor) {
if (inputDeviceDescriptor == null) {
throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
}
synchronized (mDataStore) {
return mDataStore.getKeyboardLayouts(inputDeviceDescriptor);
}
}
@Override // Binder call
public void addKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
String keyboardLayoutDescriptor) {
if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
"addKeyboardLayoutForInputDevice()")) {
throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
}
if (inputDeviceDescriptor == null) {
throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
}
if (keyboardLayoutDescriptor == null) {
throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
}
synchronized (mDataStore) {
try {
String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
if (mDataStore.addKeyboardLayout(inputDeviceDescriptor, keyboardLayoutDescriptor)
&& !Objects.equal(oldLayout,
mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
}
} finally {
mDataStore.saveIfNeeded();
}
}
}
@Override // Binder call
public void removeKeyboardLayoutForInputDevice(String inputDeviceDescriptor,
String keyboardLayoutDescriptor) {
if (!checkCallingPermission(android.Manifest.permission.SET_KEYBOARD_LAYOUT,
"removeKeyboardLayoutForInputDevice()")) {
throw new SecurityException("Requires SET_KEYBOARD_LAYOUT permission");
}
if (inputDeviceDescriptor == null) {
throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
}
if (keyboardLayoutDescriptor == null) {
throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
}
synchronized (mDataStore) {
try {
String oldLayout = mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor);
if (mDataStore.removeKeyboardLayout(inputDeviceDescriptor,
keyboardLayoutDescriptor)
&& !Objects.equal(oldLayout,
mDataStore.getCurrentKeyboardLayout(inputDeviceDescriptor))) {
mHandler.sendEmptyMessage(MSG_RELOAD_KEYBOARD_LAYOUTS);
}
} finally {
mDataStore.saveIfNeeded();
}
}
}
public void switchKeyboardLayout(int deviceId, int direction) {
mHandler.obtainMessage(MSG_SWITCH_KEYBOARD_LAYOUT, deviceId, direction).sendToTarget();