Hardware keyboard: codegen (#73440)

Rewrites tools/gen_keycodes, the script that generates key mappings across the framework and the engine.
This commit is contained in:
Tong Mu
2021-04-30 21:06:03 -07:00
committed by GitHub
parent 0cb0767bd7
commit 9956a35a5a
65 changed files with 23391 additions and 14836 deletions

View File

@@ -5,36 +5,23 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// Generates the key mapping of Android, based on the information in the key
/// Generates the key mapping for Android, based on the information in the key
/// data structure given to it.
class AndroidCodeGenerator extends PlatformCodeGenerator {
AndroidCodeGenerator(KeyData keyData) : super(keyData);
AndroidCodeGenerator(PhysicalKeyData physicalData, LogicalKeyData logicalData)
: super(physicalData, logicalData);
/// This generates the map of Android key codes to logical keys.
String get _androidKeyCodeMap {
final StringBuffer androidKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.androidKeyCodes != null) {
for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' { $code, ${toHex(entry.flutterId, digits: 10)} }, // ${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();
for (final Key entry in numpadKeyData) {
if (entry.androidKeyCodes != null) {
for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' { $code, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.androidValues) {
androidKeyCodeMap.writeln(' put(${toHex(code, digits: 10)}L, ${toHex(entry.value, digits: 10)}L); // ${entry.constantName}');
}
}
return androidKeyCodeMap.toString().trimRight();
@@ -43,10 +30,10 @@ class AndroidCodeGenerator extends PlatformCodeGenerator {
/// This generates the map of Android scan codes to physical keys.
String get _androidScanCodeMap {
final StringBuffer androidScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.androidScanCodes != null) {
for (final int code in entry.androidScanCodes.cast<int>()) {
androidScanCodeMap.writeln(' { $code, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
androidScanCodeMap.writeln(' put(${toHex(code, digits: 10)}L, ${toHex(entry.usbHidCode, digits: 10)}L); // ${entry.constantName}');
}
}
}
@@ -54,14 +41,17 @@ class AndroidCodeGenerator extends PlatformCodeGenerator {
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_android_cc.tmpl');
String get templatePath => path.join(dataRoot, 'android_keyboard_map_java.tmpl');
@override
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot, 'shell', 'platform',
path.join('android', 'io', 'flutter', 'embedding', 'android', 'KeyboardMap.java'));
@override
Map<String, String> mappings() {
return <String, String>{
'ANDROID_SCAN_CODE_MAP': _androidScanCodeMap,
'ANDROID_KEY_CODE_MAP': _androidKeyCodeMap,
'ANDROID_NUMPAD_MAP': _androidNumpadMap,
};
}
}

View File

@@ -3,15 +3,14 @@
// found in the LICENSE file.
import 'dart:io';
import 'package:path/path.dart' as path;
import 'package:gen_keycodes/logical_key_data.dart';
import 'key_data.dart';
import 'utils.dart';
import 'physical_key_data.dart';
String _injectDictionary(String template, Map<String, String> dictionary) {
String result = template;
for (final String key in dictionary.keys) {
result = result.replaceAll('@@@$key@@@', dictionary[key]);
result = result.replaceAll('@@@$key@@@', dictionary[key] ?? '@@@$key@@@');
}
return result;
}
@@ -26,7 +25,7 @@ String _injectDictionary(String template, Map<String, String> dictionary) {
/// Subclasses must implement [templatePath] and [mappings].
abstract class BaseCodeGenerator {
/// Create a code generator while providing [keyData] to be used in [mappings].
BaseCodeGenerator(this.keyData);
BaseCodeGenerator(this.keyData, this.logicalData);
/// Absolute path to the template file that this file is generated on.
String get templatePath;
@@ -42,30 +41,20 @@ abstract class BaseCodeGenerator {
}
/// The database of keys loaded from disk.
final KeyData keyData;
final PhysicalKeyData keyData;
final LogicalKeyData logicalData;
}
/// A code generator which also defines platform-based behavior.
abstract class PlatformCodeGenerator extends BaseCodeGenerator {
PlatformCodeGenerator(KeyData keyData) : super(keyData);
// Used by platform code generators.
List<Key> get numpadKeyData {
return keyData.data.where((Key entry) {
return entry.constantName.startsWith('numpad') && entry.keyLabel != null;
}).toList();
}
// Used by platform code generators.
List<Key> get functionKeyData {
final RegExp functionKeyRe = RegExp(r'^f[0-9]+$');
return keyData.data.where((Key entry) {
return functionKeyRe.hasMatch(entry.constantName);
}).toList();
}
PlatformCodeGenerator(PhysicalKeyData keyData, LogicalKeyData logicalData)
: super(keyData, logicalData);
/// Absolute path to the output file.
///
/// How this value will be used is based on the callee.
String outputPath(String platform) => path.join(flutterRoot.path, '..', path.join('engine', 'src', 'flutter', 'shell', 'platform', platform, 'keycodes', 'keyboard_map_$platform.h'));
String outputPath(String platform);
static String engineRoot = '';
}

View File

@@ -0,0 +1,148 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/* === LOGICAL KEY BITMASKS === */
// The following constants are used to composite the value for a Flutter logical
// key.
//
// A Flutter logical key supports up to 53-bits, as limited by JavaScript
// integers.
/* Bit 31-0: Value */
// The lower 32 bits represent different values within a plane.
/// Mask for the 32-bit value portion of the code.
const int kValueMask = 0x000FFFFFFFF;
/* Bit 39-32: Source of value */
// The next 8 bits represent where the values come from, consequently how to
// interpret them.
/// Mask for bit #39-32 portion of the code, indicating the source of the value.
const int kPlatformMask = 0x0FF00000000;
/// The code prefix for keys that have a Unicode representation, generated from
/// their code points.
///
/// See also:
///
/// * [kUnprintablePlane], for keys that are also generated from code points but
/// unprintable.
const int kUnicodePlane = 0x00000000000;
/// The code prefix for keys generated from their USB HID usages.
const int kHidPlane = 0x00100000000;
/// The code prefix for unrecognized keys that are unique to Android, generated
/// from platform-specific codes.
const int kAndroidPlane = 0x00200000000;
/// The code prefix for unrecognized keys that are unique to Fuchsia, generated
/// from platform-specific codes.
const int kFuchsiaPlane = 0x00300000000;
/// The code prefix for unrecognized keys that are unique to iOS, generated
/// from platform-specific codes.
const int kIosPlane = 0x00400000000;
/// The code prefix for unrecognized keys that are unique to macOS, generated
/// from platform-specific codes.
const int kMacOsPlane = 0x00500000000;
/// The code prefix for unrecognized keys that are unique to Gtk, generated from
/// platform-specific codes.
const int kGtkPlane = 0x00600000000;
/// The code prefix for unrecognized keys that are unique to Windows, generated
/// from platform-specific codes.
const int kWindowsPlane = 0x00700000000;
/// The code prefix for unrecognized keys that are unique to Web, generated from
/// platform-specific codes.
const int kWebPlane = 0x00800000000;
/// The code prefix for keys that do not have a Unicode representation, generated
/// from their code points.
///
/// See also:
///
/// * [kUnicodePlane], for keys that are also generated from code points but
/// printable.
const int kUnprintablePlane = 0x01000000000;
/* Bit 43-40: Key variation */
// The next 4 bits represent keys that have multiple variations, such as a left
// and right variation of a modifier key, or a Numpad variation of a digit key.
/// Mask for bit #43-40 portion of the code, indicating the variation of the key.
const int kVariationMask = 0xF0000000000;
/// The code prefix for pseudo-keys which represent collections of key synonyms,
/// such as Control.
const int kSynonymPlane = 0x20000000000;
/// The code prefix for the left modifier of a pair of modifiers, such as Control
/// Left.
const int kLeftModifierPlane = 0x30000000000;
/// The code prefix for the right modifier of a pair of modifiers, such as Control
/// Right.
const int kRightModifierPlane = 0x40000000000;
/// The code prefix for a Numpad key, such as Numpad 1.
const int kNumpadPlane = 0x50000000000;
class MaskConstant {
const MaskConstant({required this.name, required this.value, required this.description});
final String name;
final int value;
final List<String> description;
}
const List<MaskConstant> maskConstants = <MaskConstant>[
MaskConstant(
name: 'valueMask',
value: kValueMask,
description: <String>[
'Mask for the 32-bit value portion of the key code.',
'This is used by platform-specific code to generate Flutter key codes.',
],
),
MaskConstant(
name: 'platformMask',
value: kPlatformMask,
description: <String>[
'Mask for the platform prefix portion of the key code.',
'This is used by platform-specific code to generate Flutter key codes.'
],
),
MaskConstant(
name: 'unicodePlane',
value: kUnicodePlane,
description: <String>[
'The code prefix for keys which have a Unicode representation.',
'This is used by platform-specific code to generate Flutter key codes.'
],
),
MaskConstant(
name: 'synonymMask',
value: kSynonymPlane,
description: <String>[
'Mask for the synonym pseudo-keys generated for keys which appear in more than one place on the keyboard.',
'IDs in this range are used to represent keys which appear in multiple places on the keyboard, such as the SHIFT, ALT, CTRL, and numeric keypad keys. These key codes will never be generated by the key event system, but may be used in key maps to represent the union of all the keys of each type in order to match them.',
'To look up the synonyms that are defined, look in the [synonyms] map.'
],
),
MaskConstant(
name: 'hidPlane',
value: kHidPlane,
description: <String>[
'The code prefix for keys which do not have a Unicode representation.',
'This is used by platform-specific code to generate Flutter key codes using HID Usage codes.'
],
),
];

View File

@@ -1,49 +0,0 @@
// Copyright 2014 The Flutter 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 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'utils.dart';
/// Generates the key mapping of Fuchsia, based on the information in the key
/// data structure given to it.
class FuchsiaCodeGenerator extends PlatformCodeGenerator {
FuchsiaCodeGenerator(KeyData keyData) : super(keyData);
/// This generates the map of Fuchsia key codes to logical keys.
String get _fuchsiaKeyCodeMap {
final StringBuffer fuchsiaKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.usbHidCode != null) {
fuchsiaKeyCodeMap.writeln(' { ${toHex(entry.flutterId)}, ${toHex(entry.flutterId, digits: 10)} }, // ${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 (final Key entry in keyData.data) {
if (entry.usbHidCode != null) {
fuchsiaScanCodeMap.writeln(' { ${toHex(entry.usbHidCode)}, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
}
}
return fuchsiaScanCodeMap.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_fuchsia_cc.tmpl');
@override
Map<String, String> mappings() {
return <String, String>{
'FUCHSIA_SCAN_CODE_MAP': _fuchsiaHidCodeMap,
'FUCHSIA_KEY_CODE_MAP': _fuchsiaKeyCodeMap,
};
}
}

View File

@@ -1,53 +0,0 @@
// Copyright 2014 The Flutter 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 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'utils.dart';
/// Generates the key mapping of GLFW, based on the information in the key
/// data structure given to it.
class GlfwCodeGenerator extends PlatformCodeGenerator {
GlfwCodeGenerator(KeyData keyData) : super(keyData);
/// This generates the map of GLFW number pad key codes to logical keys.
String get _glfwNumpadMap {
final StringBuffer glfwNumpadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.glfwKeyCodes != null) {
for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwNumpadMap.writeln(' { $code, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
}
}
return glfwNumpadMap.toString().trimRight();
}
/// This generates the map of GLFW key codes to logical keys.
String get _glfwKeyCodeMap {
final StringBuffer glfwKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.glfwKeyCodes != null) {
for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwKeyCodeMap.writeln(' { $code, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
}
}
return glfwKeyCodeMap.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_glfw_cc.tmpl');
@override
Map<String, String> mappings() {
return <String, String>{
'GLFW_KEY_CODE_MAP': _glfwKeyCodeMap,
'GLFW_NUMPAD_MAP': _glfwNumpadMap,
};
}
}

View File

@@ -5,33 +5,104 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// Generates the key mapping of GTK, based on the information in the key
/// Generates the key mapping for GTK, based on the information in the key
/// data structure given to it.
class GtkCodeGenerator extends PlatformCodeGenerator {
GtkCodeGenerator(KeyData keyData) : super(keyData);
GtkCodeGenerator(
PhysicalKeyData keyData,
LogicalKeyData logicalData,
String modifierBitMapping,
String lockBitMapping,
) : _modifierBitMapping = parseMapOfListOfString(modifierBitMapping),
_lockBitMapping = parseMapOfListOfString(lockBitMapping),
super(keyData, logicalData);
/// This generates the map of XKB scan codes to USB HID codes.
String get xkbScanCodeMap {
final StringBuffer xkbScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
/// This generates the map of XKB scan codes to Flutter physical keys.
String get _xkbScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.xKbScanCode != null) {
xkbScanCodeMap.writeln(' { ${toHex(entry.xKbScanCode)}, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
lines.add(entry.xKbScanCode!, ' insert_record(table, ${toHex(entry.xKbScanCode)}, ${toHex(entry.usbHidCode)}); // ${entry.constantName}');
}
}
return xkbScanCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of GTK keyval codes to Flutter logical keys.
String get _gtkKeyvalCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK keyval map');
for (final LogicalKeyEntry entry in logicalData.entries) {
zipStrict(entry.gtkValues, entry.gtkNames, (int value, String name) {
lines.add(value, ' insert_record(table, ${toHex(value)}, ${toHex(entry.value, digits: 11)}); // $name');
});
}
return lines.sortedJoin().trimRight();
}
static String constructMapFromModToKeys(
Map<String, List<String>> source,
PhysicalKeyData physicalData,
LogicalKeyData logicalData,
String debugFunctionName,
) {
final StringBuffer result = StringBuffer();
source.forEach((String modifierBitName, List<String> keyNames) {
assert(keyNames.length == 2 || keyNames.length == 3);
final String primaryLogicalName = keyNames[0];
final String primaryPhysicalName = keyNames[1];
final String? secondaryPhysicalName = keyNames.length == 3 ? keyNames[2] : null;
final LogicalKeyEntry primaryLogical = logicalData.entryByName(primaryLogicalName);
final PhysicalKeyEntry primaryPhysical = physicalData.entryByName(primaryPhysicalName);
final PhysicalKeyEntry? secondaryPhysical = secondaryPhysicalName == null ? null : physicalData.entryByName(secondaryPhysicalName);
if (secondaryPhysical == null && secondaryPhysicalName != null) {
print('Unrecognized secondary physical key $secondaryPhysicalName specified for $debugFunctionName.');
return;
}
final String pad = secondaryPhysical == null ? '' : ' ';
result.writeln('''
data = g_new(FlKeyEmbedderCheckedKey, 1);
g_hash_table_insert(table, GUINT_TO_POINTER(GDK_${modifierBitName}_MASK), data);
data->is_caps_lock = ${primaryPhysicalName == 'CapsLock' ? 'true' : 'false'};
data->primary_logical_key = ${toHex(primaryLogical.value, digits: 11)};$pad // ${primaryLogical.constantName}
data->primary_physical_key = ${toHex(primaryPhysical.usbHidCode, digits: 9)};$pad // ${primaryPhysical.constantName}''');
if (secondaryPhysical != null) {
result.writeln('''
data->secondary_physical_key = ${toHex(secondaryPhysical.usbHidCode, digits: 9)}; // ${secondaryPhysical.constantName}''');
}
});
return result.toString().trimRight();
}
String get _gtkModifierBitMap {
return constructMapFromModToKeys(_modifierBitMapping, keyData, logicalData, 'gtkModifierBitMap');
}
final Map<String, List<String>> _modifierBitMapping;
String get _gtkModeBitMap {
return constructMapFromModToKeys(_lockBitMapping, keyData, logicalData, 'gtkModeBitMap');
}
final Map<String, List<String>> _lockBitMapping;
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_linux_cc.tmpl');
String get templatePath => path.join(dataRoot, 'gtk_key_mapping_cc.tmpl');
@override
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot,
'shell', 'platform', 'linux', 'key_mapping.cc');
@override
Map<String, String> mappings() {
return <String, String>{
'XKB_SCAN_CODE_MAP': xkbScanCodeMap,
'XKB_SCAN_CODE_MAP': _xkbScanCodeMap,
'GTK_KEYVAL_CODE_MAP': _gtkKeyvalCodeMap,
'GTK_MODIFIER_BIT_MAP': _gtkModifierBitMap,
'GTK_MODE_BIT_MAP': _gtkModeBitMap,
};
}
}

View File

@@ -1,54 +0,0 @@
// Copyright 2014 The Flutter 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 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'utils.dart';
/// Generates the key mapping of iOS, based on the information in the key
/// data structure given to it.
class IosCodeGenerator extends PlatformCodeGenerator {
IosCodeGenerator(KeyData keyData) : super(keyData);
/// This generates the map of iOS key codes to physical keys.
String get _iosScanCodeMap {
final StringBuffer iosScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.iosScanCode != null) {
iosScanCodeMap.writeln(' { ${toHex(entry.iosScanCode)}, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
}
}
return iosScanCodeMap.toString().trimRight();
}
/// This generates the map of iOS number pad key codes to logical keys.
String get _iosNumpadMap {
final StringBuffer iosNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.iosScanCode != null) {
iosNumPadMap.writeln(' { ${toHex(entry.iosScanCode)}, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
}
return iosNumPadMap.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_ios_cc.tmpl');
@override
String outputPath(String platform) => path.joinAll(<String>[flutterRoot.path, '..', 'engine', 'src', 'flutter', 'shell', 'platform', 'darwin', platform, 'keycodes', 'keyboard_map_$platform.h']);
@override
Map<String, String> mappings() {
// There is no iOS keycode map since iOS uses keycode to represent a physical key.
// The LogicalKeyboardKey is generated by raw_keyboard_macos.dart from the unmodified characters
// from NSEvent.
return <String, String>{
'IOS_SCAN_CODE_MAP': _iosScanCodeMap,
'IOS_NUMPAD_MAP': _iosNumpadMap
};
}
}

View File

@@ -1,601 +0,0 @@
// Copyright 2014 The Flutter 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:gen_keycodes/utils.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as path;
/// 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,
String glfwKeyCodeHeader,
String glfwNameMap,
String gtkKeyCodeHeader,
String gtkNameMap,
String windowsKeyCodeHeader,
String windowsNameMap,
) : assert(chromiumHidCodes != null),
assert(androidKeyboardLayout != null),
assert(androidKeyCodeHeader != null),
assert(androidNameMap != null),
assert(glfwKeyCodeHeader != null),
assert(glfwNameMap != null),
assert(gtkKeyCodeHeader != null),
assert(gtkNameMap != null),
assert(windowsKeyCodeHeader != null),
assert(windowsNameMap != null) {
_nameToAndroidScanCodes = _readAndroidScanCodes(androidKeyboardLayout);
_nameToAndroidKeyCode = _readAndroidKeyCodes(androidKeyCodeHeader);
_nameToGlfwKeyCode = _readGlfwKeyCodes(glfwKeyCodeHeader);
_nameToGtkKeyCode = _readGtkKeyCodes(gtkKeyCodeHeader);
_nameToWindowsKeyCode = _readWindowsKeyCodes(windowsKeyCodeHeader);
// Cast Android dom map
final Map<String, List<dynamic>> dynamicAndroidNames = (json.decode(androidNameMap) as Map<String, dynamic>).cast<String, List<dynamic>>();
_nameToAndroidName = dynamicAndroidNames.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
// Cast GLFW dom map
final Map<String, List<dynamic>> dynamicGlfwNames = (json.decode(glfwNameMap) as Map<String, dynamic>).cast<String, List<dynamic>>();
_nameToGlfwName = dynamicGlfwNames.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
// Cast GTK dom map
final Map<String, List<dynamic>> dynamicGtkNames = (json.decode(gtkNameMap) as Map<String, dynamic>).cast<String, List<dynamic>>();
_nameToGtkName = dynamicGtkNames.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
// Cast Windows dom map
final Map<String, List<dynamic>> dynamicWindowsNames = (json.decode(windowsNameMap) as Map<String, dynamic>).cast<String, List<dynamic>>();
_nameToWindowsName = dynamicWindowsNames.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 (final String key in contentMap.keys) Key.fromJsonMapEntry(key, contentMap[key] as Map<String, dynamic>),
];
}
/// Converts the data structure into a JSON structure that can be parsed by
/// [KeyData.fromJson].
Map<String, dynamic> toJson() {
for (final Key entry in data) {
// Android Key names
entry.androidKeyNames = _nameToAndroidName[entry.constantName]?.cast<String>();
if (entry.androidKeyNames != null && entry.androidKeyNames.isNotEmpty) {
for (final 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]);
}
}
}
// GLFW key names
entry.glfwKeyNames = _nameToGlfwName[entry.constantName]?.cast<String>();
if (entry.glfwKeyNames != null && entry.glfwKeyNames.isNotEmpty) {
for (final String glfwKeyName in entry.glfwKeyNames) {
if (_nameToGlfwKeyCode[glfwKeyName] != null) {
entry.glfwKeyCodes ??= <int>[];
entry.glfwKeyCodes.add(_nameToGlfwKeyCode[glfwKeyName]);
}
}
}
// GTK key names
entry.gtkKeyNames = _nameToGtkName[entry.constantName]?.cast<String>();
if (entry.gtkKeyNames != null && entry.gtkKeyNames.isNotEmpty) {
for (final String gtkKeyName in entry.gtkKeyNames) {
if (_nameToGtkKeyCode[gtkKeyName] != null) {
entry.gtkKeyCodes ??= <int>[];
entry.gtkKeyCodes.add(_nameToGtkKeyCode[gtkKeyName]);
}
}
}
// Windows key names
entry.windowsKeyNames = _nameToWindowsName[entry.constantName]?.cast<String>();
if (entry.windowsKeyNames != null && entry.windowsKeyNames.isNotEmpty) {
for (final String windowsKeyName in entry.windowsKeyNames) {
if (_nameToWindowsKeyCode[windowsKeyName] != null) {
entry.windowsKeyCodes ??= <int>[];
entry.windowsKeyCodes.add(_nameToWindowsKeyCode[windowsKeyName]);
}
}
}
}
final Map<String, dynamic> outputMap = <String, dynamic>{};
for (final 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 Flutter name (e.g. "eject") to the GLFW name (e.g.
/// "GLFW_MEDIA_EJECT").
///
/// Only populated if data is parsed from the source files, not if parsed from
/// JSON.
Map<String, List<String>> _nameToGlfwName;
/// The mapping from the Flutter name (e.g. "eject") to the GTK name (e.g.
/// "GDK_KEY_Eject").
///
/// Only populated if data is parsed from the source files, not if parsed from
/// JSON.
Map<String, List<String>> _nameToGtkName;
/// 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;
/// The mapping from GLFW name (e.g. "GLFW_KEY_COMMA") 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> _nameToGlfwKeyCode;
/// The mapping from GTK name (e.g. "GTK_KEY_comma") 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> _nameToGtkKeyCode;
/// The mapping from Widows name (e.g. "RETURN") 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> _nameToWindowsKeyCode;
/// The mapping from the Flutter name (e.g. "enter") to the Windows name (e.g.
/// "RETURN").
///
/// Only populated if data is parsed from the source files, not if parsed from
/// JSON.
Map<String, List<String>> _nameToWindowsName;
/// 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 null;
});
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>{};
for (final Match match in enumEntry.allMatches(headerFile)) {
result[match.group(1)] = int.parse(match.group(2));
}
return result;
}
/// Parses entries from GLFW's keycodes.h key code data file.
///
/// Lines in this file look like this (without the ///):
/// /** Space key. */
/// #define GLFW_KEY_SPACE 32,
Map<String, int> _readGlfwKeyCodes(String headerFile) {
// Only get the KEY definitions, ignore the rest (mouse, joystick, etc).
final RegExp definedCodes = RegExp(r'define GLFW_KEY_([A-Z0-9_]+)\s*([A-Z0-9_]+),?');
final Map<String, dynamic> replaced = <String, dynamic>{};
for (final Match match in definedCodes.allMatches(headerFile)) {
replaced[match.group(1)] = int.tryParse(match.group(2)) ?? match.group(2).replaceAll('GLFW_KEY_', '');
}
final Map<String, int> result = <String, int>{};
replaced.forEach((String key, dynamic value) {
// Some definition values point to other definitions (e.g #define GLFW_KEY_LAST GLFW_KEY_MENU).
if (value is String) {
result[key] = replaced[value] as int;
} else {
result[key] = value as int;
}
});
return result;
}
/// Parses entries from GTK's gdkkeysyms.h key code data file.
///
/// Lines in this file look like this (without the ///):
/// /** Space key. */
/// #define GDK_KEY_space 0x020
Map<String, int> _readGtkKeyCodes(String headerFile) {
final RegExp definedCodes = RegExp(r'#define GDK_KEY_([a-zA-Z0-9_]+)\s*0x([0-9a-f]+),?');
final Map<String, int> replaced = <String, int>{};
for (final Match match in definedCodes.allMatches(headerFile)) {
replaced[match.group(1)] = int.parse(match.group(2), radix: 16);
}
return replaced;
}
Map<String, int> _readWindowsKeyCodes(String headerFile) {
final RegExp definedCodes = RegExp(r'define VK_([A-Z0-9_]+)\s*([A-Z0-9_x]+),?');
final Map<String, int> replaced = <String, int>{};
for (final Match match in definedCodes.allMatches(headerFile)) {
replaced[match.group(1)] = int.tryParse(match.group(2));
}
// The header doesn't explicitly define the [0-9] and [A-Z], but they mention that the range
// is equivalent to the ASCII value.
for (int i = 0x30; i <= 0x39; i++) {
replaced[String.fromCharCode(i)] = i;
}
for (int i = 0x41; i <= 0x5A; i++) {
replaced[String.fromCharCode(i)] = i;
}
return replaced;
}
/// 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
/// DOM_CODE(0x000010, 0x0000, 0x0000, 0x0000, 0xffff, "Hyper", HYPER),
List<Key> _readHidEntries(String input) {
final List<Key> entries = <Key>[];
final RegExp usbMapRegExp = RegExp(
r'DOM_CODE\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 usbHidCode = getHex(match.group(1));
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: usbHidCode,
linuxScanCode: linuxScanCode == 0 ? null : linuxScanCode,
xKbScanCode: xKbScanCode == 0 ? null : xKbScanCode,
windowsScanCode: windowsScanCode == 0 ? null : windowsScanCode,
macOsScanCode: macScanCode == 0xffff ? null : macScanCode,
iosScanCode: (usbHidCode & 0x070000) == 0x070000 ? (usbHidCode ^ 0x070000) : null,
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 '';
}
// Remove duplicates: last one wins, so that supplemental codes
// override.
entries.removeWhere((Key entry) => entry.usbHidCode == newEntry.usbHidCode);
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.windowsKeyNames,
this.windowsKeyCodes,
this.macOsScanCode,
this.iosScanCode,
@required this.chromiumName,
this.androidKeyNames,
this.androidScanCodes,
this.androidKeyCodes,
this.glfwKeyNames,
this.glfwKeyCodes,
this.gtkKeyNames,
this.gtkKeyCodes,
}) : 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'] as String,
chromiumName: map['names']['chromium'] as String,
usbHidCode: map['scanCodes']['usb'] as int,
androidKeyNames: (map['names']['android'] as List<dynamic>)?.cast<String>(),
androidScanCodes: (map['scanCodes']['android'] as List<dynamic>)?.cast<int>(),
androidKeyCodes: (map['keyCodes']['android'] as List<dynamic>)?.cast<int>(),
linuxScanCode: map['scanCodes']['linux'] as int,
xKbScanCode: map['scanCodes']['xkb'] as int,
windowsScanCode: map['scanCodes']['windows'] as int,
windowsKeyCodes: (map['keyCodes']['windows'] as List<dynamic>)?.cast<int>(),
windowsKeyNames: (map['names']['windows'] as List<dynamic>)?.cast<String>(),
macOsScanCode: map['scanCodes']['macos'] as int,
iosScanCode: map['scanCodes']['ios'] as int,
glfwKeyNames: (map['names']['glfw'] as List<dynamic>)?.cast<String>(),
glfwKeyCodes: (map['keyCodes']['glfw'] as List<dynamic>)?.cast<int>(),
gtkKeyNames: (map['names']['gtk'] as List<dynamic>)?.cast<String>(),
gtkKeyCodes: (map['keyCodes']['gtk'] as List<dynamic>)?.cast<int>(),
);
}
/// 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 list of Windows key codes matching this key, created by looking up the
/// Windows name in the Chromium data, and substituting the Windows key code
/// value.
List<int> windowsKeyCodes;
/// The list of names that Windows gives to this key (symbol names minus the
/// prefix).
List<String> windowsKeyNames;
/// The macOS scan code of the key from Chromium's header file.
int macOsScanCode;
/// The iOS scan code of the key from UIKey's documentation (USB Hid table)
int iosScanCode;
/// 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;
/// The list of names that GFLW gives to this key (symbol names minus the
/// prefix).
List<String> glfwKeyNames;
/// The list of GLFW key codes matching this key, created by looking up the
/// Linux name in the Chromium data, and substituting the GLFW key code
/// value.
List<int> glfwKeyCodes;
/// The list of names that GTK gives to this key (symbol names minus the
/// prefix).
List<String> gtkKeyNames;
/// The list of GTK key codes matching this key, created by looking up the
/// Linux name in the GTK data, and substituting the GTK key code
/// value.
List<int> gtkKeyCodes;
/// 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,
'glfw': glfwKeyNames,
'gtk': gtkKeyNames,
'windows': windowsKeyNames,
},
'scanCodes': <String, dynamic>{
'android': androidScanCodes,
'usb': usbHidCode,
'linux': linuxScanCode,
'xkb': xKbScanCode,
'windows': windowsScanCode,
'macos': macOsScanCode,
'ios': iosScanCode,
},
'keyCodes': <String, List<int>>{
'android': androidKeyCodes,
'glfw': glfwKeyCodes,
'gtk': gtkKeyCodes,
'windows': windowsKeyCodes,
},
};
}
/// 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);
}
static String getCommentName(String constantName) {
String upperCamel = lowerCamelToUpperCamel(constantName);
upperCamel = upperCamel.replaceAllMapped(RegExp(r'(Digit|Numpad|Lang|Button|Left|Right)([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 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 => getCommentName(constantName);
/// 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)}, """
'linuxScanCode: ${toHex(linuxScanCode)}, xKbScanCode: ${toHex(xKbScanCode)}, '
'windowsKeyCode: ${toHex(windowsScanCode)}, macOsScanCode: ${toHex(macOsScanCode)}, '
'windowsScanCode: ${toHex(windowsScanCode)}, chromiumSymbolName: $chromiumName '
'iOSScanCode: ${toHex(iosScanCode)})';
}
/// 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) as Map<String, dynamic>;
_printable = printable.cast<String, String>();
}
return _printable;
}
static Map<String, String> _printable;
/// Returns the static map of synonym representations.
///
/// These include synonyms for keys which don't have printable
/// representations, and appear in more than one place on the keyboard (e.g.
/// SHIFT, ALT, etc.).
static Map<String, List<dynamic>> get synonyms {
if (_synonym == null) {
final String synonymKeys = File(path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'synonyms.json',)).readAsStringSync();
final Map<String, dynamic> synonym = json.decode(synonymKeys) as Map<String, dynamic>;
_synonym = synonym.cast<String, List<dynamic>>();
}
return _synonym;
}
static Map<String, List<dynamic>> _synonym;
/// 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;
/// The code prefix for pseudo-keys which represent collections of key synonyms.
static const int synonymPlane = 0x20000000000;
}

View File

@@ -5,39 +5,40 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'constants.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// 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 (final 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();
String _wrapString(String input) {
return wrapString(input, prefix: ' /// ');
}
/// Generates the keyboard_keys.dart based on the information in the key data
class SynonymKeyInfo {
SynonymKeyInfo(this.keys, this.name);
final List<LogicalKeyEntry> keys;
final String name;
// Use the first item in the synonyms as a template for the ID to use.
// It won't end up being the same value because it'll be in the pseudo-key
// plane.
LogicalKeyEntry get primaryKey => keys[0];
int get value => (primaryKey.value & ~kVariationMask) + kSynonymPlane;
String get constantName => upperCamelToLowerCamel(name);
}
/// Generates the keyboard_key.dart based on the information in the key data
/// structure given to it.
class KeyboardKeysCodeGenerator extends BaseCodeGenerator {
KeyboardKeysCodeGenerator(KeyData keyData) : super(keyData);
KeyboardKeysCodeGenerator(PhysicalKeyData keyData, LogicalKeyData logicalData) : super(keyData, logicalData);
/// Gets the generated definitions of PhysicalKeyboardKeys.
String get _physicalDefinitions {
final StringBuffer definitions = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
final String firstComment = _wrapString('Represents the location of the '
'"${entry.commentName}" key on a generalized keyboard.');
final String otherComments = _wrapString('See the function '
@@ -53,7 +54,7 @@ $otherComments static const PhysicalKeyboardKey ${entry.constantName} = Physica
String get _physicalDebugNames {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
result.write('''
${toHex(entry.usbHidCode, digits: 8)}: '${entry.commentName}',
''');
@@ -64,7 +65,7 @@ $otherComments static const PhysicalKeyboardKey ${entry.constantName} = Physica
/// Gets the generated definitions of LogicalKeyboardKeys.
String get _logicalDefinitions {
final StringBuffer definitions = StringBuffer();
void printKey(int flutterId, String constantName, String commentName, {String otherComments}) {
void printKey(int flutterId, String constantName, String commentName, {String? otherComments}) {
final String firstComment = _wrapString('Represents the logical "$commentName" key on the keyboard.');
otherComments ??= _wrapString('See the function [RawKeyEvent.logicalKey] for more information.');
definitions.write('''
@@ -74,22 +75,20 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
''');
}
for (final Key entry in keyData.data) {
for (final LogicalKeyEntry entry in logicalData.entries) {
printKey(
entry.flutterId,
entry.value,
entry.constantName,
entry.commentName,
);
}
for (final String name in Key.synonyms.keys) {
for (final SynonymKeyInfo synonymInfo in synonyms) {
// Use the first item in the synonyms as a template for the ID to use.
// It won't end up being the same value because it'll be in the pseudo-key
// plane.
final Key entry = keyData.data.firstWhere((Key item) => item.name == Key.synonyms[name][0]);
final Set<String> unionNames = Key.synonyms[name].map<String>((dynamic name) {
return upperCamelToLowerCamel(name as String);
}).toSet();
printKey(Key.synonymPlane | entry.flutterId, name, Key.getCommentName(name),
final Set<String> unionNames = synonymInfo.keys.map(
(LogicalKeyEntry entry) => entry.constantName).toSet();
printKey(synonymInfo.value, synonymInfo.constantName, PhysicalKeyEntry.getCommentName(synonymInfo.name),
otherComments: _wrapString('This key represents the union of the keys '
'$unionNames when comparing keys. This key will never be generated '
'directly, its main use is in defining key maps.'));
@@ -98,30 +97,26 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
}
String get _logicalSynonyms {
final StringBuffer synonyms = StringBuffer();
for (final String name in Key.synonyms.keys) {
for (final String synonym in Key.synonyms[name].cast<String>()) {
final String keyName = upperCamelToLowerCamel(synonym);
synonyms.writeln(' $keyName: $name,');
final StringBuffer result = StringBuffer();
for (final SynonymKeyInfo synonymInfo in synonyms) {
for (final LogicalKeyEntry key in synonymInfo.keys) {
final String synonymName = upperCamelToLowerCamel(synonymInfo.name);
result.writeln(' ${key.constantName}: $synonymName,');
}
}
return synonyms.toString();
return result.toString();
}
String get _logicalKeyLabels {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
for (final LogicalKeyEntry entry in logicalData.entries) {
result.write('''
${toHex(entry.flutterId, digits: 11)}: '${entry.commentName}',
${toHex(entry.value, digits: 11)}: '${entry.commentName}',
''');
}
for (final String name in Key.synonyms.keys) {
// Use the first item in the synonyms as a template for the ID to use.
// It won't end up being the same value because it'll be in the pseudo-key
// plane.
final Key entry = keyData.data.firstWhere((Key item) => item.name == Key.synonyms[name][0]);
for (final SynonymKeyInfo synonymInfo in synonyms) {
result.write('''
${toHex(Key.synonymPlane | entry.flutterId, digits: 11)}: '${Key.getCommentName(name)}',
${toHex(synonymInfo.value)}: '${synonymInfo.name}',
''');
}
return result.toString();
@@ -130,7 +125,7 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
/// This generates the map of USB HID codes to physical keys.
String get _predefinedHidCodeMap {
final StringBuffer scanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
scanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: ${entry.constantName},');
}
return scanCodeMap.toString().trimRight();
@@ -139,35 +134,39 @@ $otherComments static const LogicalKeyboardKey $constantName = LogicalKeyboardK
/// This generates the map of Flutter key codes to logical keys.
String get _predefinedKeyCodeMap {
final StringBuffer keyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
keyCodeMap.writeln(' ${toHex(entry.flutterId, digits: 10)}: ${entry.constantName},');
for (final LogicalKeyEntry entry in logicalData.entries) {
keyCodeMap.writeln(' ${toHex(entry.value, digits: 11)}: ${entry.constantName},');
}
for (final String entry in Key.synonyms.keys) {
// Use the first item in the synonyms as a template for the ID to use.
// It won't end up being the same value because it'll be in the pseudo-key
// plane.
final Key primaryKey = keyData.data.firstWhere((Key item) {
return item.name == Key.synonyms[entry][0];
}, orElse: () => null);
assert(primaryKey != null);
keyCodeMap.writeln(' ${toHex(Key.synonymPlane | primaryKey.flutterId, digits: 10)}: $entry,');
for (final SynonymKeyInfo synonymInfo in synonyms) {
keyCodeMap.writeln(' ${toHex(synonymInfo.value, digits: 11)}: ${synonymInfo.constantName},');
}
return keyCodeMap.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_key.tmpl');
String get templatePath => path.join(dataRoot, 'keyboard_key.tmpl');
@override
Map<String, String> mappings() {
return <String, String>{
'PHYSICAL_KEY_MAP': _predefinedHidCodeMap,
'LOGICAL_KEY_MAP': _predefinedKeyCodeMap,
'LOGICAL_KEY_DEFINITIONS': _logicalDefinitions,
'LOGICAL_KEY_SYNONYMS': _logicalSynonyms,
'LOGICAL_KEY_KEY_LABELS': _logicalKeyLabels,
'PHYSICAL_KEY_MAP': _predefinedHidCodeMap,
'PHYSICAL_KEY_DEFINITIONS': _physicalDefinitions,
'PHYSICAL_KEY_DEBUG_NAMES': _physicalDebugNames,
};
}
late final List<SynonymKeyInfo> synonyms = LogicalKeyData.synonyms.entries.map(
(MapEntry<String, List<String>> synonymDefinition) {
final List<LogicalKeyEntry> entries = synonymDefinition.value.map(
(String name) => logicalData.entryByName(name)).toList();
return SynonymKeyInfo(
entries,
synonymDefinition.key,
);
}
).toList();
}

View File

@@ -2,87 +2,101 @@
// 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 'base_code_gen.dart';
import 'key_data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
bool _isAsciiLetter(String? char) {
if (char == null)
return false;
const int charUpperA = 0x41;
const int charUpperZ = 0x5A;
const int charLowerA = 0x61;
const int charLowerZ = 0x7A;
assert(char.length == 1);
final int charCode = char.codeUnitAt(0);
return (charCode >= charUpperA && charCode <= charUpperZ)
|| (charCode >= charLowerA && charCode <= charLowerZ);
}
/// Generates the keyboard_maps.dart files, based on the information in the key
/// data structure given to it.
class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
KeyboardMapsCodeGenerator(KeyData keyData) : super(keyData);
KeyboardMapsCodeGenerator(PhysicalKeyData keyData, LogicalKeyData logicalData)
: super(keyData, logicalData);
List<Key> get numpadKeyData {
return keyData.data.where((Key entry) {
return entry.constantName.startsWith('numpad') && entry.keyLabel != null;
List<PhysicalKeyEntry> get _numpadKeyData {
return keyData.entries.where((PhysicalKeyEntry entry) {
return entry.constantName.startsWith('numpad') && LogicalKeyData.printable.containsKey(entry.name);
}).toList();
}
List<Key> get functionKeyData {
List<PhysicalKeyEntry> get _functionKeyData {
final RegExp functionKeyRe = RegExp(r'^f[0-9]+$');
return keyData.data.where((Key entry) {
return keyData.entries.where((PhysicalKeyEntry entry) {
return functionKeyRe.hasMatch(entry.constantName);
}).toList();
}
List<LogicalKeyEntry> get _numpadLogicalKeyData {
return logicalData.entries.where((LogicalKeyEntry entry) {
return entry.constantName.startsWith('numpad') && LogicalKeyData.printable.containsKey(entry.name);
}).toList();
}
/// This generates the map of GLFW number pad key codes to logical keys.
String get glfwNumpadMap {
String get _glfwNumpadMap {
final StringBuffer glfwNumpadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.glfwKeyCodes != null) {
for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwNumpadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
for (final PhysicalKeyEntry entry in _numpadKeyData) {
for (final int code in entry.glfwKeyCodes) {
glfwNumpadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return glfwNumpadMap.toString().trimRight();
}
/// This generates the map of GLFW key codes to logical keys.
String get glfwKeyCodeMap {
String get _glfwKeyCodeMap {
final StringBuffer glfwKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.glfwKeyCodes != null) {
for (final int code in entry.glfwKeyCodes.cast<int>()) {
glfwKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
for (final PhysicalKeyEntry entry in keyData.entries) {
for (final int code in entry.glfwKeyCodes) {
glfwKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return glfwKeyCodeMap.toString().trimRight();
}
/// This generates the map of GTK number pad key codes to logical keys.
String get gtkNumpadMap {
final StringBuffer gtkNumpadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.gtkKeyCodes != null) {
for (final int code in entry.gtkKeyCodes.cast<int>()) {
gtkNumpadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
String get _gtkNumpadMap {
final OutputLines<int> lines = OutputLines<int>('GTK numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.gtkValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return gtkNumpadMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of GTK key codes to logical keys.
String get gtkKeyCodeMap {
final StringBuffer gtkKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.gtkKeyCodes != null) {
for (final int code in entry.gtkKeyCodes.cast<int>()) {
gtkKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
String get _gtkKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('GTK key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.gtkValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return gtkKeyCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of XKB USB HID codes to physical keys.
String get xkbScanCodeMap {
String get _xkbScanCodeMap {
final StringBuffer xkbScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.xKbScanCode != null) {
xkbScanCodeMap.writeln(' ${toHex(entry.xKbScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
@@ -91,37 +105,33 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
}
/// This generates the map of Android key codes to logical keys.
String get androidKeyCodeMap {
final StringBuffer androidKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.androidKeyCodes != null) {
for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
String get _androidKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Android key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.androidValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return androidKeyCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of Android number pad key codes to logical keys.
String get androidNumpadMap {
final StringBuffer androidKeyCodeMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.androidKeyCodes != null) {
for (final int code in entry.androidKeyCodes.cast<int>()) {
androidKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
String get _androidNumpadMap {
final OutputLines<int> lines = OutputLines<int>('Android numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.androidValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return androidKeyCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of Android scan codes to physical keys.
String get androidScanCodeMap {
String get _androidScanCodeMap {
final StringBuffer androidScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.androidScanCodes != null) {
for (final int code in entry.androidScanCodes.cast<int>()) {
for (final int code in entry.androidScanCodes) {
androidScanCodeMap.writeln(' $code: PhysicalKeyboardKey.${entry.constantName},');
}
}
@@ -130,9 +140,9 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
}
/// This generates the map of Windows scan codes to physical keys.
String get windowsScanCodeMap {
String get _windowsScanCodeMap {
final StringBuffer windowsScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.windowsScanCode != null) {
windowsScanCodeMap.writeln(' ${toHex(entry.windowsScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
@@ -141,35 +151,38 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
}
/// This generates the map of Windows number pad key codes to logical keys.
String get windowsNumpadMap {
final StringBuffer windowsNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.windowsKeyCodes != null){
for (final int code in entry.windowsKeyCodes) {
windowsNumPadMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
}
String get _windowsNumpadMap {
final OutputLines<int> lines = OutputLines<int>('Windows numpad map');
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
for (final int code in entry.windowsValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return windowsNumPadMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of Windows key codes to logical keys.
String get windowsKeyCodeMap {
final StringBuffer windowsKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.windowsKeyCodes != null) {
for (final int code in entry.windowsKeyCodes) {
windowsKeyCodeMap.writeln(' $code: LogicalKeyboardKey.${entry.constantName},');
String get _windowsKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Windows key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
// Letter keys on Windows are not recorded in logical_key_data.json,
// because they are not used by the embedding. Add them manually.
final List<int>? keyCodes = entry.windowsValues.isNotEmpty
? entry.windowsValues
: (_isAsciiLetter(entry.keyLabel) ? <int>[entry.keyLabel!.toUpperCase().codeUnitAt(0)] : null);
if (keyCodes != null) {
for (final int code in keyCodes) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
}
return windowsKeyCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS key codes to physical keys.
String get macOsScanCodeMap {
String get _macOsScanCodeMap {
final StringBuffer macOsScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.macOsScanCode != null) {
macOsScanCodeMap.writeln(' ${toHex(entry.macOsScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
@@ -178,9 +191,9 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
}
/// This generates the map of macOS number pad key codes to logical keys.
String get macOsNumpadMap {
String get _macOsNumpadMap {
final StringBuffer macOsNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
for (final PhysicalKeyEntry entry in _numpadKeyData) {
if (entry.macOsScanCode != null) {
macOsNumPadMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
@@ -188,9 +201,9 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
return macOsNumPadMap.toString().trimRight();
}
String get macOsFunctionKeyMap {
String get _macOsFunctionKeyMap {
final StringBuffer macOsFunctionKeyMap = StringBuffer();
for (final Key entry in functionKeyData) {
for (final PhysicalKeyEntry entry in _functionKeyData) {
if (entry.macOsScanCode != null) {
macOsFunctionKeyMap.writeln(' ${toHex(entry.macOsScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
@@ -198,43 +211,65 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
return macOsFunctionKeyMap.toString().trimRight();
}
/// This generates the map of iOS key codes to physical keys.
String get iosScanCodeMap {
final StringBuffer iosScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.iosScanCode != null) {
iosScanCodeMap.writeln(' ${toHex(entry.iosScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
/// This generates the map of macOS key codes to physical keys.
String get _macOsKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('MacOS key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.macOsKeyCodeValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return iosScanCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of iOS key codes to physical keys.
String get _iosScanCodeMap {
final OutputLines<int> lines = OutputLines<int>('iOS scancode map');
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.iosScanCode != null) {
lines.add(entry.iosScanCode!, ' ${toHex(entry.iosScanCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of iOS number pad key codes to logical keys.
String get iosNumpadMap {
final StringBuffer iosNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
String get _iosNumpadMap {
final OutputLines<int> lines = OutputLines<int>('iOS numpad map');
for (final PhysicalKeyEntry entry in _numpadKeyData) {
if (entry.iosScanCode != null) {
iosNumPadMap.writeln(' ${toHex(entry.iosScanCode)}: LogicalKeyboardKey.${entry.constantName},');
lines.add(entry.iosScanCode!,' ${toHex(entry.iosScanCode)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return iosNumPadMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of macOS key codes to physical keys.
String get _iosKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('iOS key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int code in entry.iosKeyCodeValues) {
lines.add(code, ' $code: LogicalKeyboardKey.${entry.constantName},');
}
}
return lines.sortedJoin().trimRight();
}
/// This generates the map of Fuchsia key codes to logical keys.
String get fuchsiaKeyCodeMap {
final StringBuffer fuchsiaKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.usbHidCode != null) {
fuchsiaKeyCodeMap.writeln(' ${toHex(entry.flutterId)}: LogicalKeyboardKey.${entry.constantName},');
String get _fuchsiaKeyCodeMap {
final OutputLines<int> lines = OutputLines<int>('Fuchsia key code map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final int value in entry.fuchsiaValues) {
lines.add(value, ' ${toHex(value)}: LogicalKeyboardKey.${entry.constantName},');
}
}
return fuchsiaKeyCodeMap.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of Fuchsia USB HID codes to physical keys.
String get fuchsiaHidCodeMap {
String get _fuchsiaHidCodeMap {
final StringBuffer fuchsiaScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.usbHidCode != null) {
fuchsiaScanCodeMap.writeln(' ${toHex(entry.usbHidCode)}: PhysicalKeyboardKey.${entry.constantName},');
}
@@ -243,20 +278,20 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
}
/// This generates the map of Web KeyboardEvent codes to logical keys.
String get webLogicalKeyMap {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.name != null) {
result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},");
String get _webLogicalKeyMap {
final OutputLines<String> lines = OutputLines<String>('Web logical key map');
for (final LogicalKeyEntry entry in logicalData.entries) {
for (final String name in entry.webNames) {
lines.add(name, " '$name': LogicalKeyboardKey.${entry.constantName},");
}
}
return result.toString().trimRight();
return lines.sortedJoin().trimRight();
}
/// This generates the map of Web KeyboardEvent codes to physical keys.
String get webPhysicalKeyMap {
String get _webPhysicalKeyMap {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.name != null) {
result.writeln(" '${entry.name}': PhysicalKeyboardKey.${entry.constantName},");
}
@@ -264,10 +299,9 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
return result.toString().trimRight();
}
/// This generates the map of Web number pad codes to logical keys.
String get webNumpadMap {
String get _webNumpadMap {
final StringBuffer result = StringBuffer();
for (final Key entry in numpadKeyData) {
for (final LogicalKeyEntry entry in _numpadLogicalKeyData) {
if (entry.name != null) {
result.writeln(" '${entry.name}': LogicalKeyboardKey.${entry.constantName},");
}
@@ -275,33 +309,51 @@ class KeyboardMapsCodeGenerator extends BaseCodeGenerator {
return result.toString().trimRight();
}
/// This generates the map of Web number pad codes to logical keys.
String get _webLocationMap {
final String jsonRaw = File(path.join(dataRoot, 'web_logical_location_mapping.json')).readAsStringSync();
final Map<String, List<String?>> locationMap = parseMapOfListOfNullableString(jsonRaw);
final StringBuffer result = StringBuffer();
locationMap.forEach((String key, List<String?> keyNames) {
final String keyStrings = keyNames.map((String? keyName) {
final String? constantName = keyName == null ? null : logicalData.entryByName(keyName).constantName;
return constantName != null ? 'LogicalKeyboardKey.$constantName' : 'null';
}).join(', ');
result.writeln(" '$key': <LogicalKeyboardKey?>[$keyStrings],");
});
return result.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_maps.tmpl');
String get templatePath => path.join(dataRoot, 'keyboard_maps.tmpl');
@override
Map<String, String> mappings() {
return <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,
'MACOS_SCAN_CODE_MAP': macOsScanCodeMap,
'MACOS_NUMPAD_MAP': macOsNumpadMap,
'MACOS_FUNCTION_KEY_MAP': macOsFunctionKeyMap,
'IOS_SCAN_CODE_MAP': iosScanCodeMap,
'IOS_NUMPAD_MAP': iosNumpadMap,
'GLFW_KEY_CODE_MAP': glfwKeyCodeMap,
'GLFW_NUMPAD_MAP': glfwNumpadMap,
'GTK_KEY_CODE_MAP': gtkKeyCodeMap,
'GTK_NUMPAD_MAP': gtkNumpadMap,
'XKB_SCAN_CODE_MAP': xkbScanCodeMap,
'WEB_LOGICAL_KEY_MAP': webLogicalKeyMap,
'WEB_PHYSICAL_KEY_MAP': webPhysicalKeyMap,
'WEB_NUMPAD_MAP': webNumpadMap,
'WINDOWS_LOGICAL_KEY_MAP': windowsKeyCodeMap,
'WINDOWS_PHYSICAL_KEY_MAP': windowsScanCodeMap,
'WINDOWS_NUMPAD_MAP': windowsNumpadMap,
'ANDROID_SCAN_CODE_MAP': _androidScanCodeMap,
'ANDROID_KEY_CODE_MAP': _androidKeyCodeMap,
'ANDROID_NUMPAD_MAP': _androidNumpadMap,
'FUCHSIA_SCAN_CODE_MAP': _fuchsiaHidCodeMap,
'FUCHSIA_KEY_CODE_MAP': _fuchsiaKeyCodeMap,
'MACOS_SCAN_CODE_MAP': _macOsScanCodeMap,
'MACOS_NUMPAD_MAP': _macOsNumpadMap,
'MACOS_FUNCTION_KEY_MAP': _macOsFunctionKeyMap,
'MACOS_KEY_CODE_MAP': _macOsKeyCodeMap,
'IOS_SCAN_CODE_MAP': _iosScanCodeMap,
'IOS_NUMPAD_MAP': _iosNumpadMap,
'IOS_KEY_CODE_MAP': _iosKeyCodeMap,
'GLFW_KEY_CODE_MAP': _glfwKeyCodeMap,
'GLFW_NUMPAD_MAP': _glfwNumpadMap,
'GTK_KEY_CODE_MAP': _gtkKeyCodeMap,
'GTK_NUMPAD_MAP': _gtkNumpadMap,
'XKB_SCAN_CODE_MAP': _xkbScanCodeMap,
'WEB_LOGICAL_KEY_MAP': _webLogicalKeyMap,
'WEB_PHYSICAL_KEY_MAP': _webPhysicalKeyMap,
'WEB_NUMPAD_MAP': _webNumpadMap,
'WEB_LOCATION_MAP': _webLocationMap,
'WINDOWS_LOGICAL_KEY_MAP': _windowsKeyCodeMap,
'WINDOWS_PHYSICAL_KEY_MAP': _windowsScanCodeMap,
'WINDOWS_NUMPAD_MAP': _windowsNumpadMap,
};
}
}

View File

@@ -0,0 +1,611 @@
// Copyright 2014 The Flutter 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:gen_keycodes/utils.dart';
import 'constants.dart';
import 'physical_key_data.dart';
bool _isControlCharacter(String label) {
if (label.length != 1) {
return false;
}
final int codeUnit = label.codeUnitAt(0);
return (codeUnit <= 0x1f && codeUnit >= 0x00) || (codeUnit >= 0x7f && codeUnit <= 0x9f);
}
/// A pair of strings that represents left and right modifiers.
class _ModifierPair {
const _ModifierPair(this.left, this.right);
final String left;
final String right;
}
List<T> _toNonEmptyArray<T>(dynamic source) {
final List<dynamic>? dynamicNullableList = source as List<dynamic>?;
final List<dynamic> dynamicList = dynamicNullableList ?? <dynamic>[];
return dynamicList.cast<T>();
}
/// 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
/// [LogicalKeyData.fromJson] constructor and [toJson] method, respectively.
class LogicalKeyData {
factory LogicalKeyData(
String chromiumKeys,
String gtkKeyCodeHeader,
String gtkNameMap,
String windowsKeyCodeHeader,
String windowsNameMap,
String androidKeyCodeHeader,
String androidNameMap,
String macosLogicalToPhysical,
String iosLogicalToPhysical,
PhysicalKeyData physicalKeyData,
) {
final Map<String, LogicalKeyEntry> data = <String, LogicalKeyEntry>{};
_readKeyEntries(data, chromiumKeys);
_readWindowsKeyCodes(data, windowsKeyCodeHeader, parseMapOfListOfString(windowsNameMap));
_readGtkKeyCodes(data, gtkKeyCodeHeader, parseMapOfListOfString(gtkNameMap));
_readAndroidKeyCodes(data, androidKeyCodeHeader, parseMapOfListOfString(androidNameMap));
_readMacOsKeyCodes(data, physicalKeyData, parseMapOfListOfString(macosLogicalToPhysical));
_readIosKeyCodes(data, physicalKeyData, parseMapOfListOfString(iosLogicalToPhysical));
_readFuchsiaKeyCodes(data, physicalKeyData);
// Sort entries by value
final List<MapEntry<String, LogicalKeyEntry>> sortedEntries = data.entries.toList()..sort(
(MapEntry<String, LogicalKeyEntry> a, MapEntry<String, LogicalKeyEntry> b) =>
LogicalKeyEntry.compareByValue(a.value, b.value),
);
data
..clear()
..addEntries(sortedEntries);
return LogicalKeyData._(data);
}
/// Parses the given JSON data and populates the data structure from it.
factory LogicalKeyData.fromJson(Map<String, dynamic> contentMap) {
final Map<String, LogicalKeyEntry> data = <String, LogicalKeyEntry>{};
data.addEntries(contentMap.values.map((dynamic value) {
final LogicalKeyEntry entry = LogicalKeyEntry.fromJsonMapEntry(value as Map<String, dynamic>);
return MapEntry<String, LogicalKeyEntry>(entry.name, entry);
}));
return LogicalKeyData._(data);
}
/// Parses the input data given in from the various data source files,
/// populating the data structure.
///
/// None of the parameters may be null.
LogicalKeyData._(this._data);
/// Converts the data structure into a JSON structure that can be parsed by
/// [LogicalKeyData.fromJson].
Map<String, dynamic> toJson() {
final Map<String, dynamic> outputMap = <String, dynamic>{};
for (final LogicalKeyEntry entry in _data.values) {
outputMap[entry.name] = entry.toJson();
}
return outputMap;
}
/// Find an entry from name.
///
/// Asserts if the name is not found.
LogicalKeyEntry entryByName(String name) {
assert(_data.containsKey(name),
'Unable to find logical entry by name $name.');
return _data[name]!;
}
/// All entries.
Iterable<LogicalKeyEntry> get entries => _data.values;
// Keys mapped from their names.
final Map<String, LogicalKeyEntry> _data;
/// Parses entries from Chromium's key mapping header file.
///
/// Lines in this file look like either of these (without the ///):
/// Key Enum Unicode code point
/// DOM_KEY_UNI("Backspace", BACKSPACE, 0x0008),
/// Key Enum Value
/// DOM_KEY_MAP("Accel", ACCEL, 0x0101),
///
/// Flutter's supplemental_key_data.inc also has a new format
/// that uses a character as the 3rd argument.
/// Key Enum Character
/// DOM_KEY_UNI("KeyB", KEY_B, 'b'),
static void _readKeyEntries(Map<String, LogicalKeyEntry> data, String input) {
final Map<String, String> unusedNumpad = Map<String, String>.from(_printableToNumpads);
final RegExp domKeyRegExp = RegExp(
r'DOM_KEY_(?<kind>UNI|MAP)\s*\(\s*'
r'"(?<name>[^\s]+?)",\s*'
r'(?<enum>[^\s]+?),\s*'
r"(?:0[xX](?<unicode>[a-fA-F0-9]+)|'(?<char>.)')\s*"
r'\)',
// Multiline is necessary because some definitions spread across
// multiple lines.
multiLine: true,
);
final RegExp commentRegExp = RegExp(r'//.*$', multiLine: true);
input = input.replaceAll(commentRegExp, '');
for (final RegExpMatch match in domKeyRegExp.allMatches(input)) {
final String webName = match.namedGroup('name')!;
// ".AltGraphLatch" is consumed internally and not expressed to the Web.
if (webName.startsWith('.')) {
continue;
}
final String name = LogicalKeyEntry.computeName(webName.replaceAll(RegExp('[^A-Za-z0-9]'), ''));
final int value = match.namedGroup('unicode') != null ?
getHex(match.namedGroup('unicode')!) :
match.namedGroup('char')!.codeUnitAt(0);
final String? keyLabel = match.namedGroup('kind')! == 'UNI' ? String.fromCharCode(value) : null;
// If it's a modifier key, add left and right keys instead.
// Don't add web names and values; they're solved with locations.
if (_chromeModifiers.containsKey(name)) {
final _ModifierPair pair = _chromeModifiers[name]!;
data[pair.left] = LogicalKeyEntry.fromName(
value: value + kLeftModifierPlane,
name: pair.left,
keyLabel: null, // Modifier keys don't have keyLabels
)..webNames.add(pair.left)
..webValues.add(value + kLeftModifierPlane);
data[pair.right] = LogicalKeyEntry.fromName(
value: value + kRightModifierPlane,
name: pair.right,
keyLabel: null, // Modifier keys don't have keyLabels
)..webNames.add(pair.right)
..webValues.add(value + kRightModifierPlane);
continue;
}
// If it has a numpad counterpart, also add the numpad key.
final String? char = value < 256 ? String.fromCharCode(value) : null;
if (char != null && _printableToNumpads.containsKey(char)) {
final String numpadName = _printableToNumpads[char]!;
data[numpadName] = LogicalKeyEntry.fromName(
value: char.codeUnitAt(0) + kNumpadPlane,
name: numpadName,
keyLabel: null, // Don't add keyLabel for numpad counterparts
)..webNames.add(numpadName)
..webValues.add(char.codeUnitAt(0) + kNumpadPlane);
unusedNumpad.remove(char);
}
data.putIfAbsent(name, () {
final bool isPrintable = (keyLabel != null && !_isControlCharacter(keyLabel))
|| printable.containsKey(name)
|| value == 0; // "None" key
return LogicalKeyEntry.fromName(
value: value + (isPrintable ? kUnicodePlane : kUnprintablePlane),
name: name,
keyLabel: keyLabel,
)..webNames.add(webName)
..webValues.add(value);
});
}
// Make sure every Numpad key that we care about has been defined.
unusedNumpad.forEach((String key, String value) {
print('Unuadded numpad key $value');
});
}
static void _readMacOsKeyCodes(
Map<String, LogicalKeyEntry> data,
PhysicalKeyData physicalKeyData,
Map<String, List<String>> logicalToPhysical,
) {
final Map<String, String> physicalToLogical = reverseMapOfListOfString(logicalToPhysical,
(String logicalKeyName, String physicalKeyName) { print('Duplicate logical key name $logicalKeyName for macOS'); });
physicalToLogical.forEach((String physicalKeyName, String logicalKeyName) {
final PhysicalKeyEntry physicalEntry = physicalKeyData.entryByName(physicalKeyName);
assert(physicalEntry.macOsScanCode != null,
'Physical entry $physicalKeyName does not have a macOsScanCode.');
final LogicalKeyEntry? logicalEntry = data[logicalKeyName];
assert(logicalEntry != null,
'Unable to find logical entry by name $logicalKeyName.');
logicalEntry!.macOsKeyCodeNames.add(physicalEntry.name);
logicalEntry.macOsKeyCodeValues.add(physicalEntry.macOsScanCode!);
});
}
static void _readIosKeyCodes(
Map<String, LogicalKeyEntry> data,
PhysicalKeyData physicalKeyData,
Map<String, List<String>> logicalToPhysical,
) {
final Map<String, String> physicalToLogical = reverseMapOfListOfString(logicalToPhysical,
(String logicalKeyName, String physicalKeyName) { print('Duplicate logical key name $logicalKeyName for iOS'); });
physicalToLogical.forEach((String physicalKeyName, String logicalKeyName) {
final PhysicalKeyEntry physicalEntry = physicalKeyData.entryByName(physicalKeyName);
assert(physicalEntry.iosScanCode != null,
'Physical entry $physicalKeyName does not have an iosScanCode.');
final LogicalKeyEntry? logicalEntry = data[logicalKeyName];
assert(logicalEntry != null,
'Unable to find logical entry by name $logicalKeyName.');
logicalEntry!.iosKeyCodeNames.add(physicalEntry.name);
logicalEntry.iosKeyCodeValues.add(physicalEntry.iosScanCode!);
});
}
/// Parses entries from GTK's gdkkeysyms.h key code data file.
///
/// Lines in this file look like this (without the ///):
/// /** Space key. */
/// #define GDK_KEY_space 0x020
static void _readGtkKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameToGtkName) {
final RegExp definedCodes = RegExp(
r'#define '
r'GDK_KEY_(?<name>[a-zA-Z0-9_]+)\s*'
r'0x(?<value>[0-9a-f]+),?',
);
final Map<String, String> gtkNameToFlutterName = reverseMapOfListOfString(nameToGtkName,
(String flutterName, String gtkName) { print('Duplicate GTK logical name $gtkName'); });
for (final RegExpMatch match in definedCodes.allMatches(headerFile)) {
final String gtkName = match.namedGroup('name')!;
final String? name = gtkNameToFlutterName[gtkName];
final int value = int.parse(match.namedGroup('value')!, radix: 16);
if (name == null) {
// print('Unmapped GTK logical entry $gtkName');
continue;
}
final LogicalKeyEntry? entry = data[name];
if (entry == null) {
print('Invalid logical entry by name $name (from GTK $gtkName)');
continue;
}
entry
..gtkNames.add(gtkName)
..gtkValues.add(value);
}
}
static void _readWindowsKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameMap) {
// The mapping from the Flutter name (e.g. "enter") to the Windows name (e.g.
// "RETURN").
final Map<String, String> nameToFlutterName = reverseMapOfListOfString(nameMap,
(String flutterName, String windowsName) { print('Duplicate Windows logical name $windowsName'); });
final RegExp definedCodes = RegExp(
r'define '
r'VK_(?<name>[A-Z0-9_]+)\s*'
r'(?<value>[A-Z0-9_x]+),?',
);
for (final RegExpMatch match in definedCodes.allMatches(headerFile)) {
final String windowsName = match.namedGroup('name')!;
final String? name = nameToFlutterName[windowsName];
final int value = int.tryParse(match.namedGroup('value')!)!;
if (name == null) {
print('Unmapped Windows logical entry $windowsName');
continue;
}
final LogicalKeyEntry? entry = data[name];
if (entry == null) {
print('Invalid logical entry by name $name (from Windows $windowsName)');
continue;
}
addNameValue(
entry.windowsNames,
entry.windowsValues,
windowsName,
value,
);
}
}
/// 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,
static void _readAndroidKeyCodes(Map<String, LogicalKeyEntry> data, String headerFile, Map<String, List<String>> nameMap) {
final Map<String, String> nameToFlutterName = reverseMapOfListOfString(nameMap,
(String flutterName, String androidName) { print('Duplicate Android logical name $androidName'); });
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_(?<name>[A-Z0-9_]+)\s*'
r'=\s*'
r'(?<value>[0-9]+),?',
);
for (final RegExpMatch match in enumEntry.allMatches(headerFile)) {
final String androidName = match.namedGroup('name')!;
final String? name = nameToFlutterName[androidName];
final int value = int.tryParse(match.namedGroup('value')!)!;
if (name == null) {
print('Unmapped Android logical entry $androidName');
continue;
}
final LogicalKeyEntry? entry = data[name];
if (entry == null) {
print('Invalid logical entry by name $name (from Android $androidName)');
continue;
}
entry
..androidNames.add(androidName)
..androidValues.add(value);
}
}
static void _readFuchsiaKeyCodes(Map<String, LogicalKeyEntry> data, PhysicalKeyData physicalData) {
for (final LogicalKeyEntry entry in data.values) {
final int? value = (() {
if (entry.value == 0) // "None" key
return 0;
final String? keyLabel = printable[entry.constantName];
if (keyLabel != null && !entry.constantName.startsWith('numpad')) {
return kUnicodePlane | (keyLabel.codeUnitAt(0) & kValueMask);
} else {
final PhysicalKeyEntry? physicalEntry = physicalData.tryEntryByName(entry.name);
if (physicalEntry != null) {
return kHidPlane | (physicalEntry.usbHidCode & kValueMask);
}
}
})();
if (value != null)
entry.fuchsiaValues.add(value);
}
}
// Map Web key to the pair of key names
static late final Map<String, _ModifierPair> _chromeModifiers = () {
final String rawJson = File(path.join(dataRoot, 'chromium_modifiers.json',)).readAsStringSync();
return (json.decode(rawJson) as Map<String, dynamic>).map((String key, dynamic value) {
final List<dynamic> pair = value as List<dynamic>;
return MapEntry<String, _ModifierPair>(key, _ModifierPair(pair[0] as String, pair[1] as String));
});
}();
/// Returns the static map of printable representations.
static late final Map<String, String> printable = ((){
final String printableKeys = File(path.join(dataRoot, 'printable.json',)).readAsStringSync();
return (json.decode(printableKeys) as Map<String, dynamic>)
.cast<String, String>();
})();
// Map printable to corresponding numpad key name
static late final Map<String, String> _printableToNumpads = () {
final String rawJson = File(path.join(dataRoot, 'printable_to_numpads.json',)).readAsStringSync();
return (json.decode(rawJson) as Map<String, dynamic>).map((String key, dynamic value) {
return MapEntry<String, String>(key, value as String);
});
}();
/// Returns the static map of synonym representations.
///
/// These include synonyms for keys which don't have printable
/// representations, and appear in more than one place on the keyboard (e.g.
/// SHIFT, ALT, etc.).
static late final Map<String, List<String>> synonyms = ((){
final String synonymKeys = File(path.join(dataRoot, 'synonyms.json',)).readAsStringSync();
final Map<String, dynamic> dynamicSynonym = json.decode(synonymKeys) as Map<String, dynamic>;
return dynamicSynonym.map((String name, dynamic values) {
// The keygen and algorithm of macOS relies on synonyms being pairs.
// See siblingKeyMap in macos_code_gen.dart.
final List<String> names = (values as List<dynamic>).whereType<String>().toList();
assert(names.length == 2);
return MapEntry<String, List<String>>(name, names);
});
})();
}
/// A single entry in the key data structure.
///
/// Can be read from JSON with the [LogicalKeyEntry.fromJsonMapEntry] constructor, or
/// written with the [toJson] method.
class LogicalKeyEntry {
/// Creates a single key entry from available data.
LogicalKeyEntry({
required this.value,
required this.name,
this.keyLabel,
}) : webNames = <String>[],
webValues = <int>[],
macOsKeyCodeNames = <String>[],
macOsKeyCodeValues = <int>[],
iosKeyCodeNames = <String>[],
iosKeyCodeValues = <int>[],
gtkNames = <String>[],
gtkValues = <int>[],
windowsNames = <String>[],
windowsValues = <int>[],
androidNames = <String>[],
androidValues = <int>[],
fuchsiaValues = <int>[];
LogicalKeyEntry.fromName({
required int value,
required String name,
String? keyLabel,
}) : this(
value: value,
name: name,
keyLabel: keyLabel,
);
/// Populates the key from a JSON map.
LogicalKeyEntry.fromJsonMapEntry(Map<String, dynamic> map)
: value = map['value'] as int,
name = map['name'] as String,
webNames = _toNonEmptyArray<String>(map['names']['web']),
webValues = _toNonEmptyArray<int>(map['values']['web']),
macOsKeyCodeNames = _toNonEmptyArray<String>(map['names']['macOs']),
macOsKeyCodeValues = _toNonEmptyArray<int>(map['values']['macOs']),
iosKeyCodeNames = _toNonEmptyArray<String>(map['names']['ios']),
iosKeyCodeValues = _toNonEmptyArray<int>(map['values']['ios']),
gtkNames = _toNonEmptyArray<String>(map['names']['gtk']),
gtkValues = _toNonEmptyArray<int>(map['values']['gtk']),
windowsNames = _toNonEmptyArray<String>(map['names']['windows']),
windowsValues = _toNonEmptyArray<int>(map['values']['windows']),
androidNames = _toNonEmptyArray<String>(map['names']['android']),
androidValues = _toNonEmptyArray<int>(map['values']['android']),
fuchsiaValues = _toNonEmptyArray<int>(map['values']['fuchsia']),
keyLabel = map['keyLabel'] as String?;
final int value;
final String name;
/// The name of the key suitable for placing in comments.
String get commentName => computeCommentName(name);
String get constantName => computeConstantName(commentName);
/// 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.
final List<String> webNames;
/// The value of the key.
final List<int> webValues;
/// The names of the key codes that corresponds to this logical key on macOS,
/// created from the corresponding physical keys.
final List<String> macOsKeyCodeNames;
/// The key codes that corresponds to this logical key on macOS, created from
/// the physical key list substituted with the key mapping.
final List<int> macOsKeyCodeValues;
/// The names of the key codes that corresponds to this logical key on iOS,
/// created from the corresponding physical keys.
final List<String> iosKeyCodeNames;
/// The key codes that corresponds to this logical key on iOS, created from the
/// physical key list substituted with the key mapping.
final List<int> iosKeyCodeValues;
/// The list of names that GTK gives to this key (symbol names minus the
/// prefix).
final List<String> gtkNames;
/// The list of GTK key codes matching this key, created by looking up the
/// Linux name in the GTK data, and substituting the GTK key code
/// value.
final List<int> gtkValues;
/// The list of names that Windows gives to this key (symbol names minus the
/// prefix).
final List<String> windowsNames;
/// The list of Windows key codes matching this key, created by looking up the
/// Windows name in the Chromium data, and substituting the Windows key code
/// value.
final List<int> windowsValues;
/// The list of names that Android gives to this key (symbol names minus the
/// prefix).
final List<String> androidNames;
/// 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.
final List<int> androidValues;
final List<int> fuchsiaValues;
/// A string indicating the letter on the keycap of a letter key.
///
/// This is only used to generate the key label mapping in keyboard_map.dart.
/// [LogicalKeyboardKey.keyLabel] uses a different definition and is generated
/// differently.
final String? keyLabel;
/// Creates a JSON map from the key data.
Map<String, dynamic> toJson() {
return removeEmptyValues(<String, dynamic>{
'name': name,
'value': value,
'keyLabel': keyLabel,
'names': <String, dynamic>{
'web': webNames,
'macOs': macOsKeyCodeNames,
'ios': iosKeyCodeNames,
'gtk': gtkNames,
'windows': windowsNames,
'android': androidNames,
},
'values': <String, List<int>>{
'web': webValues,
'macOs': macOsKeyCodeValues,
'ios': iosKeyCodeValues,
'gtk': gtkValues,
'windows': windowsValues,
'android': androidValues,
'fuchsia': fuchsiaValues,
},
});
}
@override
String toString() {
return "'$name': (value: ${toHex(value)}) ";
}
/// Gets the named used for the key constant in the definitions in
/// keyboard_key.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).
static String computeName(String rawName) {
final String result = rawName.replaceAll('PinP', 'PInP');
if (kDartReservedWords.contains(result)) {
return '${result}Key';
}
return result;
}
/// Takes the [name] and converts it from lower camel case to capitalized
/// separate words (e.g. "wakeUp" converts to "Wake Up").
static String computeCommentName(String name) {
final String replaced = name.replaceAllMapped(
RegExp(r'(Digit|Numpad|Lang|Button|Left|Right)([0-9]+)'), (Match match) => '${match.group(1)} ${match.group(2)}',
);
return replaced
// 'fooBar' => 'foo Bar', 'fooBAR' => 'foo BAR'
.replaceAllMapped(RegExp(r'([^A-Z])([A-Z])'), (Match match) => '${match.group(1)} ${match.group(2)}')
// 'ABCDoo' => 'ABC Doo'
.replaceAllMapped(RegExp(r'([A-Z])([A-Z])([a-z])'), (Match match) => '${match.group(1)} ${match.group(2)}${match.group(3)}')
// 'AB1' => 'AB 1', 'F1' => 'F1'
.replaceAllMapped(RegExp(r'([A-Z]{2,})([0-9])'), (Match match) => '${match.group(1)} ${match.group(2)}')
// 'Foo1' => 'Foo 1'
.replaceAllMapped(RegExp(r'([a-z])([0-9])'), (Match match) => '${match.group(1)} ${match.group(2)}')
.trim();
}
static String computeConstantName(String commentName) {
// Convert the first word in the comment name.
final String lowerCamelSpace = commentName.replaceFirstMapped(RegExp(r'^[^ ]+'),
(Match match) => match[0]!.toLowerCase(),
);
final String result = lowerCamelSpace.replaceAll(' ', '');
if (kDartReservedWords.contains(result)) {
return '${result}Key';
}
return result;
}
static int compareByValue(LogicalKeyEntry a, LogicalKeyEntry b) =>
a.value.compareTo(b.value);
}

View File

@@ -5,52 +5,108 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'constants.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
const List<String> kModifiersOfInterest = <String>[
'ShiftLeft',
'ShiftRight',
'ControlLeft',
'ControlRight',
'AltLeft',
'AltRight',
'MetaLeft',
'MetaRight',
];
/// Generates the key mapping of macOS, based on the information in the key
// The name of keys that require special attention.
const List<String> kSpecialPhysicalKeys = <String>['CapsLock'];
const List<String> kSpecialLogicalKeys = <String>['CapsLock'];
String _toConstantVariableName(String variableName) {
return 'k${variableName[0].toUpperCase()}${variableName.substring(1)}';
}
/// Generates the key mapping for macOS, based on the information in the key
/// data structure given to it.
class MacOsCodeGenerator extends PlatformCodeGenerator {
MacOsCodeGenerator(KeyData keyData) : super(keyData);
MacOsCodeGenerator(PhysicalKeyData keyData, LogicalKeyData logicalData)
: super(keyData, logicalData);
/// This generates the map of macOS key codes to physical keys.
String get _macOsScanCodeMap {
final StringBuffer macOsScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
String get _scanCodeMap {
final StringBuffer scanCodeMap = StringBuffer();
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.macOsScanCode != null) {
macOsScanCodeMap.writeln(' { ${toHex(entry.macOsScanCode)}, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
scanCodeMap.writeln(' @${toHex(entry.macOsScanCode)} : @${toHex(entry.usbHidCode)}, // ${entry.constantName}');
}
}
return macOsScanCodeMap.toString().trimRight();
return scanCodeMap.toString().trimRight();
}
/// This generates the map of macOS number pad key codes to logical keys.
String get _macOsNumpadMap {
final StringBuffer macOsNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.macOsScanCode != null) {
macOsNumPadMap.writeln(' { ${toHex(entry.macOsScanCode)}, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
String get _keyCodeToLogicalMap {
final StringBuffer result = StringBuffer();
for (final LogicalKeyEntry entry in logicalData.entries) {
zipStrict(entry.macOsKeyCodeValues, entry.macOsKeyCodeNames, (int macOsValue, String macOsName) {
result.writeln(' @${toHex(macOsValue)} : @${toHex(entry.value, digits: 10)}, // $macOsName');
});
}
return macOsNumPadMap.toString().trimRight();
return result.toString().trimRight();
}
String get _macOsFunctionKeyMap {
final StringBuffer macOsFunctionKeyMap = StringBuffer();
for (final Key entry in functionKeyData) {
if (entry.macOsScanCode != null) {
macOsFunctionKeyMap.writeln(' { ${toHex(entry.macOsScanCode)}, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
/// This generates the mask values for the part of a key code that defines its plane.
String get _maskConstants {
final StringBuffer buffer = StringBuffer();
for (final MaskConstant constant in maskConstants) {
buffer.writeln('/**');
buffer.write(constant.description
.map((String line) => wrapString(line, prefix: ' * '))
.join(' *\n'));
buffer.writeln(' */');
buffer.writeln('const uint64_t ${_toConstantVariableName(constant.name)} = ${toHex(constant.value, digits: 11)};');
buffer.writeln('');
}
return macOsFunctionKeyMap.toString().trimRight();
return buffer.toString().trimRight();
}
/// This generates a map from the key code to a modifier flag.
String get _keyToModifierFlagMap {
final StringBuffer modifierKeyMap = StringBuffer();
for (final String name in kModifiersOfInterest) {
modifierKeyMap.writeln(' @${toHex(logicalData.entryByName(name).macOsKeyCodeValues[0])} : @(kModifierFlag${lowerCamelToUpperCamel(name)}),');
}
return modifierKeyMap.toString().trimRight();
}
/// This generates a map from the modifier flag to the key code.
String get _modifierFlagToKeyMap {
final StringBuffer modifierKeyMap = StringBuffer();
for (final String name in kModifiersOfInterest) {
modifierKeyMap.writeln(' @(kModifierFlag${lowerCamelToUpperCamel(name)}) : @${toHex(logicalData.entryByName(name).macOsKeyCodeValues[0])},');
}
return modifierKeyMap.toString().trimRight();
}
/// This generates some keys that needs special attention.
String get _specialKeyConstants {
final StringBuffer specialKeyConstants = StringBuffer();
for (final String keyName in kSpecialPhysicalKeys) {
specialKeyConstants.writeln('const uint64_t k${keyName}PhysicalKey = ${toHex(keyData.entryByName(keyName).usbHidCode)};');
}
for (final String keyName in kSpecialLogicalKeys) {
specialKeyConstants.writeln('const uint64_t k${lowerCamelToUpperCamel(keyName)}LogicalKey = ${toHex(logicalData.entryByName(keyName).value)};');
}
return specialKeyConstants.toString().trimRight();
}
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_macos_cc.tmpl');
String get templatePath => path.join(dataRoot, 'macos_key_code_map_cc.tmpl');
@override
String outputPath(String platform) => path.joinAll(<String>[flutterRoot.path, '..', 'engine', 'src', 'flutter', 'shell', 'platform', 'darwin', platform, 'keycodes', 'keyboard_map_$platform.h']);
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot,
'shell', 'platform', 'darwin', 'macos', 'framework', 'Source', 'KeyCodeMap.mm');
@override
Map<String, String> mappings() {
@@ -58,9 +114,12 @@ class MacOsCodeGenerator extends PlatformCodeGenerator {
// The LogicalKeyboardKey is generated by raw_keyboard_macos.dart from the unmodified characters
// from NSEvent.
return <String, String>{
'MACOS_SCAN_CODE_MAP': _macOsScanCodeMap,
'MACOS_NUMPAD_MAP': _macOsNumpadMap,
'MACOS_FUNCTION_KEY_MAP': _macOsFunctionKeyMap,
'MACOS_SCAN_CODE_MAP': _scanCodeMap,
'MACOS_KEYCODE_LOGICAL_MAP': _keyCodeToLogicalMap,
'MASK_CONSTANTS': _maskConstants,
'KEYCODE_TO_MODIFIER_FLAG_MAP': _keyToModifierFlagMap,
'MODIFIER_FLAG_TO_KEYCODE_MAP': _modifierFlagToKeyMap,
'SPECIAL_KEY_CONSTANTS': _specialKeyConstants,
};
}
}

View File

@@ -0,0 +1,390 @@
// Copyright 2014 The Flutter 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 '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
/// [PhysicalKeyData.fromJson] constructor and [toJson] method, respectively.
class PhysicalKeyData {
factory PhysicalKeyData(
String chromiumHidCodes,
String androidKeyboardLayout,
String androidNameMap,
String glfwHeaderFile,
String glfwNameMap,
) {
final Map<String, List<int>> nameToAndroidScanCodes = _readAndroidScanCodes(androidKeyboardLayout, androidNameMap);
final Map<String, List<int>> nameToGlfwKeyCodes = _readGlfwKeyCodes(glfwHeaderFile, glfwNameMap);
final Map<String, PhysicalKeyEntry> data = _readHidEntries(
chromiumHidCodes,
nameToAndroidScanCodes,
nameToGlfwKeyCodes,
);
final List<MapEntry<String, PhysicalKeyEntry>> sortedEntries = data.entries.toList()..sort(
(MapEntry<String, PhysicalKeyEntry> a, MapEntry<String, PhysicalKeyEntry> b) =>
PhysicalKeyEntry.compareByUsbHidCode(a.value, b.value),
);
data
..clear()
..addEntries(sortedEntries);
return PhysicalKeyData._(data);
}
/// Parses the given JSON data and populates the data structure from it.
factory PhysicalKeyData.fromJson(Map<String, dynamic> contentMap) {
final Map<String, PhysicalKeyEntry> data = <String, PhysicalKeyEntry>{};
for (final MapEntry<String, dynamic> jsonEntry in contentMap.entries) {
final PhysicalKeyEntry entry = PhysicalKeyEntry.fromJsonMapEntry(jsonEntry.value as Map<String, dynamic>);
data[entry.name] = entry;
}
return PhysicalKeyData._(data);
}
PhysicalKeyData._(this._data);
/// Find an entry from name, or null if not found.
PhysicalKeyEntry? tryEntryByName(String name) {
return _data[name];
}
/// Find an entry from name.
///
/// Asserts if the name is not found.
PhysicalKeyEntry entryByName(String name) {
final PhysicalKeyEntry? entry = tryEntryByName(name);
assert(entry != null,
'Unable to find logical entry by name $name.');
return entry!;
}
/// All entries.
Iterable<PhysicalKeyEntry> get entries => _data.values;
// Keys mapped from their names.
final Map<String, PhysicalKeyEntry> _data;
/// Converts the data structure into a JSON structure that can be parsed by
/// [PhysicalKeyData.fromJson].
Map<String, dynamic> toJson() {
final Map<String, dynamic> outputMap = <String, dynamic>{};
for (final PhysicalKeyEntry entry in _data.values) {
outputMap[entry.name] = entry.toJson();
}
return outputMap;
}
/// 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"
/// key 477 F12 FUNCTION
///
/// 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.
static Map<String, List<int>> _readAndroidScanCodes(String keyboardLayout, String nameMap) {
final RegExp keyEntry = RegExp(
r'#?\s*' // Optional comment mark
r'key\s+' // Literal "key"
r'(?<id>[0-9]+)\s*' // ID section
r'"?(?:KEY_)?(?<name>[0-9A-Z_]+|\(undefined\))"?\s*' // Name section
r'(?<function>FUNCTION)?' // Optional literal "FUNCTION"
);
final Map<String, List<int>> androidNameToScanCodes = <String, List<int>>{};
for (final RegExpMatch match in keyEntry.allMatches(keyboardLayout)) {
if (match.namedGroup('function') == 'FUNCTION') {
// Skip odd duplicate Android FUNCTION keys (F1-F12 are already defined).
continue;
}
final String name = match.namedGroup('name')!;
if (name == '(undefined)') {
// Skip undefined scan codes.
continue;
}
androidNameToScanCodes.putIfAbsent(name, () => <int>[])
.add(int.parse(match.namedGroup('id')!));
}
// Cast Android dom map
final Map<String, List<String>> nameToAndroidNames = (json.decode(nameMap) as Map<String, dynamic>)
.cast<String, List<dynamic>>()
.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
final Map<String, List<int>> result = nameToAndroidNames.map((String name, List<String> androidNames) {
final Set<int> scanCodes = <int>{};
for (final String androidName in androidNames) {
scanCodes.addAll(androidNameToScanCodes[androidName] ?? <int>[]);
}
return MapEntry<String, List<int>>(name, scanCodes.toList()..sort());
});
return result;
}
/// Parses entries from GLFW's keycodes.h key code data file.
///
/// Lines in this file look like this (without the ///):
/// /** Space key. */
/// #define GLFW_KEY_SPACE 32,
/// #define GLFW_KEY_LAST GLFW_KEY_MENU
static Map<String, List<int>> _readGlfwKeyCodes(String headerFile, String nameMap) {
// Only get the KEY definitions, ignore the rest (mouse, joystick, etc).
final RegExp definedCodes = RegExp(
r'define\s+'
r'GLFW_KEY_(?<name>[A-Z0-9_]+)\s+'
r'(?<value>[A-Z0-9_]+),?',
);
final Map<String, dynamic> replaced = <String, dynamic>{};
for (final RegExpMatch match in definedCodes.allMatches(headerFile)) {
final String name = match.namedGroup('name')!;
final String value = match.namedGroup('value')!;
replaced[name] = int.tryParse(value) ?? value.replaceAll('GLFW_KEY_', '');
}
final Map<String, int> glfwNameToKeyCode = <String, int>{};
replaced.forEach((String key, dynamic value) {
// Some definition values point to other definitions (e.g #define GLFW_KEY_LAST GLFW_KEY_MENU).
if (value is String) {
glfwNameToKeyCode[key] = replaced[value] as int;
} else {
glfwNameToKeyCode[key] = value as int;
}
});
final Map<String, List<String>> nameToGlfwNames = (json.decode(nameMap) as Map<String, dynamic>)
.cast<String, List<dynamic>>()
.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
final Map<String, List<int>> result = nameToGlfwNames.map((String name, List<String> glfwNames) {
final Set<int> keyCodes = <int>{};
for (final String glfwName in glfwNames) {
if (glfwNameToKeyCode[glfwName] != null)
keyCodes.add(glfwNameToKeyCode[glfwName]!);
}
return MapEntry<String, List<int>>(name, keyCodes.toList()..sort());
});
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
/// DOM_CODE(0x000010, 0x0000, 0x0000, 0x0000, 0xffff, "Hyper", HYPER),
static Map<String, PhysicalKeyEntry> _readHidEntries(
String input,
Map<String, List<int>> nameToAndroidScanCodes,
Map<String, List<int>> nameToGlfwKeyCodes,
) {
final Map<int, PhysicalKeyEntry> entries = <int, PhysicalKeyEntry>{};
final RegExp usbMapRegExp = RegExp(
r'DOM_CODE\s*\(\s*'
r'0[xX](?<usb>[a-fA-F0-9]+),\s*'
r'0[xX](?<evdev>[a-fA-F0-9]+),\s*'
r'0[xX](?<xkb>[a-fA-F0-9]+),\s*'
r'0[xX](?<win>[a-fA-F0-9]+),\s*'
r'0[xX](?<mac>[a-fA-F0-9]+),\s*'
r'(?:"(?<code>[^\s]+)")?[^")]*?,'
r'\s*(?<enum>[^\s]+?)\s*'
r'\)',
// Multiline is necessary because some definitions spread across
// multiple lines.
multiLine: true,
);
final RegExp commentRegExp = RegExp(r'//.*$', multiLine: true);
input = input.replaceAll(commentRegExp, '');
for (final RegExpMatch match in usbMapRegExp.allMatches(input)) {
final int usbHidCode = getHex(match.namedGroup('usb')!);
final int linuxScanCode = getHex(match.namedGroup('evdev')!);
final int xKbScanCode = getHex(match.namedGroup('xkb')!);
final int windowsScanCode = getHex(match.namedGroup('win')!);
final int macScanCode = getHex(match.namedGroup('mac')!);
final String? chromiumCode = match.namedGroup('code');
// The input data has a typo...
final String enumName = match.namedGroup('enum')!.replaceAll('MINIMIUM', 'MINIMUM');
final String name = chromiumCode ?? shoutingToUpperCamel(enumName);
if (name == 'IntlHash') {
// Skip key that is not actually generated by any keyboard.
continue;
}
final PhysicalKeyEntry newEntry = PhysicalKeyEntry(
usbHidCode: usbHidCode,
androidScanCodes: nameToAndroidScanCodes[name] ?? <int>[],
glfwKeyCodes: nameToGlfwKeyCodes[name] ?? <int>[],
linuxScanCode: linuxScanCode == 0 ? null : linuxScanCode,
xKbScanCode: xKbScanCode == 0 ? null : xKbScanCode,
windowsScanCode: windowsScanCode == 0 ? null : windowsScanCode,
macOsScanCode: macScanCode == 0xffff ? null : macScanCode,
iosScanCode: (usbHidCode & 0x070000) == 0x070000 ? (usbHidCode ^ 0x070000) : null,
name: name,
chromiumCode: chromiumCode,
);
// Remove duplicates: last one wins, so that supplemental codes
// override.
if (entries.containsKey(newEntry.usbHidCode)) {
// This is expected for Fn. Warn for other keys.
if (newEntry.name != 'Fn') {
print('Duplicate usbHidCode ${newEntry.usbHidCode} of key ${newEntry.name} '
'conflicts with existing ${entries[newEntry.usbHidCode]!.name}. Keeping the new one.');
}
}
entries[newEntry.usbHidCode] = newEntry;
}
return entries.map((int code, PhysicalKeyEntry entry) =>
MapEntry<String, PhysicalKeyEntry>(entry.name, entry));
}
}
/// A single entry in the key data structure.
///
/// Can be read from JSON with the [PhysicalKeyEntry.fromJsonMapEntry] constructor, or
/// written with the [toJson] method.
class PhysicalKeyEntry {
/// Creates a single key entry from available data.
///
/// The [usbHidCode] and [chromiumName] parameters must not be null.
PhysicalKeyEntry({
required this.usbHidCode,
required this.name,
required this.androidScanCodes,
required this.linuxScanCode,
required this.xKbScanCode,
required this.windowsScanCode,
required this.macOsScanCode,
required this.iosScanCode,
required this.chromiumCode,
required this.glfwKeyCodes,
});
/// Populates the key from a JSON map.
factory PhysicalKeyEntry.fromJsonMapEntry(Map<String, dynamic> map) {
return PhysicalKeyEntry(
name: map['names']['name'] as String,
chromiumCode: map['names']['chromium'] as String?,
usbHidCode: map['scanCodes']['usb'] as int,
androidScanCodes: (map['scanCodes']['android'] as List<dynamic>?)?.cast<int>() ?? <int>[],
linuxScanCode: map['scanCodes']['linux'] as int?,
xKbScanCode: map['scanCodes']['xkb'] as int?,
windowsScanCode: map['scanCodes']['windows'] as int?,
macOsScanCode: map['scanCodes']['macos'] as int?,
iosScanCode: map['scanCodes']['ios'] as int?,
glfwKeyCodes: (map['keyCodes']?['glfw'] as List<dynamic>?)?.cast<int>() ?? <int>[],
);
}
/// The USB HID code of the key
final int usbHidCode;
/// The Linux scan code of the key, from Chromium's header file.
final int? linuxScanCode;
/// The XKb scan code of the key from Chromium's header file.
final int? xKbScanCode;
/// The Windows scan code of the key from Chromium's header file.
final int? windowsScanCode;
/// The macOS scan code of the key from Chromium's header file.
final int? macOsScanCode;
/// The iOS scan code of the key from UIKey's documentation (USB Hid table)
final int? iosScanCode;
/// 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.
final List<int> androidScanCodes;
/// The list of GLFW key codes matching this key, created by looking up the
/// Linux name in the Chromium data, and substituting the GLFW key code
/// value.
final List<int> glfwKeyCodes;
/// 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.
final String name;
/// The Chromium event code for the key.
final String? chromiumCode;
/// Creates a JSON map from the key data.
Map<String, dynamic> toJson() {
return removeEmptyValues(<String, dynamic>{
'names': <String, dynamic>{
'name': name,
'chromium': chromiumCode,
},
'scanCodes': <String, dynamic>{
'android': androidScanCodes,
'usb': usbHidCode,
'linux': linuxScanCode,
'xkb': xKbScanCode,
'windows': windowsScanCode,
'macos': macOsScanCode,
'ios': iosScanCode,
},
'keyCodes': <String, List<int>>{
'glfw': glfwKeyCodes,
},
});
}
static String getCommentName(String constantName) {
String upperCamel = lowerCamelToUpperCamel(constantName);
upperCamel = upperCamel.replaceAllMapped(
RegExp(r'(Digit|Numpad|Lang|Button|Left|Right)([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 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 => getCommentName(constantName);
/// Gets the named used for the key constant in the definitions in
/// keyboard_key.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).
late final String constantName = ((){
String? result;
if (name.isEmpty) {
// If it doesn't have a DomKey name then use the Chromium symbol name.
result = chromiumCode;
} else {
result = upperCamelToLowerCamel(name);
}
result ??= 'Key${toHex(usbHidCode)}';
if (kDartReservedWords.contains(result)) {
return '${result}Key';
}
return result;
})();
@override
String toString() {
return """'$constantName': (name: "$name", usbHidCode: ${toHex(usbHidCode)}, """
'linuxScanCode: ${toHex(linuxScanCode)}, xKbScanCode: ${toHex(xKbScanCode)}, '
'windowsKeyCode: ${toHex(windowsScanCode)}, macOsScanCode: ${toHex(macOsScanCode)}, '
'windowsScanCode: ${toHex(windowsScanCode)}, chromiumSymbolName: $chromiumCode '
'iOSScanCode: ${toHex(iosScanCode)})';
}
static int compareByUsbHidCode(PhysicalKeyEntry a, PhysicalKeyEntry b) =>
a.usbHidCode.compareTo(b.usbHidCode);
}

View File

@@ -2,6 +2,7 @@
// 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;
@@ -9,20 +10,27 @@ import 'package:path/path.dart' as path;
/// The location of the Flutter root directory, based on the known location of
/// this script.
final Directory flutterRoot = Directory(path.dirname(Platform.script.toFilePath())).parent.parent.parent.parent;
final String dataRoot = path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data');
/// Converts `FOO_BAR` to `fooBar`.
String shoutingToLowerCamel(String shouting) {
final RegExp initialLetter = RegExp(r'_([^_])([^_]*)');
/// Converts `FOO_BAR` to `FooBar`.
String shoutingToUpperCamel(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 match.group(1)!.toUpperCase() + match.group(2)!.toLowerCase();
});
return result;
}
/// Converts 'FooBar' to 'fooBar'.
///
/// 'TVFoo' should be convert to 'tvFoo'.
/// 'KeyX' should be convert to 'keyX'.
String upperCamelToLowerCamel(String upperCamel) {
return upperCamel.substring(0, 1).toLowerCase() + upperCamel.substring(1);
final RegExp initialGroup = RegExp(r'^([A-Z]([A-Z]*|[^A-Z]*))([A-Z]([^A-Z]|$)|$)');
return upperCamel.replaceFirstMapped(initialGroup, (Match match) {
return match.group(1)!.toLowerCase() + (match.group(3) ?? '');
});
}
/// Converts 'fooBar' to 'FooBar'.
@@ -97,7 +105,7 @@ const List<String> kDartReservedWords = <String>[
];
/// Converts an integer into a hex string with the given number of digits.
String toHex(int value, {int digits = 8}) {
String toHex(int? value, {int digits = 8}) {
if (value == null) {
return 'null';
}
@@ -108,3 +116,137 @@ String toHex(int value, {int digits = 8}) {
int getHex(String input) {
return int.parse(input, radix: 16);
}
/// 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, {required 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 (final 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();
}
/// Run `fn` with each corresponding element from list1 and list2.
///
/// If `list1` has a different length from `list2`, the execution is aborted
/// after printing an error.
///
/// An null list is considered a list with length 0.
void zipStrict<T1, T2>(Iterable<T1> list1, Iterable<T2> list2, void Function(T1, T2) fn) {
if (list1 == null && list2 == null)
return;
assert(list1.length == list2.length);
final Iterator<T1> it1 = list1.iterator;
final Iterator<T2> it2 = list2.iterator;
while (it1.moveNext()) {
it2.moveNext();
fn(it1.current, it2.current);
}
}
/// Read a Map<String, String> out of its string representation in JSON.
Map<String, String> parseMapOfString(String jsonString) {
return (json.decode(jsonString) as Map<String, dynamic>).cast<String, String>();
}
/// Read a Map<String, List<String>> out of its string representation in JSON.
Map<String, List<String>> parseMapOfListOfString(String jsonString) {
final Map<String, List<dynamic>> dynamicMap = (json.decode(jsonString) as Map<String, dynamic>).cast<String, List<dynamic>>();
return dynamicMap.map<String, List<String>>((String key, List<dynamic> value) {
return MapEntry<String, List<String>>(key, value.cast<String>());
});
}
Map<String, List<String?>> parseMapOfListOfNullableString(String jsonString) {
final Map<String, List<dynamic>> dynamicMap = (json.decode(jsonString) as Map<String, dynamic>).cast<String, List<dynamic>>();
return dynamicMap.map<String, List<String?>>((String key, List<dynamic> value) {
return MapEntry<String, List<String?>>(key, value.cast<String?>());
});
}
/// Reverse the map of { fromValue -> list of toValue } to { toValue -> fromValue } and return.
Map<String, String> reverseMapOfListOfString(Map<String, List<String>> inMap, void Function(String fromValue, String newToValue) onDuplicate) {
final Map<String, String> result = <String, String>{};
inMap.forEach((String fromValue, List<String> toValues) {
for (final String toValue in toValues) {
if (result.containsKey(toValue)) {
onDuplicate(fromValue, toValue);
continue;
}
result[toValue] = fromValue;
}
});
return result;
}
/// Remove entries whose value `isEmpty` or is null, and return the map.
///
/// Will modify the input map.
Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) {
return map..removeWhere((String key, dynamic value) {
if (value == null)
return true;
if (value is Map<String, dynamic>) {
final Map<String, dynamic> regularizedMap = removeEmptyValues(value);
return regularizedMap.isEmpty;
}
if (value is Iterable<dynamic>) {
return value.isEmpty;
}
return false;
});
}
void addNameValue(List<String> names, List<int> values, String name, int value) {
final int foundIndex = values.indexOf(value);
if (foundIndex == -1) {
names.add(name);
values.add(value);
} else {
if (!RegExp(r'(^|, )abc1($|, )').hasMatch(name)) {
names[foundIndex] = '${names[foundIndex]}, $name';
}
}
}
/// A utility class to build join a number of lines in a sorted order.
///
/// Use [add] to add a line and associate it with an index. Use [sortedJoin] to
/// get the joined string of these lines joined sorting them in the order of the
/// index.
class OutputLines<T extends Comparable<Object>> {
OutputLines(this.mapName);
/// The name for this map.
///
/// Used in warning messages.
final String mapName;
final Map<T, String> lines = <T, String>{};
void add(T code, String line) {
if (lines.containsKey(code)) {
print('Warn: $mapName is requested to add line $code as:\n $line\n but it already exists as:\n ${lines[code]}');
}
lines[code] = line;
}
String sortedJoin() {
return (lines.entries.toList()
..sort((MapEntry<T, String> a, MapEntry<T, String> b) => a.key.compareTo(b.key)))
.map((MapEntry<T, String> entry) => entry.value)
.join('\n');
}
}

View File

@@ -5,22 +5,27 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// Generates the key mapping of Web, based on the information in the key
/// Generates the key mapping for Web, based on the information in the key
/// data structure given to it.
class WebCodeGenerator extends PlatformCodeGenerator {
WebCodeGenerator(KeyData keyData) : super(keyData);
WebCodeGenerator(
PhysicalKeyData keyData,
LogicalKeyData logicalData,
String logicalLocationMap,
) : _logicalLocationMap = parseMapOfListOfNullableString(logicalLocationMap),
super(keyData, logicalData);
/// This generates the map of Web KeyboardEvent codes to logical key ids.
String get _webLogicalKeyCodeMap {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.name != null) {
result.writeln(" '${entry.name}': ${toHex(entry.flutterId, digits: 10)},");
}
for (final LogicalKeyEntry entry in logicalData.entries) {
zipStrict(entry.webValues, entry.webNames, (int value, String name) {
result.writeln(" '$name': ${toHex(value, digits: 10)},");
});
}
return result.toString().trimRight();
}
@@ -28,7 +33,7 @@ class WebCodeGenerator extends PlatformCodeGenerator {
/// This generates the map of Web KeyboardEvent codes to physical key USB HID codes.
String get _webPhysicalKeyCodeMap {
final StringBuffer result = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.name != null) {
result.writeln(" '${entry.name}': ${toHex(entry.usbHidCode)},");
}
@@ -37,28 +42,31 @@ class WebCodeGenerator extends PlatformCodeGenerator {
}
/// This generates the map of Web number pad codes to logical key ids.
String get _webNumpadCodeMap {
String get _webLogicalLocationMap {
final StringBuffer result = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.name != null) {
result.writeln(" '${entry.name}': ${toHex(entry.flutterId, digits: 10)},");
}
}
_logicalLocationMap.forEach((String webKey, List<String?> locations) {
final String valuesString = locations.map((String? value) {
return value == null ? 'null' : toHex(logicalData.entryByName(value).value, digits: 10);
}).join(', ');
result.writeln(" '$webKey': <int?>[$valuesString],");
});
return result.toString().trimRight();
}
final Map<String, List<String?>> _logicalLocationMap;
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_web.tmpl');
String get templatePath => path.join(dataRoot, 'web_key_map_dart.tmpl');
@override
String outputPath(String platform) => path.join(flutterRoot.path, '..', 'engine', 'src', 'flutter', path.join('lib', 'web_ui', 'lib', 'src', 'engine', 'keycodes', 'keyboard_map_web.dart'));
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot,
'lib', 'web_ui', 'lib', 'src', 'engine', 'key_map.dart');
@override
Map<String, String> mappings() {
return <String, String>{
'WEB_LOGICAL_KEY_CODE_MAP': _webLogicalKeyCodeMap,
'WEB_PHYSICAL_KEY_CODE_MAP': _webPhysicalKeyCodeMap,
'WEB_NUMPAD_CODE_MAP': _webNumpadCodeMap,
'WEB_LOGICAL_LOCATION_MAP': _webLogicalLocationMap,
};
}
}

View File

@@ -5,59 +5,71 @@
import 'package:path/path.dart' as path;
import 'base_code_gen.dart';
import 'key_data.dart';
import 'logical_key_data.dart';
import 'physical_key_data.dart';
import 'utils.dart';
/// Generates the key mapping of Windows, based on the information in the key
/// Generates the key mapping for Windows, based on the information in the key
/// data structure given to it.
class WindowsCodeGenerator extends PlatformCodeGenerator {
WindowsCodeGenerator(KeyData keyData) : super(keyData);
WindowsCodeGenerator(
PhysicalKeyData keyData,
LogicalKeyData logicalData,
String scancodeToLogical,
) : _scancodeToLogical = parseMapOfString(scancodeToLogical),
super(keyData, logicalData);
/// This generates the map of Windows scan codes to physical keys.
String get _windowsScanCodeMap {
final StringBuffer windowsScanCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
for (final PhysicalKeyEntry entry in keyData.entries) {
if (entry.windowsScanCode != null) {
windowsScanCodeMap.writeln(' { ${entry.windowsScanCode}, ${toHex(entry.usbHidCode)} }, // ${entry.constantName}');
windowsScanCodeMap.writeln(' {${toHex(entry.windowsScanCode)}, ${toHex(entry.usbHidCode)}}, // ${entry.constantName}');
}
}
return windowsScanCodeMap.toString().trimRight();
}
/// This generates the map of Windows number pad key codes to logical keys.
String get _windowsNumpadMap {
final StringBuffer windowsNumPadMap = StringBuffer();
for (final Key entry in numpadKeyData) {
if (entry.windowsScanCode != null) {
windowsNumPadMap.writeln(' { ${toHex(entry.windowsScanCode)}, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
/// This generates the map of Windows key codes to logical keys.
String get _windowsLogicalKeyCodeMap {
final StringBuffer result = StringBuffer();
for (final LogicalKeyEntry entry in logicalData.entries) {
zipStrict(entry.windowsValues, entry.windowsNames, (int windowsValue, String windowsName) {
result.writeln(' {${toHex(windowsValue)}, ${toHex(entry.value, digits: 11)}}, // $windowsName');
});
}
return windowsNumPadMap.toString().trimRight();
return result.toString().trimRight();
}
/// This generates the map of Android key codes to logical keys.
String get _windowsKeyCodeMap {
final StringBuffer windowsKeyCodeMap = StringBuffer();
for (final Key entry in keyData.data) {
if (entry.windowsKeyCodes != null) {
for (final int code in entry.windowsKeyCodes.cast<int>()) {
windowsKeyCodeMap.writeln(' { $code, ${toHex(entry.flutterId, digits: 10)} }, // ${entry.constantName}');
}
}
}
return windowsKeyCodeMap.toString().trimRight();
/// This generates the map from scan code to logical keys.
///
/// Normally logical keys should only be derived from key codes, but since some
/// key codes are either 0 or ambiguous (multiple keys using the same key
/// code), these keys are resolved by scan codes.
String get _scanCodeToLogicalMap {
final StringBuffer result = StringBuffer();
_scancodeToLogical.forEach((String scanCodeName, String logicalName) {
final PhysicalKeyEntry physicalEntry = keyData.entryByName(scanCodeName);
final int logicalValue = logicalData.entryByName(logicalName).value;
result.writeln(' {${toHex(physicalEntry.windowsScanCode)}, ${toHex(logicalValue, digits: 10)}}, // ${physicalEntry.name}');
});
return result.toString().trimRight();
}
final Map<String, String> _scancodeToLogical;
@override
String get templatePath => path.join(flutterRoot.path, 'dev', 'tools', 'gen_keycodes', 'data', 'keyboard_map_windows_cc.tmpl');
String get templatePath => path.join(dataRoot, 'windows_flutter_key_map_cc.tmpl');
@override
String outputPath(String platform) => path.join(PlatformCodeGenerator.engineRoot,
'shell', 'platform', 'windows', 'flutter_key_map.cc');
@override
Map<String, String> mappings() {
return <String, String>{
'WINDOWS_SCAN_CODE_MAP': _windowsScanCodeMap,
'WINDOWS_NUMPAD_MAP': _windowsNumpadMap,
'WINDOWS_KEY_CODE_MAP': _windowsKeyCodeMap,
'WINDOWS_SCAN_CODE_TO_LOGICAL_MAP': _scanCodeToLogicalMap,
'WINDOWS_KEY_CODE_MAP': _windowsLogicalKeyCodeMap,
};
}
}