base_code_gen.dart 1.93 KB
Newer Older
1 2 3 4 5
// 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:io';
6
import 'logical_key_data.dart';
7

8
import 'physical_key_data.dart';
9 10 11 12

String _injectDictionary(String template, Map<String, String> dictionary) {
  String result = template;
  for (final String key in dictionary.keys) {
13
    result = result.replaceAll('@@@$key@@@', dictionary[key] ?? '@@@$key@@@');
14 15 16 17 18 19 20 21 22 23 24 25 26 27
  }
  return result;
}

/// Generates a file based on the information in the key data structure given to
/// it.
///
/// [BaseCodeGenerator] finds tokens in the template file that has the form of
/// `@@@TOKEN@@@`, and replace them by looking up the key `TOKEN` from the map
/// returned by [mappings].
///
/// Subclasses must implement [templatePath] and [mappings].
abstract class BaseCodeGenerator {
  /// Create a code generator while providing [keyData] to be used in [mappings].
28
  BaseCodeGenerator(this.keyData, this.logicalData);
29 30 31 32 33 34 35 36

  /// Absolute path to the template file that this file is generated on.
  String get templatePath;

  /// A mapping from tokens to be replaced in the template to the result string.
  Map<String, String> mappings();

  /// Substitutes the various platform specific maps into the template file for
37
  /// keyboard_maps.g.dart.
38 39 40 41 42 43
  String generate() {
    final String template = File(templatePath).readAsStringSync();
    return _injectDictionary(template, mappings());
  }

  /// The database of keys loaded from disk.
44 45 46
  final PhysicalKeyData keyData;

  final LogicalKeyData logicalData;
47 48 49 50
}

/// A code generator which also defines platform-based behavior.
abstract class PlatformCodeGenerator extends BaseCodeGenerator {
51
  PlatformCodeGenerator(super.keyData, super.logicalData);
52 53 54 55

  /// Absolute path to the output file.
  ///
  /// How this value will be used is based on the callee.
56 57 58
  String outputPath(String platform);

  static String engineRoot = '';
59
}