update_icons.dart 8.54 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Regenerates the material icons file.
// See https://github.com/flutter/flutter/wiki/Updating-Material-Design-Fonts

import 'dart:convert' show LineSplitter;
import 'dart:io';

import 'package:args/args.dart';
import 'package:path/path.dart' as path;

14 15 16 17
const String _newCodepointsPathOption = 'new-codepoints';
const String _oldCodepointsPathOption = 'old-codepoints';
const String _iconsClassPathOption = 'icons';
const String _dryRunOption = 'dry-run';
18

19 20 21
const String _defaultNewCodepointsPath = 'codepoints';
const String _defaultOldCodepointsPath = 'bin/cache/artifacts/material_fonts/codepoints';
const String _defaultIconsPath = 'packages/flutter/lib/src/material/icons.dart';
22

23 24
const String _beginGeneratedMark = '// BEGIN GENERATED';
const String _endGeneratedMark = '// END GENERATED';
25

26
const Map<String, String> _identifierRewrites = <String, String>{
27 28
  '360': 'threesixty',
  '3d_rotation': 'threed_rotation',
29 30
  '6_ft': 'six_ft',
  '5g': 'five_g',
31 32 33
  '1k': 'one_k',
  '2k': 'two_k',
  '3k': 'three_k',
34
  '4k': 'four_k',
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  '5k': 'five_k',
  '6k': 'six_k',
  '7k': 'seven_k',
  '8k': 'eight_k',
  '9k': 'nine_k',
  '10k': 'ten_k',
  '1k_plus': 'one_k_plus',
  '2k_plus': 'two_k_plus',
  '3k_plus': 'three_k_plus',
  '4k_plus': 'four_k_plus',
  '5k_plus': 'five_k_plus',
  '6k_plus': 'six_k_plus',
  '7k_plus': 'seven_k_plus',
  '8k_plus': 'eight_k_plus',
  '9k_plus': 'nine_k_plus',
  '1mp': 'one_mp',
  '2mp': 'two_mp',
  '3mp': 'three_mp',
  '4mp': 'four_mp',
  '5mp': 'five_mp',
  '6mp': 'six_mp',
  '7mp': 'seven_mp',
  '8mp': 'eight_mp',
  '9mp': 'nine_mp',
  '10mp': 'ten_mp',
  '11mp': 'eleven_mp',
  '12mp': 'twelve_mp',
  '13mp': 'thirteen_mp',
  '14mp': 'fourteen_mp',
  '15mp': 'fifteen_mp',
  '16mp': 'sixteen_mp',
  '17mp': 'seventeen_mp',
  '18mp': 'eighteen_mp',
  '19mp': 'nineteen_mp',
  '20mp': 'twenty_mp',
  '21mp': 'twenty_one_mp',
  '22mp': 'twenty_two_mp',
  '23mp': 'twenty_three_mp',
  '24mp': 'twenty_four_mp',
74 75 76
  'class': 'class_',
};

77
const Set<String> _mirroredIcons = <String>{
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  // This list is obtained from:
  // http://google.github.io/material-design-icons/#icons-in-rtl
  'arrow_back',
  'arrow_back_ios',
  'arrow_forward',
  'arrow_forward_ios',
  'arrow_left',
  'arrow_right',
  'assignment',
  'assignment_return',
  'backspace',
  'battery_unknown',
  'call_made',
  'call_merge',
  'call_missed',
  'call_missed_outgoing',
  'call_received',
  'call_split',
  'chevron_left',
  'chevron_right',
  'chrome_reader_mode',
  'device_unknown',
  'dvr',
  'event_note',
  'featured_play_list',
  'featured_video',
  'first_page',
  'flight_land',
  'flight_takeoff',
  'format_indent_decrease',
  'format_indent_increase',
  'format_list_bulleted',
  'forward',
  'functions',
  'help',
  'help_outline',
  'input',
  'keyboard_backspace',
  'keyboard_tab',
  'label',
  'label_important',
  'label_outline',
  'last_page',
  'launch',
  'list',
  'live_help',
  'mobile_screen_share',
  'multiline_chart',
  'navigate_before',
  'navigate_next',
  'next_week',
  'note',
  'open_in_new',
  'playlist_add',
  'queue_music',
  'redo',
  'reply',
  'reply_all',
  'screen_share',
  'send',
  'short_text',
  'show_chart',
  'sort',
  'star_half',
  'subject',
  'trending_flat',
  'toc',
  'trending_down',
  'trending_up',
  'undo',
  'view_list',
  'view_quilt',
  'wrap_text',
151
};
152

153 154 155 156 157
void main(List<String> args) {
  // If we're run from the `tools` dir, set the cwd to the repo root.
  if (path.basename(Directory.current.path) == 'tools')
    Directory.current = Directory.current.parent.parent;

158
  final ArgResults argResults = _handleArguments(args);
159

160 161 162 163 164 165 166 167
  final File iconClassFile = File(path.normalize(path.absolute(argResults[_iconsClassPathOption] as String)));
  if (!iconClassFile.existsSync()) {
    stderr.writeln('Error: Icons file not found: ${iconClassFile.path}');
    exit(1);
  }
  final File newCodepointsFile = File(path.absolute(path.normalize(argResults[_newCodepointsPathOption] as String)));
  if (!newCodepointsFile.existsSync()) {
    stderr.writeln('Error: New codepoints file not found: ${newCodepointsFile.path}');
168 169
    exit(1);
  }
170 171 172
  final File oldCodepointsFile = File(path.absolute(argResults[_oldCodepointsPathOption] as String));
  if (!oldCodepointsFile.existsSync()) {
    stderr.writeln('Error: Old codepoints file not found: ${oldCodepointsFile.path}');
173 174 175
    exit(1);
  }

176
  final String newCodepointsString = newCodepointsFile.readAsStringSync();
177
  final Map<String, String> newTokenPairMap = stringToTokenPairMap(newCodepointsString);
178 179

  final String oldCodepointsString = oldCodepointsFile.readAsStringSync();
180
  final Map<String, String> oldTokenPairMap = stringToTokenPairMap(oldCodepointsString);
181

182 183 184 185 186
  _testIsMapSuperset(newTokenPairMap, oldTokenPairMap);

  final String iconClassFileData = iconClassFile.readAsStringSync();

  stderr.writeln('Generating new token pairs.');
187
  final String newIconData = regenerateIconsFile(iconClassFileData, newTokenPairMap);
188 189

  if (argResults[_dryRunOption] as bool) {
190
    stdout.writeln(newIconData);
191 192 193 194 195
  } else {
    stderr.writeln('\nWriting to ${iconClassFile.path}.');
    iconClassFile.writeAsStringSync(newIconData);
    _cleanUpFiles(newCodepointsFile, oldCodepointsFile);
  }
196 197
}

198 199 200 201 202 203 204 205 206
ArgResults _handleArguments(List<String> args) {
  final ArgParser argParser = ArgParser()
    ..addOption(_newCodepointsPathOption, defaultsTo: _defaultNewCodepointsPath)
    ..addOption(_oldCodepointsPathOption, defaultsTo: _defaultOldCodepointsPath)
    ..addOption(_iconsClassPathOption, defaultsTo: _defaultIconsPath)
    ..addFlag(_dryRunOption, defaultsTo: false);
  return argParser.parse(args);
}

207 208
// Do not make this method private as it is used by g3 roll.
Map<String, String> stringToTokenPairMap(String codepointData) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
  final Iterable<String> cleanData = LineSplitter.split(codepointData)
      .map((String line) => line.trim())
      .where((String line) => line.isNotEmpty);

  final Map<String, String> pairs = <String, String>{};

  for (final String line in cleanData) {
    final List<String> tokens = line.split(' ');
    if (tokens.length != 2) {
      throw FormatException('Unexpected codepoint data: $line');
    }
    pairs.putIfAbsent(tokens[0], () => tokens[1]);
  }

  return pairs;
}

226 227
// Do not make this method private as it is used by g3 roll.
String regenerateIconsFile(String iconData, Map<String, String> tokenPairMap) {
228
  final StringBuffer buf = StringBuffer();
229
  bool generating = false;
230
  for (final String line in LineSplitter.split(iconData)) {
231
    if (!generating) {
232
      buf.writeln(line);
233 234
    }
    if (line.contains(_beginGeneratedMark)) {
235
      generating = true;
236 237 238 239 240 241 242 243

      final String iconDeclarationsString = <String>[
        for (MapEntry<String, String> entry in tokenPairMap.entries)
          _generateDeclaration(entry)
      ].join();

      buf.write(iconDeclarationsString);
    } else if (line.contains(_endGeneratedMark)) {
244 245 246 247 248 249 250
      generating = false;
      buf.writeln(line);
    }
  }
  return buf.toString();
}

251 252 253 254 255 256 257 258 259 260 261 262
void _testIsMapSuperset(Map<String, String> newCodepoints, Map<String, String> oldCodepoints) {
  final Set<String> newCodepointsSet = newCodepoints.keys.toSet();
  final Set<String> oldCodepointsSet = oldCodepoints.keys.toSet();

  if (!newCodepointsSet.containsAll(oldCodepointsSet)) {
    stderr.writeln(
      '''Error: New codepoints file does not contain all the existing codepoints.\n
        Missing: ${oldCodepointsSet.difference(newCodepointsSet)}
        ''',
    );
    exit(1);
  }
263 264
}

265 266 267 268 269 270
String _generateDeclaration(MapEntry<String, String> tokenPair) {
  final String identifier = _generateIdentifier(tokenPair.key);
  final String description = tokenPair.key.replaceAll('_', ' ');
  final String rtl = _mirroredIcons.contains(tokenPair.key)
      ? ', matchTextDirection: true'
      : '';
271 272
  return '''

273 274
  /// <i class="material-icons md-36">${tokenPair.key}</i> &#x2014; material icon named "$description".
  static const IconData $identifier = IconData(0x${tokenPair.value}, fontFamily: 'MaterialIcons'$rtl);
275 276
''';
}
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291

String _generateIdentifier(String rawIdentifier) {
  for (final MapEntry<String, String> rewritePair in _identifierRewrites.entries) {
    if (rawIdentifier.startsWith(rewritePair.key)) {
      return rawIdentifier.replaceFirst(rewritePair.key, _identifierRewrites[rewritePair.key]);
    }
  }
  return rawIdentifier;
}

// Replace the old codepoints file with the new.
void _cleanUpFiles(File newCodepointsFile, File oldCodepointsFile) {
  stderr.writeln('\nMoving new codepoints file to ${oldCodepointsFile.path}.\n');
  newCodepointsFile.renameSync(oldCodepointsFile.path);
}