blob: f51d4a0d4a1e2088e7a98cf8cd53fd348503899a [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 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
17#include "Macros.h"
18
19#include "KeyboardInputMapper.h"
20
21namespace android {
22
23// --- Static Definitions ---
24
25static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
26 const int32_t map[][4], size_t mapSize) {
27 if (orientation != DISPLAY_ORIENTATION_0) {
28 for (size_t i = 0; i < mapSize; i++) {
29 if (value == map[i][0]) {
30 return map[i][orientation];
31 }
32 }
33 }
34 return value;
35}
36
37static const int32_t keyCodeRotationMap[][4] = {
38 // key codes enumerated counter-clockwise with the original (unrotated) key first
39 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
40 {AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT},
41 {AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN},
42 {AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT},
43 {AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP},
44 {AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
45 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT},
46 {AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
47 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN},
48 {AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
49 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT},
50 {AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
51 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP},
52};
53
54static const size_t keyCodeRotationMapSize =
55 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
56
57static int32_t rotateStemKey(int32_t value, int32_t orientation, const int32_t map[][2],
58 size_t mapSize) {
59 if (orientation == DISPLAY_ORIENTATION_180) {
60 for (size_t i = 0; i < mapSize; i++) {
61 if (value == map[i][0]) {
62 return map[i][1];
63 }
64 }
65 }
66 return value;
67}
68
69// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
70static int32_t stemKeyRotationMap[][2] = {
71 // key codes enumerated with the original (unrotated) key first
72 // no rotation, 180 degree rotation
73 {AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY},
74 {AKEYCODE_STEM_1, AKEYCODE_STEM_1},
75 {AKEYCODE_STEM_2, AKEYCODE_STEM_2},
76 {AKEYCODE_STEM_3, AKEYCODE_STEM_3},
77};
78
79static const size_t stemKeyRotationMapSize =
80 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
81
82static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
83 keyCode = rotateStemKey(keyCode, orientation, stemKeyRotationMap, stemKeyRotationMapSize);
84 return rotateValueUsingRotationMap(keyCode, orientation, keyCodeRotationMap,
85 keyCodeRotationMapSize);
86}
87
88// --- KeyboardInputMapper ---
89
90KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType)
91 : InputMapper(device), mSource(source), mKeyboardType(keyboardType) {}
92
93KeyboardInputMapper::~KeyboardInputMapper() {}
94
95uint32_t KeyboardInputMapper::getSources() {
96 return mSource;
97}
98
99int32_t KeyboardInputMapper::getOrientation() {
100 if (mViewport) {
101 return mViewport->orientation;
102 }
103 return DISPLAY_ORIENTATION_0;
104}
105
106int32_t KeyboardInputMapper::getDisplayId() {
107 if (mViewport) {
108 return mViewport->displayId;
109 }
110 return ADISPLAY_ID_NONE;
111}
112
113void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
114 InputMapper::populateDeviceInfo(info);
115
116 info->setKeyboardType(mKeyboardType);
117 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
118}
119
120void KeyboardInputMapper::dump(std::string& dump) {
121 dump += INDENT2 "Keyboard Input Mapper:\n";
122 dumpParameters(dump);
123 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
124 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
125 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
126 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
127 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
128}
129
130std::optional<DisplayViewport> KeyboardInputMapper::findViewport(
131 nsecs_t when, const InputReaderConfiguration* config) {
132 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
133 if (displayPort) {
134 // Find the viewport that contains the same port
135 return mDevice->getAssociatedViewport();
136 }
137
138 // No associated display defined, try to find default display if orientationAware.
139 if (mParameters.orientationAware) {
140 return config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
141 }
142
143 return std::nullopt;
144}
145
146void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
147 uint32_t changes) {
148 InputMapper::configure(when, config, changes);
149
150 if (!changes) { // first time only
151 // Configure basic parameters.
152 configureParameters();
153 }
154
155 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
156 mViewport = findViewport(when, config);
157 }
158}
159
160static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const* property) {
161 int32_t mapped = 0;
162 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
163 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
164 if (stemKeyRotationMap[i][0] == keyCode) {
165 stemKeyRotationMap[i][1] = mapped;
166 return;
167 }
168 }
169 }
170}
171
172void KeyboardInputMapper::configureParameters() {
173 mParameters.orientationAware = false;
174 const PropertyMap& config = getDevice()->getConfiguration();
175 config.tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware);
176
177 if (mParameters.orientationAware) {
178 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
179 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
180 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
181 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
182 }
183
184 mParameters.handlesKeyRepeat = false;
185 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"), mParameters.handlesKeyRepeat);
186}
187
188void KeyboardInputMapper::dumpParameters(std::string& dump) {
189 dump += INDENT3 "Parameters:\n";
190 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
191 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n", toString(mParameters.handlesKeyRepeat));
192}
193
194void KeyboardInputMapper::reset(nsecs_t when) {
195 mMetaState = AMETA_NONE;
196 mDownTime = 0;
197 mKeyDowns.clear();
198 mCurrentHidUsage = 0;
199
200 resetLedState();
201
202 InputMapper::reset(when);
203}
204
205void KeyboardInputMapper::process(const RawEvent* rawEvent) {
206 switch (rawEvent->type) {
207 case EV_KEY: {
208 int32_t scanCode = rawEvent->code;
209 int32_t usageCode = mCurrentHidUsage;
210 mCurrentHidUsage = 0;
211
212 if (isKeyboardOrGamepadKey(scanCode)) {
213 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
214 }
215 break;
216 }
217 case EV_MSC: {
218 if (rawEvent->code == MSC_SCAN) {
219 mCurrentHidUsage = rawEvent->value;
220 }
221 break;
222 }
223 case EV_SYN: {
224 if (rawEvent->code == SYN_REPORT) {
225 mCurrentHidUsage = 0;
226 }
227 }
228 }
229}
230
231bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
232 return scanCode < BTN_MOUSE || scanCode >= KEY_OK ||
233 (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) ||
234 (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
235}
236
237bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
238 switch (keyCode) {
239 case AKEYCODE_MEDIA_PLAY:
240 case AKEYCODE_MEDIA_PAUSE:
241 case AKEYCODE_MEDIA_PLAY_PAUSE:
242 case AKEYCODE_MUTE:
243 case AKEYCODE_HEADSETHOOK:
244 case AKEYCODE_MEDIA_STOP:
245 case AKEYCODE_MEDIA_NEXT:
246 case AKEYCODE_MEDIA_PREVIOUS:
247 case AKEYCODE_MEDIA_REWIND:
248 case AKEYCODE_MEDIA_RECORD:
249 case AKEYCODE_MEDIA_FAST_FORWARD:
250 case AKEYCODE_MEDIA_SKIP_FORWARD:
251 case AKEYCODE_MEDIA_SKIP_BACKWARD:
252 case AKEYCODE_MEDIA_STEP_FORWARD:
253 case AKEYCODE_MEDIA_STEP_BACKWARD:
254 case AKEYCODE_MEDIA_AUDIO_TRACK:
255 case AKEYCODE_VOLUME_UP:
256 case AKEYCODE_VOLUME_DOWN:
257 case AKEYCODE_VOLUME_MUTE:
258 case AKEYCODE_TV_AUDIO_DESCRIPTION:
259 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
260 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
261 return true;
262 }
263 return false;
264}
265
266void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode) {
267 int32_t keyCode;
268 int32_t keyMetaState;
269 uint32_t policyFlags;
270
271 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState, &keyCode,
272 &keyMetaState, &policyFlags)) {
273 keyCode = AKEYCODE_UNKNOWN;
274 keyMetaState = mMetaState;
275 policyFlags = 0;
276 }
277
278 if (down) {
279 // Rotate key codes according to orientation if needed.
280 if (mParameters.orientationAware) {
281 keyCode = rotateKeyCode(keyCode, getOrientation());
282 }
283
284 // Add key down.
285 ssize_t keyDownIndex = findKeyDown(scanCode);
286 if (keyDownIndex >= 0) {
287 // key repeat, be sure to use same keycode as before in case of rotation
288 keyCode = mKeyDowns[keyDownIndex].keyCode;
289 } else {
290 // key down
291 if ((policyFlags & POLICY_FLAG_VIRTUAL) &&
292 mContext->shouldDropVirtualKey(when, getDevice(), keyCode, scanCode)) {
293 return;
294 }
295 if (policyFlags & POLICY_FLAG_GESTURE) {
296 mDevice->cancelTouch(when);
297 }
298
299 KeyDown keyDown;
300 keyDown.keyCode = keyCode;
301 keyDown.scanCode = scanCode;
302 mKeyDowns.push_back(keyDown);
303 }
304
305 mDownTime = when;
306 } else {
307 // Remove key down.
308 ssize_t keyDownIndex = findKeyDown(scanCode);
309 if (keyDownIndex >= 0) {
310 // key up, be sure to use same keycode as before in case of rotation
311 keyCode = mKeyDowns[keyDownIndex].keyCode;
312 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
313 } else {
314 // key was not actually down
315 ALOGI("Dropping key up from device %s because the key was not down. "
316 "keyCode=%d, scanCode=%d",
317 getDeviceName().c_str(), keyCode, scanCode);
318 return;
319 }
320 }
321
322 if (updateMetaStateIfNeeded(keyCode, down)) {
323 // If global meta state changed send it along with the key.
324 // If it has not changed then we'll use what keymap gave us,
325 // since key replacement logic might temporarily reset a few
326 // meta bits for given key.
327 keyMetaState = mMetaState;
328 }
329
330 nsecs_t downTime = mDownTime;
331
332 // Key down on external an keyboard should wake the device.
333 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
334 // For internal keyboards, the key layout file should specify the policy flags for
335 // each wake key individually.
336 // TODO: Use the input device configuration to control this behavior more finely.
337 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
338 policyFlags |= POLICY_FLAG_WAKE;
339 }
340
341 if (mParameters.handlesKeyRepeat) {
342 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
343 }
344
345 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, getDisplayId(),
346 policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
347 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
348 getListener()->notifyKey(&args);
349}
350
351ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
352 size_t n = mKeyDowns.size();
353 for (size_t i = 0; i < n; i++) {
354 if (mKeyDowns[i].scanCode == scanCode) {
355 return i;
356 }
357 }
358 return -1;
359}
360
361int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
362 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
363}
364
365int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
366 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
367}
368
369bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
370 const int32_t* keyCodes, uint8_t* outFlags) {
371 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
372}
373
374int32_t KeyboardInputMapper::getMetaState() {
375 return mMetaState;
376}
377
378void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
379 updateMetaStateIfNeeded(keyCode, false);
380}
381
382bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
383 int32_t oldMetaState = mMetaState;
384 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
385 bool metaStateChanged = oldMetaState != newMetaState;
386 if (metaStateChanged) {
387 mMetaState = newMetaState;
388 updateLedState(false);
389
390 getContext()->updateGlobalMetaState();
391 }
392
393 return metaStateChanged;
394}
395
396void KeyboardInputMapper::resetLedState() {
397 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
398 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
399 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
400
401 updateLedState(true);
402}
403
404void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
405 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
406 ledState.on = false;
407}
408
409void KeyboardInputMapper::updateLedState(bool reset) {
410 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK, AMETA_CAPS_LOCK_ON, reset);
411 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK, AMETA_NUM_LOCK_ON, reset);
412 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, reset);
413}
414
415void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, int32_t led,
416 int32_t modifier, bool reset) {
417 if (ledState.avail) {
418 bool desiredState = (mMetaState & modifier) != 0;
419 if (reset || ledState.on != desiredState) {
420 getEventHub()->setLedState(getDeviceId(), led, desiredState);
421 ledState.on = desiredState;
422 }
423 }
424}
425
426std::optional<int32_t> KeyboardInputMapper::getAssociatedDisplayId() {
427 if (mViewport) {
428 return std::make_optional(mViewport->displayId);
429 }
430 return std::nullopt;
431}
432
433} // namespace android