• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 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 #define LOG_TAG "KeyLayoutMap"
18 
19 #include <android-base/logging.h>
20 #include <android/keycodes.h>
21 #include <ftl/enum.h>
22 #include <input/InputEventLabels.h>
23 #include <input/KeyLayoutMap.h>
24 #include <input/Keyboard.h>
25 #include <log/log.h>
26 #include <utils/Errors.h>
27 #include <utils/Timers.h>
28 #include <utils/Tokenizer.h>
29 #if defined(__ANDROID__)
30 #include <vintf/KernelConfigs.h>
31 #endif
32 
33 #include <cstdlib>
34 #include <string_view>
35 #include <unordered_map>
36 
37 /**
38  * Log debug output for the parser.
39  * Enable this via "adb shell setprop log.tag.KeyLayoutMapParser DEBUG" (requires restart)
40  */
41 const bool DEBUG_PARSER =
42         __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Parser", ANDROID_LOG_INFO);
43 
44 // Enables debug output for parser performance.
45 #define DEBUG_PARSER_PERFORMANCE 0
46 
47 /**
48  * Log debug output for mapping.
49  * Enable this via "adb shell setprop log.tag.KeyLayoutMapMapping DEBUG" (requires restart)
50  */
51 const bool DEBUG_MAPPING =
52         __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Mapping", ANDROID_LOG_INFO);
53 
54 namespace android {
55 namespace {
56 
parseInt(const char * str)57 std::optional<int> parseInt(const char* str) {
58     char* end;
59     errno = 0;
60     const int value = strtol(str, &end, 0);
61     if (end == str) {
62         LOG(ERROR) << "Could not parse " << str;
63         return {};
64     }
65     if (errno == ERANGE) {
66         LOG(ERROR) << "Out of bounds: " << str;
67         return {};
68     }
69     return value;
70 }
71 
72 constexpr const char* WHITESPACE = " \t\r";
73 
74 template <InputDeviceSensorType S>
sensorPair()75 constexpr auto sensorPair() {
76     return std::make_pair(ftl::enum_name<S>(), S);
77 }
78 
79 static const std::unordered_map<std::string_view, InputDeviceSensorType> SENSOR_LIST =
80         {sensorPair<InputDeviceSensorType::ACCELEROMETER>(),
81          sensorPair<InputDeviceSensorType::MAGNETIC_FIELD>(),
82          sensorPair<InputDeviceSensorType::ORIENTATION>(),
83          sensorPair<InputDeviceSensorType::GYROSCOPE>(),
84          sensorPair<InputDeviceSensorType::LIGHT>(),
85          sensorPair<InputDeviceSensorType::PRESSURE>(),
86          sensorPair<InputDeviceSensorType::TEMPERATURE>(),
87          sensorPair<InputDeviceSensorType::PROXIMITY>(),
88          sensorPair<InputDeviceSensorType::GRAVITY>(),
89          sensorPair<InputDeviceSensorType::LINEAR_ACCELERATION>(),
90          sensorPair<InputDeviceSensorType::ROTATION_VECTOR>(),
91          sensorPair<InputDeviceSensorType::RELATIVE_HUMIDITY>(),
92          sensorPair<InputDeviceSensorType::AMBIENT_TEMPERATURE>(),
93          sensorPair<InputDeviceSensorType::MAGNETIC_FIELD_UNCALIBRATED>(),
94          sensorPair<InputDeviceSensorType::GAME_ROTATION_VECTOR>(),
95          sensorPair<InputDeviceSensorType::GYROSCOPE_UNCALIBRATED>(),
96          sensorPair<InputDeviceSensorType::SIGNIFICANT_MOTION>()};
97 
kernelConfigsArePresent(const std::set<std::string> & configs)98 bool kernelConfigsArePresent(const std::set<std::string>& configs) {
99 #if defined(__ANDROID__)
100     if (configs.empty()) {
101         return true;
102     }
103 
104     std::map<std::string, std::string> kernelConfigs;
105     const status_t result = android::kernelconfigs::LoadKernelConfigs(&kernelConfigs);
106     LOG_ALWAYS_FATAL_IF(result != OK, "Kernel configs could not be fetched");
107 
108     for (const std::string& requiredConfig : configs) {
109         const auto configIt = kernelConfigs.find(requiredConfig);
110         if (configIt == kernelConfigs.end()) {
111             ALOGI("Required kernel config %s is not found", requiredConfig.c_str());
112             return false;
113         }
114         const std::string& option = configIt->second;
115         if (option != "y" && option != "m") {
116             ALOGI("Required kernel config %s has option %s", requiredConfig.c_str(),
117                   option.c_str());
118             return false;
119         }
120     }
121     return true;
122 #else
123     (void)configs; // Suppress 'unused variable' warning
124     return true;
125 #endif
126 }
127 
128 } // namespace
129 
130 KeyLayoutMap::KeyLayoutMap() = default;
131 KeyLayoutMap::~KeyLayoutMap() = default;
132 
loadContents(const std::string & filename,const char * contents)133 base::Result<std::shared_ptr<KeyLayoutMap>> KeyLayoutMap::loadContents(const std::string& filename,
134                                                                        const char* contents) {
135     return load(filename, contents);
136 }
137 
load(const std::string & filename,const char * contents)138 base::Result<std::shared_ptr<KeyLayoutMap>> KeyLayoutMap::load(const std::string& filename,
139                                                                const char* contents) {
140     Tokenizer* tokenizer;
141     status_t status;
142     if (contents == nullptr) {
143         status = Tokenizer::open(String8(filename.c_str()), &tokenizer);
144     } else {
145         status = Tokenizer::fromContents(String8(filename.c_str()), contents, &tokenizer);
146     }
147     if (status) {
148         ALOGE("Error %d opening key layout map file %s.", status, filename.c_str());
149         return Errorf("Error {} opening key layout map file {}.", status, filename.c_str());
150     }
151     std::unique_ptr<Tokenizer> t(tokenizer);
152     auto ret = load(t.get());
153     if (!ret.ok()) {
154         return ret;
155     }
156     const std::shared_ptr<KeyLayoutMap>& map = *ret;
157     LOG_ALWAYS_FATAL_IF(map == nullptr, "Returned map should not be null if there's no error");
158     if (!kernelConfigsArePresent(map->mRequiredKernelConfigs)) {
159         ALOGI("Not loading %s because the required kernel configs are not set", filename.c_str());
160         return Errorf("Missing kernel config");
161     }
162     map->mLoadFileName = filename;
163     return ret;
164 }
165 
load(Tokenizer * tokenizer)166 base::Result<std::shared_ptr<KeyLayoutMap>> KeyLayoutMap::load(Tokenizer* tokenizer) {
167     std::shared_ptr<KeyLayoutMap> map = std::shared_ptr<KeyLayoutMap>(new KeyLayoutMap());
168     status_t status = OK;
169     if (!map.get()) {
170         ALOGE("Error allocating key layout map.");
171         return Errorf("Error allocating key layout map.");
172     } else {
173 #if DEBUG_PARSER_PERFORMANCE
174         nsecs_t startTime = systemTime(SYSTEM_TIME_MONOTONIC);
175 #endif
176         Parser parser(map.get(), tokenizer);
177         status = parser.parse();
178 #if DEBUG_PARSER_PERFORMANCE
179         nsecs_t elapsedTime = systemTime(SYSTEM_TIME_MONOTONIC) - startTime;
180         ALOGD("Parsed key layout map file '%s' %d lines in %0.3fms.",
181               tokenizer->getFilename().c_str(), tokenizer->getLineNumber(),
182               elapsedTime / 1000000.0);
183 #endif
184         if (!status) {
185             return std::move(map);
186         }
187     }
188     return Errorf("Load KeyLayoutMap failed {}.", status);
189 }
190 
mapKey(int32_t scanCode,int32_t usageCode,int32_t * outKeyCode,uint32_t * outFlags) const191 status_t KeyLayoutMap::mapKey(int32_t scanCode, int32_t usageCode,
192         int32_t* outKeyCode, uint32_t* outFlags) const {
193     const Key* key = getKey(scanCode, usageCode);
194     if (!key) {
195         ALOGD_IF(DEBUG_MAPPING, "mapKey: scanCode=%d, usageCode=0x%08x ~ Failed.", scanCode,
196                  usageCode);
197         *outKeyCode = AKEYCODE_UNKNOWN;
198         *outFlags = 0;
199         return NAME_NOT_FOUND;
200     }
201 
202     *outKeyCode = key->keyCode;
203     *outFlags = key->flags;
204 
205     ALOGD_IF(DEBUG_MAPPING,
206              "mapKey: scanCode=%d, usageCode=0x%08x ~ Result keyCode=%d, outFlags=0x%08x.",
207              scanCode, usageCode, *outKeyCode, *outFlags);
208     return NO_ERROR;
209 }
210 
211 // Return pair of sensor type and sensor data index, for the input device abs code
mapSensor(int32_t absCode) const212 base::Result<std::pair<InputDeviceSensorType, int32_t>> KeyLayoutMap::mapSensor(
213         int32_t absCode) const {
214     auto it = mSensorsByAbsCode.find(absCode);
215     if (it == mSensorsByAbsCode.end()) {
216         ALOGD_IF(DEBUG_MAPPING, "mapSensor: absCode=%d, ~ Failed.", absCode);
217         return Errorf("Can't find abs code {}.", absCode);
218     }
219     const Sensor& sensor = it->second;
220     ALOGD_IF(DEBUG_MAPPING, "mapSensor: absCode=%d, sensorType=%s, sensorDataIndex=0x%x.", absCode,
221              ftl::enum_string(sensor.sensorType).c_str(), sensor.sensorDataIndex);
222     return std::make_pair(sensor.sensorType, sensor.sensorDataIndex);
223 }
224 
getKey(int32_t scanCode,int32_t usageCode) const225 const KeyLayoutMap::Key* KeyLayoutMap::getKey(int32_t scanCode, int32_t usageCode) const {
226     if (usageCode) {
227         auto it = mKeysByUsageCode.find(usageCode);
228         if (it != mKeysByUsageCode.end()) {
229             return &it->second;
230         }
231     }
232     if (scanCode) {
233         auto it = mKeysByScanCode.find(scanCode);
234         if (it != mKeysByScanCode.end()) {
235             return &it->second;
236         }
237     }
238     return nullptr;
239 }
240 
findScanCodesForKey(int32_t keyCode) const241 std::vector<int32_t> KeyLayoutMap::findScanCodesForKey(int32_t keyCode) const {
242     std::vector<int32_t> scanCodes;
243     for (const auto& [scanCode, key] : mKeysByScanCode) {
244         if (keyCode == key.keyCode) {
245             scanCodes.push_back(scanCode);
246         }
247     }
248     return scanCodes;
249 }
250 
findUsageCodesForKey(int32_t keyCode) const251 std::vector<int32_t> KeyLayoutMap::findUsageCodesForKey(int32_t keyCode) const {
252     std::vector<int32_t> usageCodes;
253     for (const auto& [usageCode, key] : mKeysByUsageCode) {
254         if (keyCode == key.keyCode && !(key.flags & POLICY_FLAG_FALLBACK_USAGE_MAPPING)) {
255             usageCodes.push_back(usageCode);
256         }
257     }
258     return usageCodes;
259 }
260 
mapAxis(int32_t scanCode) const261 std::optional<AxisInfo> KeyLayoutMap::mapAxis(int32_t scanCode) const {
262     auto it = mAxes.find(scanCode);
263     if (it == mAxes.end()) {
264         ALOGD_IF(DEBUG_MAPPING, "mapAxis: scanCode=%d ~ Failed.", scanCode);
265         return std::nullopt;
266     }
267 
268     const AxisInfo& axisInfo = it->second;
269     ALOGD_IF(DEBUG_MAPPING,
270              "mapAxis: scanCode=%d ~ Result mode=%d, axis=%d, highAxis=%d, "
271              "splitValue=%d, flatOverride=%d.",
272              scanCode, axisInfo.mode, axisInfo.axis, axisInfo.highAxis, axisInfo.splitValue,
273              axisInfo.flatOverride);
274     return axisInfo;
275 }
276 
findScanCodeForLed(int32_t ledCode) const277 std::optional<int32_t> KeyLayoutMap::findScanCodeForLed(int32_t ledCode) const {
278     for (const auto& [scanCode, led] : mLedsByScanCode) {
279         if (led.ledCode == ledCode) {
280             ALOGD_IF(DEBUG_MAPPING, "%s: ledCode=%d, scanCode=%d.", __func__, ledCode, scanCode);
281             return scanCode;
282         }
283     }
284     ALOGD_IF(DEBUG_MAPPING, "%s: ledCode=%d ~ Not found.", __func__, ledCode);
285     return std::nullopt;
286 }
287 
findUsageCodeForLed(int32_t ledCode) const288 std::optional<int32_t> KeyLayoutMap::findUsageCodeForLed(int32_t ledCode) const {
289     for (const auto& [usageCode, led] : mLedsByUsageCode) {
290         if (led.ledCode == ledCode) {
291             ALOGD_IF(DEBUG_MAPPING, "%s: ledCode=%d, usage=%x.", __func__, ledCode, usageCode);
292             return usageCode;
293         }
294     }
295     ALOGD_IF(DEBUG_MAPPING, "%s: ledCode=%d ~ Not found.", __func__, ledCode);
296     return std::nullopt;
297 }
298 
299 // --- KeyLayoutMap::Parser ---
300 
Parser(KeyLayoutMap * map,Tokenizer * tokenizer)301 KeyLayoutMap::Parser::Parser(KeyLayoutMap* map, Tokenizer* tokenizer) :
302         mMap(map), mTokenizer(tokenizer) {
303 }
304 
~Parser()305 KeyLayoutMap::Parser::~Parser() {
306 }
307 
parse()308 status_t KeyLayoutMap::Parser::parse() {
309     while (!mTokenizer->isEof()) {
310         ALOGD_IF(DEBUG_PARSER, "Parsing %s: '%s'.", mTokenizer->getLocation().c_str(),
311                  mTokenizer->peekRemainderOfLine().c_str());
312 
313         mTokenizer->skipDelimiters(WHITESPACE);
314 
315         if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
316             String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
317             if (keywordToken == "key") {
318                 mTokenizer->skipDelimiters(WHITESPACE);
319                 status_t status = parseKey();
320                 if (status) return status;
321             } else if (keywordToken == "axis") {
322                 mTokenizer->skipDelimiters(WHITESPACE);
323                 status_t status = parseAxis();
324                 if (status) return status;
325             } else if (keywordToken == "led") {
326                 mTokenizer->skipDelimiters(WHITESPACE);
327                 status_t status = parseLed();
328                 if (status) return status;
329             } else if (keywordToken == "sensor") {
330                 mTokenizer->skipDelimiters(WHITESPACE);
331                 status_t status = parseSensor();
332                 if (status) return status;
333             } else if (keywordToken == "requires_kernel_config") {
334                 mTokenizer->skipDelimiters(WHITESPACE);
335                 status_t status = parseRequiredKernelConfig();
336                 if (status) return status;
337             } else {
338                 ALOGE("%s: Expected keyword, got '%s'.", mTokenizer->getLocation().c_str(),
339                       keywordToken.c_str());
340                 return BAD_VALUE;
341             }
342 
343             mTokenizer->skipDelimiters(WHITESPACE);
344             if (!mTokenizer->isEol() && mTokenizer->peekChar() != '#') {
345                 ALOGE("%s: Expected end of line or trailing comment, got '%s'.",
346                       mTokenizer->getLocation().c_str(), mTokenizer->peekRemainderOfLine().c_str());
347                 return BAD_VALUE;
348             }
349         }
350 
351         mTokenizer->nextLine();
352     }
353     return NO_ERROR;
354 }
355 
parseKey()356 status_t KeyLayoutMap::Parser::parseKey() {
357     String8 codeToken = mTokenizer->nextToken(WHITESPACE);
358     bool mapUsage = false;
359     if (codeToken == "usage") {
360         mapUsage = true;
361         mTokenizer->skipDelimiters(WHITESPACE);
362         codeToken = mTokenizer->nextToken(WHITESPACE);
363     }
364 
365     std::optional<int> code = parseInt(codeToken.c_str());
366     if (!code) {
367         ALOGE("%s: Expected key %s number, got '%s'.", mTokenizer->getLocation().c_str(),
368                 mapUsage ? "usage" : "scan code", codeToken.c_str());
369         return BAD_VALUE;
370     }
371     std::unordered_map<int32_t, Key>& map =
372             mapUsage ? mMap->mKeysByUsageCode : mMap->mKeysByScanCode;
373     if (map.find(*code) != map.end()) {
374         ALOGE("%s: Duplicate entry for key %s '%s'.", mTokenizer->getLocation().c_str(),
375                 mapUsage ? "usage" : "scan code", codeToken.c_str());
376         return BAD_VALUE;
377     }
378 
379     mTokenizer->skipDelimiters(WHITESPACE);
380     String8 keyCodeToken = mTokenizer->nextToken(WHITESPACE);
381     std::optional<int> keyCode = InputEventLookup::getKeyCodeByLabel(keyCodeToken.c_str());
382     if (!keyCode) {
383         ALOGE("%s: Expected key code label, got '%s'.", mTokenizer->getLocation().c_str(),
384               keyCodeToken.c_str());
385         return BAD_VALUE;
386     }
387 
388     uint32_t flags = 0;
389     for (;;) {
390         mTokenizer->skipDelimiters(WHITESPACE);
391         if (mTokenizer->isEol() || mTokenizer->peekChar() == '#') break;
392 
393         String8 flagToken = mTokenizer->nextToken(WHITESPACE);
394         std::optional<int> flag = InputEventLookup::getKeyFlagByLabel(flagToken.c_str());
395         if (!flag) {
396             ALOGE("%s: Expected key flag label, got '%s'.", mTokenizer->getLocation().c_str(),
397                   flagToken.c_str());
398             return BAD_VALUE;
399         }
400         if (flags & *flag) {
401             ALOGE("%s: Duplicate key flag '%s'.", mTokenizer->getLocation().c_str(),
402                     flagToken.c_str());
403             return BAD_VALUE;
404         }
405         flags |= *flag;
406     }
407 
408     ALOGD_IF(DEBUG_PARSER, "Parsed key %s: code=%d, keyCode=%d, flags=0x%08x.",
409              mapUsage ? "usage" : "scan code", *code, *keyCode, flags);
410 
411     Key key;
412     key.keyCode = *keyCode;
413     key.flags = flags;
414     map.insert({*code, key});
415     return NO_ERROR;
416 }
417 
parseAxis()418 status_t KeyLayoutMap::Parser::parseAxis() {
419     String8 scanCodeToken = mTokenizer->nextToken(WHITESPACE);
420     std::optional<int> scanCode = parseInt(scanCodeToken.c_str());
421     if (!scanCode) {
422         ALOGE("%s: Expected axis scan code number, got '%s'.", mTokenizer->getLocation().c_str(),
423                 scanCodeToken.c_str());
424         return BAD_VALUE;
425     }
426     if (mMap->mAxes.find(*scanCode) != mMap->mAxes.end()) {
427         ALOGE("%s: Duplicate entry for axis scan code '%s'.", mTokenizer->getLocation().c_str(),
428                 scanCodeToken.c_str());
429         return BAD_VALUE;
430     }
431 
432     AxisInfo axisInfo;
433 
434     mTokenizer->skipDelimiters(WHITESPACE);
435     String8 token = mTokenizer->nextToken(WHITESPACE);
436     if (token == "invert") {
437         axisInfo.mode = AxisInfo::MODE_INVERT;
438 
439         mTokenizer->skipDelimiters(WHITESPACE);
440         String8 axisToken = mTokenizer->nextToken(WHITESPACE);
441         std::optional<int> axis = InputEventLookup::getAxisByLabel(axisToken.c_str());
442         if (!axis) {
443             ALOGE("%s: Expected inverted axis label, got '%s'.",
444                     mTokenizer->getLocation().c_str(), axisToken.c_str());
445             return BAD_VALUE;
446         }
447         axisInfo.axis = *axis;
448     } else if (token == "split") {
449         axisInfo.mode = AxisInfo::MODE_SPLIT;
450 
451         mTokenizer->skipDelimiters(WHITESPACE);
452         String8 splitToken = mTokenizer->nextToken(WHITESPACE);
453         std::optional<int> splitValue = parseInt(splitToken.c_str());
454         if (!splitValue) {
455             ALOGE("%s: Expected split value, got '%s'.",
456                     mTokenizer->getLocation().c_str(), splitToken.c_str());
457             return BAD_VALUE;
458         }
459         axisInfo.splitValue = *splitValue;
460 
461         mTokenizer->skipDelimiters(WHITESPACE);
462         String8 lowAxisToken = mTokenizer->nextToken(WHITESPACE);
463         std::optional<int> axis = InputEventLookup::getAxisByLabel(lowAxisToken.c_str());
464         if (!axis) {
465             ALOGE("%s: Expected low axis label, got '%s'.",
466                     mTokenizer->getLocation().c_str(), lowAxisToken.c_str());
467             return BAD_VALUE;
468         }
469         axisInfo.axis = *axis;
470 
471         mTokenizer->skipDelimiters(WHITESPACE);
472         String8 highAxisToken = mTokenizer->nextToken(WHITESPACE);
473         std::optional<int> highAxis = InputEventLookup::getAxisByLabel(highAxisToken.c_str());
474         if (!highAxis) {
475             ALOGE("%s: Expected high axis label, got '%s'.",
476                     mTokenizer->getLocation().c_str(), highAxisToken.c_str());
477             return BAD_VALUE;
478         }
479         axisInfo.highAxis = *highAxis;
480     } else {
481         std::optional<int> axis = InputEventLookup::getAxisByLabel(token.c_str());
482         if (!axis) {
483             ALOGE("%s: Expected axis label, 'split' or 'invert', got '%s'.",
484                   mTokenizer->getLocation().c_str(), token.c_str());
485             return BAD_VALUE;
486         }
487         axisInfo.axis = *axis;
488     }
489 
490     for (;;) {
491         mTokenizer->skipDelimiters(WHITESPACE);
492         if (mTokenizer->isEol() || mTokenizer->peekChar() == '#') {
493             break;
494         }
495         String8 keywordToken = mTokenizer->nextToken(WHITESPACE);
496         if (keywordToken == "flat") {
497             mTokenizer->skipDelimiters(WHITESPACE);
498             String8 flatToken = mTokenizer->nextToken(WHITESPACE);
499             std::optional<int> flatOverride = parseInt(flatToken.c_str());
500             if (!flatOverride) {
501                 ALOGE("%s: Expected flat value, got '%s'.",
502                         mTokenizer->getLocation().c_str(), flatToken.c_str());
503                 return BAD_VALUE;
504             }
505             axisInfo.flatOverride = *flatOverride;
506         } else {
507             ALOGE("%s: Expected keyword 'flat', got '%s'.", mTokenizer->getLocation().c_str(),
508                   keywordToken.c_str());
509             return BAD_VALUE;
510         }
511     }
512 
513     ALOGD_IF(DEBUG_PARSER,
514              "Parsed axis: scanCode=%d, mode=%d, axis=%d, highAxis=%d, "
515              "splitValue=%d, flatOverride=%d.",
516              *scanCode, axisInfo.mode, axisInfo.axis, axisInfo.highAxis, axisInfo.splitValue,
517              axisInfo.flatOverride);
518     mMap->mAxes.insert({*scanCode, axisInfo});
519     return NO_ERROR;
520 }
521 
parseLed()522 status_t KeyLayoutMap::Parser::parseLed() {
523     String8 codeToken = mTokenizer->nextToken(WHITESPACE);
524     bool mapUsage = false;
525     if (codeToken == "usage") {
526         mapUsage = true;
527         mTokenizer->skipDelimiters(WHITESPACE);
528         codeToken = mTokenizer->nextToken(WHITESPACE);
529     }
530     std::optional<int> code = parseInt(codeToken.c_str());
531     if (!code) {
532         ALOGE("%s: Expected led %s number, got '%s'.", mTokenizer->getLocation().c_str(),
533                 mapUsage ? "usage" : "scan code", codeToken.c_str());
534         return BAD_VALUE;
535     }
536 
537     std::unordered_map<int32_t, Led>& map =
538             mapUsage ? mMap->mLedsByUsageCode : mMap->mLedsByScanCode;
539     if (map.find(*code) != map.end()) {
540         ALOGE("%s: Duplicate entry for led %s '%s'.", mTokenizer->getLocation().c_str(),
541                 mapUsage ? "usage" : "scan code", codeToken.c_str());
542         return BAD_VALUE;
543     }
544 
545     mTokenizer->skipDelimiters(WHITESPACE);
546     String8 ledCodeToken = mTokenizer->nextToken(WHITESPACE);
547     std::optional<int> ledCode = InputEventLookup::getLedByLabel(ledCodeToken.c_str());
548     if (!ledCode) {
549         ALOGE("%s: Expected LED code label, got '%s'.", mTokenizer->getLocation().c_str(),
550                 ledCodeToken.c_str());
551         return BAD_VALUE;
552     }
553 
554     ALOGD_IF(DEBUG_PARSER, "Parsed led %s: code=%d, ledCode=%d.", mapUsage ? "usage" : "scan code",
555              *code, *ledCode);
556 
557     Led led;
558     led.ledCode = *ledCode;
559     map.insert({*code, led});
560     return NO_ERROR;
561 }
562 
getSensorType(const char * token)563 static std::optional<InputDeviceSensorType> getSensorType(const char* token) {
564     auto it = SENSOR_LIST.find(token);
565     if (it == SENSOR_LIST.end()) {
566         return std::nullopt;
567     }
568     return it->second;
569 }
570 
getSensorDataIndex(String8 token)571 static std::optional<int32_t> getSensorDataIndex(String8 token) {
572     std::string tokenStr(token.c_str());
573     if (tokenStr == "X") {
574         return 0;
575     } else if (tokenStr == "Y") {
576         return 1;
577     } else if (tokenStr == "Z") {
578         return 2;
579     }
580     return std::nullopt;
581 }
582 
583 // Parse sensor type and data index mapping, as below format
584 // sensor <raw abs> <sensor type> <sensor data index>
585 // raw abs : the linux abs code of the axis
586 // sensor type : string name of InputDeviceSensorType
587 // sensor data index : the data index of sensor, out of [X, Y, Z]
588 // Examples:
589 // sensor 0x00 ACCELEROMETER X
590 // sensor 0x01 ACCELEROMETER Y
591 // sensor 0x02 ACCELEROMETER Z
592 // sensor 0x03 GYROSCOPE X
593 // sensor 0x04 GYROSCOPE Y
594 // sensor 0x05 GYROSCOPE Z
parseSensor()595 status_t KeyLayoutMap::Parser::parseSensor() {
596     String8 codeToken = mTokenizer->nextToken(WHITESPACE);
597     std::optional<int> code = parseInt(codeToken.c_str());
598     if (!code) {
599         ALOGE("%s: Expected sensor %s number, got '%s'.", mTokenizer->getLocation().c_str(),
600               "abs code", codeToken.c_str());
601         return BAD_VALUE;
602     }
603 
604     std::unordered_map<int32_t, Sensor>& map = mMap->mSensorsByAbsCode;
605     if (map.find(*code) != map.end()) {
606         ALOGE("%s: Duplicate entry for sensor %s '%s'.", mTokenizer->getLocation().c_str(),
607               "abs code", codeToken.c_str());
608         return BAD_VALUE;
609     }
610 
611     mTokenizer->skipDelimiters(WHITESPACE);
612     String8 sensorTypeToken = mTokenizer->nextToken(WHITESPACE);
613     std::optional<InputDeviceSensorType> typeOpt = getSensorType(sensorTypeToken.c_str());
614     if (!typeOpt) {
615         ALOGE("%s: Expected sensor code label, got '%s'.", mTokenizer->getLocation().c_str(),
616               sensorTypeToken.c_str());
617         return BAD_VALUE;
618     }
619     InputDeviceSensorType sensorType = typeOpt.value();
620     mTokenizer->skipDelimiters(WHITESPACE);
621     String8 sensorDataIndexToken = mTokenizer->nextToken(WHITESPACE);
622     std::optional<int32_t> indexOpt = getSensorDataIndex(sensorDataIndexToken);
623     if (!indexOpt) {
624         ALOGE("%s: Expected sensor data index label, got '%s'.", mTokenizer->getLocation().c_str(),
625               sensorDataIndexToken.c_str());
626         return BAD_VALUE;
627     }
628     int32_t sensorDataIndex = indexOpt.value();
629 
630     ALOGD_IF(DEBUG_PARSER, "Parsed sensor: abs code=%d, sensorType=%s, sensorDataIndex=%d.", *code,
631              ftl::enum_string(sensorType).c_str(), sensorDataIndex);
632 
633     Sensor sensor;
634     sensor.sensorType = sensorType;
635     sensor.sensorDataIndex = sensorDataIndex;
636     map.emplace(*code, sensor);
637     return NO_ERROR;
638 }
639 
640 // Parse the name of a required kernel config.
641 // The layout won't be used if the specified kernel config is not present
642 // Examples:
643 // requires_kernel_config CONFIG_HID_PLAYSTATION
parseRequiredKernelConfig()644 status_t KeyLayoutMap::Parser::parseRequiredKernelConfig() {
645     String8 codeToken = mTokenizer->nextToken(WHITESPACE);
646     std::string configName = codeToken.c_str();
647 
648     const auto result = mMap->mRequiredKernelConfigs.emplace(configName);
649     if (!result.second) {
650         ALOGE("%s: Duplicate entry for required kernel config %s.",
651               mTokenizer->getLocation().c_str(), configName.c_str());
652         return BAD_VALUE;
653     }
654 
655     ALOGD_IF(DEBUG_PARSER, "Parsed required kernel config: name=%s", configName.c_str());
656     return NO_ERROR;
657 }
658 
659 } // namespace android
660