Add a keyboard key code generator. (#27620)
This adds a keycode generator that incorporates input from the Chromium and Android source trees, as well as some local tables, to generate static constants for the LogicalKeyboardKey and PhysicalKeyboardKey classes, as well as mappings from each of the platforms we support so far (currently only Android and Fuchsia). This code generator parses the input files, generates an intermediate data structure (`key_data.json`) that is checked in, and then generates the Dart sources for these classes and some static maps that will also be checked in (but are not included in this PR). The idea is that these codes don't change often, and so we don't need to generate them on every build, but we would like to be able to update them easily in the future if new data becomes available. If the existing data disappears or becomes unusable, we can maintain the checked-in data structure by hand if necessary, and still be able to generate the code. This PR only contains the code generator, not the classes themselves. In another follow-on PR, I'll run the generator and check in the output of the generator.
This commit is contained in:
195
dev/tools/gen_keycodes/lib/code_gen.dart
Normal file
195
dev/tools/gen_keycodes/lib/code_gen.dart
Normal file
@@ -0,0 +1,195 @@
|
||||
// Copyright 2019 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:io';
|
||||
import 'package:path/path.dart' as path;
|
||||
|
||||
import 'package:gen_keycodes/key_data.dart';
|
||||
import 'package:gen_keycodes/utils.dart';
|
||||
|
||||
/// Generates the keyboard_keys.dart and keyboard_maps.dart files, based on the
|
||||
/// information in the key data structure given to it.
|
||||
class CodeGenerator {
|
||||
CodeGenerator(this.keyData);
|
||||
|
||||
/// Given an [input] string, wraps the text at 80 characters and prepends each
|
||||
/// line with the [prefix] string. Use for generated comments.
|
||||
String wrapString(String input, String prefix) {
|
||||
final int wrapWidth = 80 - prefix.length;
|
||||
final StringBuffer result = StringBuffer();
|
||||
final List<String> words = input.split(RegExp(r'\s+'));
|
||||
String currentLine = words.removeAt(0);
|
||||
for (String word in words) {
|
||||
if ((currentLine.length + word.length) < wrapWidth) {
|
||||
currentLine += ' $word';
|
||||
} else {
|
||||
result.writeln('$prefix$currentLine');
|
||||
currentLine = '$word';
|
||||
}
|
||||
}
|
||||
if (currentLine.isNotEmpty) {
|
||||
result.writeln('$prefix$currentLine');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/// Gets the generated definitions of PhysicalKeyboardKeys.
|
||||
String get physicalDefinitions {
|
||||
final StringBuffer definitions = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
final String comment = wrapString('Represents the location of a '
|
||||
'"${entry.commentName}" key on a generalized keyboard. See the function '
|
||||
'[RawKeyEvent.physicalKey] for more information.', ' /// ');
|
||||
definitions.write('''
|
||||
|
||||
$comment static const PhysicalKeyboardKey ${entry.constantName} = PhysicalKeyboardKey(${toHex(entry.usbHidCode, digits: 8)}, debugName: kReleaseMode ? null : '${entry.commentName}');
|
||||
''');
|
||||
}
|
||||
return definitions.toString();
|
||||
}
|
||||
|
||||
/// Gets the generated definitions of LogicalKeyboardKeys.
|
||||
String get logicalDefinitions {
|
||||
String escapeLabel(String label) => label.contains("'") ? 'r"$label"' : "r'$label'";
|
||||
final StringBuffer definitions = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
final String comment = wrapString('Represents a logical "${entry.commentName}" key on the '
|
||||
'keyboard. See the function [RawKeyEvent.logicalKey] for more information.', ' /// ');
|
||||
if (entry.keyLabel == null) {
|
||||
definitions.write('''
|
||||
|
||||
$comment static const LogicalKeyboardKey ${entry.constantName} = LogicalKeyboardKey(${toHex(entry.flutterId, digits: 11)}, debugName: kReleaseMode ? null : '${entry.commentName}');
|
||||
''');
|
||||
} else {
|
||||
definitions.write('''
|
||||
|
||||
$comment static const LogicalKeyboardKey ${entry.constantName} = LogicalKeyboardKey(${toHex(entry.flutterId, digits: 11)}, keyLabel: ${escapeLabel(entry.keyLabel)}, debugName: kReleaseMode ? null : '${entry.commentName}');
|
||||
''');
|
||||
}
|
||||
}
|
||||
return definitions.toString();
|
||||
}
|
||||
|
||||
/// This generates the map of USB HID codes to physical keys.
|
||||
String get predefinedHidCodeMap {
|
||||
final StringBuffer scanCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
scanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: ${entry.constantName},');
|
||||
}
|
||||
return scanCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// THis generates the map of Flutter key codes to logical keys.
|
||||
String get predefinedKeyCodeMap {
|
||||
final StringBuffer keyCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
keyCodeMap.writeln(' ${toHex(entry.flutterId, digits: 10)}: ${entry.constantName},');
|
||||
}
|
||||
return keyCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// This generates the map of Android key codes to logical keys.
|
||||
String get androidKeyCodeMap {
|
||||
final StringBuffer androidKeyCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
if (entry.androidKeyCodes != null) {
|
||||
for (int code in entry.androidKeyCodes.cast<int>()) {
|
||||
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
|
||||
}
|
||||
}
|
||||
}
|
||||
return androidKeyCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// This generates the map of Android number pad key codes to logical keys.
|
||||
String get androidNumpadMap {
|
||||
final StringBuffer androidKeyCodeMap = StringBuffer();
|
||||
final List<Key> onlyNumpads = keyData.data.where((Key entry) {
|
||||
return entry.constantName.startsWith('numpad') && entry.keyLabel != null;
|
||||
}).toList();
|
||||
for (Key entry in onlyNumpads) {
|
||||
if (entry.androidKeyCodes != null) {
|
||||
for (int code in entry.androidKeyCodes.cast<int>()) {
|
||||
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
|
||||
}
|
||||
}
|
||||
}
|
||||
return androidKeyCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// This generates the map of Android scan codes to physical keys.
|
||||
String get androidScanCodeMap {
|
||||
final StringBuffer androidScanCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
if (entry.androidScanCodes != null) {
|
||||
for (int code in entry.androidScanCodes.cast<int>()) {
|
||||
androidScanCodeMap.writeln(' $code: PhysicalKeyboardKey.${entry.constantName},');
|
||||
}
|
||||
}
|
||||
}
|
||||
return androidScanCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// This generates the map of Fuchsia key codes to logical keys.
|
||||
String get fuchsiaKeyCodeMap {
|
||||
final StringBuffer fuchsiaKeyCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
if (entry.usbHidCode != null) {
|
||||
fuchsiaKeyCodeMap.writeln(' ${toHex(entry.flutterId)}: LogicalKeyboardKey.${entry.constantName},');
|
||||
}
|
||||
}
|
||||
return fuchsiaKeyCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// This generates the map of Fuchsia USB HID codes to physical keys.
|
||||
String get fuchsiaHidCodeMap {
|
||||
final StringBuffer fuchsiaScanCodeMap = StringBuffer();
|
||||
for (Key entry in keyData.data) {
|
||||
if (entry.usbHidCode != null) {
|
||||
fuchsiaScanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: PhysicalKeyboardKey.${entry.constantName},');
|
||||
}
|
||||
}
|
||||
return fuchsiaScanCodeMap.toString().trimRight();
|
||||
}
|
||||
|
||||
/// Substitutes the various maps and definitions into the template file for
|
||||
/// keyboard_key.dart.
|
||||
String generateKeyboardKeys() {
|
||||
final Map<String, String> mappings = <String, String>{
|
||||
'PHYSICAL_KEY_MAP': predefinedHidCodeMap,
|
||||
'LOGICAL_KEY_MAP': predefinedKeyCodeMap,
|
||||
'LOGICAL_KEY_DEFINITIONS': logicalDefinitions,
|
||||
'PHYSICAL_KEY_DEFINITIONS': physicalDefinitions,
|
||||
};
|
||||
|
||||
final String template = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_key.tmpl')).readAsStringSync();
|
||||
return _injectDictionary(template, mappings);
|
||||
}
|
||||
|
||||
/// Substitutes the various platform specific maps into the template file for
|
||||
/// keyboard_maps.dart.
|
||||
String generateKeyboardMaps() {
|
||||
final Map<String, String> mappings = <String, String>{
|
||||
'ANDROID_SCAN_CODE_MAP': androidScanCodeMap,
|
||||
'ANDROID_KEY_CODE_MAP': androidKeyCodeMap,
|
||||
'ANDROID_NUMPAD_MAP': androidNumpadMap,
|
||||
'FUCHSIA_SCAN_CODE_MAP': fuchsiaHidCodeMap,
|
||||
'FUCHSIA_KEY_CODE_MAP': fuchsiaKeyCodeMap,
|
||||
};
|
||||
|
||||
final String template = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_maps.tmpl')).readAsStringSync();
|
||||
return _injectDictionary(template, mappings);
|
||||
}
|
||||
|
||||
/// The database of keys loaded from disk.
|
||||
final KeyData keyData;
|
||||
|
||||
static String _injectDictionary(String template, Map<String, String> dictionary) {
|
||||
String result = template;
|
||||
for (String key in dictionary.keys) {
|
||||
result = result.replaceAll('@@@$key@@@', dictionary[key]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
365
dev/tools/gen_keycodes/lib/key_data.dart
Normal file
365
dev/tools/gen_keycodes/lib/key_data.dart
Normal file
@@ -0,0 +1,365 @@
|
||||
// Copyright 2019 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
import 'package:gen_keycodes/utils.dart';
|
||||
|
||||
/// The data structure used to manage keyboard key entries.
|
||||
///
|
||||
/// The main constructor parses the given input data into the data structure.
|
||||
///
|
||||
/// The data structure can be also loaded and saved to JSON, with the
|
||||
/// [KeyData.fromJson] constructor and [toJson] method, respectively.
|
||||
class KeyData {
|
||||
/// Parses the input data given in from the various data source files,
|
||||
/// populating the data structure.
|
||||
///
|
||||
/// None of the parameters may be null.
|
||||
KeyData(
|
||||
String chromiumHidCodes,
|
||||
String androidKeyboardLayout,
|
||||
String androidKeyCodeHeader,
|
||||
String androidNameMap,
|
||||
) : assert(chromiumHidCodes != null),
|
||||
assert(androidKeyboardLayout != null),
|
||||
assert(androidKeyCodeHeader != null),
|
||||
assert(androidNameMap != null) {
|
||||
_nameToAndroidScanCodes = _readAndroidScanCodes(androidKeyboardLayout);
|
||||
_nameToAndroidKeyCode = _readAndroidKeyCodes(androidKeyCodeHeader);
|
||||
final Map<String, List<dynamic>> dynamicNames = json.decode(androidNameMap).cast<String, List<dynamic>>();
|
||||
_nameToAndroidName = dynamicNames.map<String, List<String>>((String key, List<dynamic> value) {
|
||||
return MapEntry<String, List<String>>(key, value.cast<String>());
|
||||
});
|
||||
data = _readHidEntries(chromiumHidCodes);
|
||||
}
|
||||
|
||||
/// Parses the given JSON data and populates the data structure from it.
|
||||
KeyData.fromJson(Map<String, dynamic> contentMap) {
|
||||
data = <Key>[];
|
||||
for (String key in contentMap.keys) {
|
||||
data.add(Key.fromJsonMapEntry(key, contentMap[key]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts the data structure into a JSON structure that can be parsed by
|
||||
/// [KeyData.fromJson].
|
||||
Map<String, dynamic> toJson() {
|
||||
for (Key entry in data) {
|
||||
entry.androidKeyNames = _nameToAndroidName[entry.constantName]?.cast<String>();
|
||||
if (entry.androidKeyNames != null && entry.androidKeyNames.isNotEmpty) {
|
||||
for (String androidKeyName in entry.androidKeyNames) {
|
||||
if (_nameToAndroidKeyCode[androidKeyName] != null) {
|
||||
entry.androidKeyCodes ??= <int>[];
|
||||
entry.androidKeyCodes.add(_nameToAndroidKeyCode[androidKeyName]);
|
||||
}
|
||||
if (_nameToAndroidScanCodes[androidKeyName] != null && _nameToAndroidScanCodes[androidKeyName].isNotEmpty) {
|
||||
entry.androidScanCodes ??= <int>[];
|
||||
entry.androidScanCodes.addAll(_nameToAndroidScanCodes[androidKeyName]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final Map<String, dynamic> outputMap = <String, dynamic>{};
|
||||
for (Key entry in data) {
|
||||
outputMap[entry.constantName] = entry.toJson();
|
||||
}
|
||||
return outputMap;
|
||||
}
|
||||
|
||||
/// The list of keys.
|
||||
List<Key> data;
|
||||
|
||||
/// The mapping from the Flutter name (e.g. "eject") to the Android name (e.g.
|
||||
/// "MEDIA_EJECT").
|
||||
///
|
||||
/// Only populated if data is parsed from the source files, not if parsed from
|
||||
/// JSON.
|
||||
Map<String, List<String>> _nameToAndroidName;
|
||||
|
||||
/// The mapping from the Android name (e.g. "MEDIA_EJECT") to the integer scan
|
||||
/// code (physical location) of the key.
|
||||
///
|
||||
/// Only populated if data is parsed from the source files, not if parsed from
|
||||
/// JSON.
|
||||
Map<String, List<int>> _nameToAndroidScanCodes;
|
||||
|
||||
/// The mapping from Android name (e.g. "MEDIA_EJECT") to the integer key code
|
||||
/// (logical meaning) of the key.
|
||||
///
|
||||
/// Only populated if data is parsed from the source files, not if parsed from
|
||||
/// JSON.
|
||||
Map<String, int> _nameToAndroidKeyCode;
|
||||
|
||||
/// Parses entries from Androids Generic.kl scan code data file.
|
||||
///
|
||||
/// Lines in this file look like this (without the ///):
|
||||
/// key 100 ALT_RIGHT
|
||||
/// # key 101 "KEY_LINEFEED"
|
||||
///
|
||||
/// We parse the commented out lines as well as the non-commented lines, so so
|
||||
/// that we can get names for all of the available scan codes, not just ones
|
||||
/// defined for the generic profile.
|
||||
///
|
||||
/// Also, note that some keys (notably MEDIA_EJECT) can be mapped to more than
|
||||
/// one scan code, so the mapping can't just be 1:1, it has to be 1:many.
|
||||
Map<String, List<int>> _readAndroidScanCodes(String keyboardLayout) {
|
||||
final RegExp keyEntry = RegExp(r'''#?\s*key\s+([0-9]+)\s*"?(?:KEY_)?([0-9A-Z_]+|\(undefined\))"?\s*(FUNCTION)?''');
|
||||
final Map<String, List<int>> result = <String, List<int>>{};
|
||||
keyboardLayout.replaceAllMapped(keyEntry, (Match match) {
|
||||
if (match.group(3) == 'FUNCTION') {
|
||||
// Skip odd duplicate Android FUNCTION keys (F1-F12 are already defined).
|
||||
return '';
|
||||
}
|
||||
final String name = match.group(2);
|
||||
if (name == '(undefined)') {
|
||||
// Skip undefined scan codes.
|
||||
return '';
|
||||
}
|
||||
final String androidName = match.group(2);
|
||||
result[androidName] ??= <int>[];
|
||||
result[androidName].add(int.parse(match.group(1)));
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses entries from Android's keycodes.h key code data file.
|
||||
///
|
||||
/// Lines in this file look like this (without the ///):
|
||||
/// /** Left Control modifier key. */
|
||||
/// AKEYCODE_CTRL_LEFT = 113,
|
||||
Map<String, int> _readAndroidKeyCodes(String headerFile) {
|
||||
final RegExp enumBlock = RegExp(r'enum\s*\{(.*)\};', multiLine: true);
|
||||
// Eliminate everything outside of the enum block.
|
||||
headerFile = headerFile.replaceAllMapped(enumBlock, (Match match) => match.group(1));
|
||||
final RegExp enumEntry = RegExp(r'''AKEYCODE_([A-Z0-9_]+)\s*=\s*([0-9]+),?''');
|
||||
final Map<String, int> result = <String, int>{};
|
||||
headerFile.replaceAllMapped(enumEntry, (Match match) {
|
||||
result[match.group(1)] = int.parse(match.group(2));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Parses entries from Chromium's HID code mapping header file.
|
||||
///
|
||||
/// Lines in this file look like this (without the ///):
|
||||
/// USB evdev XKB Win Mac Code Enum
|
||||
/// USB_KEYMAP(0x000010, 0x0000, 0x0000, 0x0000, 0xffff, "Hyper", HYPER),
|
||||
List<Key> _readHidEntries(String input) {
|
||||
final List<Key> entries = <Key>[];
|
||||
final RegExp usbMapRegExp = RegExp(
|
||||
r'''USB_KEYMAP\s*\(\s*0x([a-fA-F0-9]+),\s*0x([a-fA-F0-9]+),'''
|
||||
r'''\s*0x([a-fA-F0-9]+),\s*0x([a-fA-F0-9]+),\s*0x([a-fA-F0-9]+),\s*"?([^\s]+?)"?,\s*([^\s]+?)\s*\)''',
|
||||
multiLine: true);
|
||||
final RegExp commentRegExp = RegExp(r'//.*$', multiLine: true);
|
||||
input = input.replaceAll(commentRegExp, '');
|
||||
input.replaceAllMapped(usbMapRegExp, (Match match) {
|
||||
if (match != null) {
|
||||
final int macScanCode = getHex(match.group(5));
|
||||
final int linuxScanCode = getHex(match.group(2));
|
||||
final int xKbScanCode = getHex(match.group(3));
|
||||
final int windowsScanCode = getHex(match.group(4));
|
||||
final Key newEntry = Key(
|
||||
usbHidCode: getHex(match.group(1)),
|
||||
linuxScanCode: linuxScanCode == 0 ? null : linuxScanCode,
|
||||
xKbScanCode: xKbScanCode == 0 ? null : xKbScanCode,
|
||||
windowsScanCode: windowsScanCode == 0 ? null : windowsScanCode,
|
||||
macOsScanCode: macScanCode == 0xffff ? null : macScanCode,
|
||||
name: match.group(6) == 'NULL' ? null : match.group(6),
|
||||
// The input data has a typo...
|
||||
chromiumName: shoutingToLowerCamel(match.group(7)).replaceAll('Minimium', 'Minimum'),
|
||||
);
|
||||
if (newEntry.chromiumName == 'none') {
|
||||
newEntry.name = 'None';
|
||||
}
|
||||
if (newEntry.name == 'IntlHash') {
|
||||
// Skip key that is not actually generated by any keyboard.
|
||||
return '';
|
||||
}
|
||||
entries.add(newEntry);
|
||||
}
|
||||
return match.group(0);
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
}
|
||||
|
||||
/// A single entry in the key data structure.
|
||||
///
|
||||
/// Can be read from JSON with the [Key..fromJsonMapEntry] constructor, or
|
||||
/// written with the [toJson] method.
|
||||
class Key {
|
||||
/// Creates a single key entry from available data.
|
||||
///
|
||||
/// The [usbHidCode] and [chromiumName] parameters must not be null.
|
||||
Key({
|
||||
String enumName,
|
||||
this.name,
|
||||
@required this.usbHidCode,
|
||||
this.linuxScanCode,
|
||||
this.xKbScanCode,
|
||||
this.windowsScanCode,
|
||||
this.macOsScanCode,
|
||||
@required this.chromiumName,
|
||||
this.androidKeyNames,
|
||||
this.androidScanCodes,
|
||||
this.androidKeyCodes,
|
||||
}) : assert(usbHidCode != null),
|
||||
assert(chromiumName != null),
|
||||
_constantName = enumName;
|
||||
|
||||
/// Populates the key from a JSON map.
|
||||
factory Key.fromJsonMapEntry(String name, Map<String, dynamic> map) {
|
||||
return Key(
|
||||
enumName: name,
|
||||
name: map['names']['domkey'],
|
||||
chromiumName: map['names']['chromium'],
|
||||
usbHidCode: map['scanCodes']['usb'],
|
||||
androidKeyNames: map['names']['android']?.cast<String>(),
|
||||
androidScanCodes: map['scanCodes']['android']?.cast<int>(),
|
||||
androidKeyCodes: map['keyCodes']['android']?.cast<int>(),
|
||||
linuxScanCode: map['scanCodes']['linux'],
|
||||
xKbScanCode: map['scanCodes']['xkb'],
|
||||
windowsScanCode: map['scanCodes']['windows'],
|
||||
macOsScanCode: map['scanCodes']['macos'],
|
||||
);
|
||||
}
|
||||
|
||||
/// The USB HID code of the key
|
||||
int usbHidCode;
|
||||
|
||||
/// The Linux scan code of the key, from Chromium's header file.
|
||||
int linuxScanCode;
|
||||
/// The XKb scan code of the key from Chromium's header file.
|
||||
int xKbScanCode;
|
||||
/// The Windows scan code of the key from Chromium's header file.
|
||||
int windowsScanCode;
|
||||
/// The macOS scan code of the key from Chromium's header file.
|
||||
int macOsScanCode;
|
||||
/// The name of the key, mostly derived from the DomKey name in Chromium,
|
||||
/// but where there was no DomKey representation, derived from the Chromium
|
||||
/// symbol name.
|
||||
String name;
|
||||
/// The Chromium symbol name for the key.
|
||||
String chromiumName;
|
||||
/// The list of names that Android gives to this key (symbol names minus the
|
||||
/// prefix).
|
||||
List<String> androidKeyNames;
|
||||
/// The list of Android key codes matching this key, created by looking up the
|
||||
/// Android name in the Chromium data, and substituting the Android key code
|
||||
/// value.
|
||||
List<int> androidKeyCodes;
|
||||
/// The list of Android scan codes matching this key, created by looking up
|
||||
/// the Android name in the Chromium data, and substituting the Android scan
|
||||
/// code value.
|
||||
List<int> androidScanCodes;
|
||||
|
||||
/// Creates a JSON map from the key data.
|
||||
Map<String, dynamic> toJson() {
|
||||
return <String, dynamic>{
|
||||
'names': <String, dynamic>{
|
||||
'domkey': name,
|
||||
'android': androidKeyNames,
|
||||
'english': commentName,
|
||||
'chromium': chromiumName,
|
||||
},
|
||||
'scanCodes': <String, dynamic>{
|
||||
'android': androidScanCodes,
|
||||
'usb': usbHidCode,
|
||||
'linux': linuxScanCode,
|
||||
'xkb': xKbScanCode,
|
||||
'windows': windowsScanCode,
|
||||
'macos': macOsScanCode,
|
||||
},
|
||||
'keyCodes': <String, List<int>>{
|
||||
'android': androidKeyCodes,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the printable representation of this key, if any.
|
||||
///
|
||||
/// If there is no printable representation, returns null.
|
||||
String get keyLabel => printable[constantName];
|
||||
|
||||
int get flutterId {
|
||||
if (printable.containsKey(constantName) && !constantName.startsWith('numpad')) {
|
||||
return unicodePlane | (keyLabel.codeUnitAt(0) & valueMask);
|
||||
}
|
||||
return hidPlane | (usbHidCode & valueMask);
|
||||
}
|
||||
|
||||
/// Gets the name of the key suitable for placing in comments.
|
||||
///
|
||||
/// Takes the [constantName] and converts it from lower camel case to capitalized
|
||||
/// separate words (e.g. "wakeUp" converts to "Wake Up").
|
||||
String get commentName {
|
||||
String upperCamel = lowerCamelToUpperCamel(constantName);
|
||||
upperCamel = upperCamel.replaceAllMapped(RegExp(r'(Digit|Numpad|Lang)([0-9]+)'), (Match match) => '${match.group(1)} ${match.group(2)}');
|
||||
return upperCamel.replaceAllMapped(RegExp(r'([A-Z])'), (Match match) => ' ${match.group(1)}').trim();
|
||||
}
|
||||
|
||||
/// Gets the named used for the key constant in the definitions in
|
||||
/// keyboard_keys.dart.
|
||||
///
|
||||
/// If set by the constructor, returns the name set, but otherwise constructs
|
||||
/// the name from the various different names available, making sure that the
|
||||
/// name isn't a Dart reserved word (if it is, then it adds the word "Key" to
|
||||
/// the end of the name).
|
||||
String get constantName {
|
||||
if (_constantName == null) {
|
||||
String result;
|
||||
if (name == null || name.isEmpty) {
|
||||
// If it doesn't have a DomKey name then use the Chromium symbol name.
|
||||
result = chromiumName;
|
||||
} else {
|
||||
result = upperCamelToLowerCamel(name);
|
||||
}
|
||||
if (kDartReservedWords.contains(result)) {
|
||||
return '${result}Key';
|
||||
}
|
||||
// Don't set enumName: we want it to regen each time if never set, but
|
||||
// to stay set if set by the JSON loading.
|
||||
return result;
|
||||
}
|
||||
return _constantName;
|
||||
}
|
||||
set constantName(String value) => _constantName = value;
|
||||
String _constantName;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return """'$constantName': (name: "$name", usbHidCode: ${toHex(usbHidCode)}, """
|
||||
'''linuxKeyCode: ${toHex(linuxScanCode)}, xKbKeyCode: ${toHex(xKbScanCode)}, '''
|
||||
'''windowsKeyCode: ${toHex(windowsScanCode)}, macOsKeyCode: ${toHex(macOsScanCode)}, '''
|
||||
'''chromiumSymbolName: $chromiumName''';
|
||||
}
|
||||
|
||||
/// Returns the static map of printable representations.
|
||||
static Map<String, String> get printable {
|
||||
if (_printable == null) {
|
||||
final String printableKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'printable.json',)).readAsStringSync();
|
||||
final Map<String, dynamic> printable = json.decode(printableKeys);
|
||||
_printable = printable.cast<String, String>();
|
||||
}
|
||||
return _printable;
|
||||
}
|
||||
static Map<String, String> _printable;
|
||||
|
||||
/// Mask for the 32-bit value portion of the code.
|
||||
static const int valueMask = 0x000FFFFFFFF;
|
||||
|
||||
/// The code prefix for keys which have a Unicode representation.
|
||||
static const int unicodePlane = 0x00000000000;
|
||||
|
||||
/// The code prefix for keys which do not have a Unicode representation, but
|
||||
/// do have a USB HID ID.
|
||||
static const int hidPlane = 0x00100000000;
|
||||
}
|
||||
111
dev/tools/gen_keycodes/lib/utils.dart
Normal file
111
dev/tools/gen_keycodes/lib/utils.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
// Copyright 2019 The Chromium Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:io' hide Platform;
|
||||
|
||||
import 'package:path/path.dart' as path;
|
||||
import 'package:platform/platform.dart' show LocalPlatform;
|
||||
|
||||
/// The location of the Flutter root directory, based on the known location of
|
||||
/// this script.
|
||||
final Directory flutterRoot = Directory(path.dirname(const LocalPlatform().script.toFilePath())).parent.parent.parent.parent;
|
||||
|
||||
/// Converts `FOO_BAR` to `fooBar`.
|
||||
String shoutingToLowerCamel(String shouting) {
|
||||
final RegExp initialLetter = RegExp(r'_([^_])([^_]*)');
|
||||
final String snake = shouting.toLowerCase();
|
||||
final String result = snake.replaceAllMapped(initialLetter, (Match match) {
|
||||
return match.group(1).toUpperCase() + match.group(2).toLowerCase();
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Converts 'FooBar' to 'fooBar'.
|
||||
String upperCamelToLowerCamel(String upperCamel) {
|
||||
return upperCamel.substring(0, 1).toLowerCase() + upperCamel.substring(1);
|
||||
}
|
||||
|
||||
/// Converts 'fooBar' to 'FooBar'.
|
||||
String lowerCamelToUpperCamel(String lowerCamel) {
|
||||
return lowerCamel.substring(0, 1).toUpperCase() + lowerCamel.substring(1);
|
||||
}
|
||||
|
||||
/// A list of Dart reserved words.
|
||||
///
|
||||
/// Since these are Dart reserved words, we can't use them as-is for enum names.
|
||||
const List<String> kDartReservedWords = <String>[
|
||||
'abstract',
|
||||
'as',
|
||||
'assert',
|
||||
'async',
|
||||
'await',
|
||||
'break',
|
||||
'case',
|
||||
'catch',
|
||||
'class',
|
||||
'const',
|
||||
'continue',
|
||||
'covariant',
|
||||
'default',
|
||||
'deferred',
|
||||
'do',
|
||||
'dynamic',
|
||||
'else',
|
||||
'enum',
|
||||
'export',
|
||||
'extends',
|
||||
'external',
|
||||
'factory',
|
||||
'false',
|
||||
'final',
|
||||
'finally',
|
||||
'for',
|
||||
'Function',
|
||||
'get',
|
||||
'hide',
|
||||
'if',
|
||||
'implements',
|
||||
'import',
|
||||
'in',
|
||||
'interface',
|
||||
'is',
|
||||
'library',
|
||||
'mixin',
|
||||
'new',
|
||||
'null',
|
||||
'on',
|
||||
'operator',
|
||||
'part',
|
||||
'rethrow',
|
||||
'return',
|
||||
'set',
|
||||
'show',
|
||||
'static',
|
||||
'super',
|
||||
'switch',
|
||||
'sync',
|
||||
'this',
|
||||
'throw',
|
||||
'true',
|
||||
'try',
|
||||
'typedef',
|
||||
'var',
|
||||
'void',
|
||||
'while',
|
||||
'with',
|
||||
'yield',
|
||||
];
|
||||
|
||||
/// Converts an integer into a hex string with the given number of digits.
|
||||
String toHex(int value, {int digits = 8}) {
|
||||
if (value == null) {
|
||||
return 'null';
|
||||
}
|
||||
return '0x${value.toRadixString(16).padLeft(digits, '0')}';
|
||||
}
|
||||
|
||||
/// Parses an integer from a hex string.
|
||||
int getHex(String input) {
|
||||
return int.parse(input, radix: 16);
|
||||
}
|
||||
Reference in New Issue
Block a user