| OLD | NEW |
| (Empty) |
| 1 #!/usr/bin/env python | |
| 2 # | |
| 3 # Copyright 2013 The Chromium Authors. All rights reserved. | |
| 4 # Use of this source code is governed by a BSD-style license that can be | |
| 5 # found in the LICENSE file. | |
| 6 | |
| 7 """Mirrors (i.e. horizontally flips) images in the Android res folder for use | |
| 8 in right-to-left (RTL) mode on Android. | |
| 9 | |
| 10 Only some images are mirrored, as determined by the config file, typically | |
| 11 named mirror_images_config. The config file uses python syntax to define | |
| 12 two lists of image names: images_to_mirror and images_not_to_mirror. Images in | |
| 13 images_to_mirror will be mirrored by this tool. To ensure every image has been | |
| 14 considered for mirroring, the remaining images must be listed in | |
| 15 images_not_to_mirror. | |
| 16 | |
| 17 Mirrorable images include directional images (e.g. back and forward buttons) and | |
| 18 asymmetric UI elements (e.g. a left-to-right fade image). Non-mirrorable images | |
| 19 include images with text (e.g. the Chrome logo), symmetric images (e.g. a star | |
| 20 or X button), and images whose asymmetry is not critical to their meaning. Most | |
| 21 images do not need to be mirrored. | |
| 22 | |
| 23 Example mirror_images_config: | |
| 24 | |
| 25 images_to_mirror = ['back.png', 'forward.png', 'left_to_right_fade.png'] | |
| 26 images_not_to_mirror = ['star.png', 'chrome_logo.png', 'blank_page.png'] | |
| 27 | |
| 28 Source images are taken from input_dir/res/drawable-* folders, and the | |
| 29 generated images are saved into output_dir/res/drawable-ldrtl-* folders. For | |
| 30 example: input_dir/res/drawable-hdpi/back.png would be mirrored into | |
| 31 output_dir/res/drawable-ldrtl-hdpi/back.png. | |
| 32 """ | |
| 33 | |
| 34 import errno | |
| 35 import multiprocessing.pool | |
| 36 import optparse | |
| 37 import os | |
| 38 import subprocess | |
| 39 import sys | |
| 40 | |
| 41 from util import build_utils | |
| 42 | |
| 43 BUILD_ANDROID_DIR = os.path.join(os.path.dirname(__file__), '..') | |
| 44 sys.path.append(BUILD_ANDROID_DIR) | |
| 45 | |
| 46 from pylib import constants | |
| 47 | |
| 48 | |
| 49 class Image(object): | |
| 50 """Represents an image in the Android res directory.""" | |
| 51 | |
| 52 def __init__(self, drawable_dir, name): | |
| 53 # The image's directory, e.g. drawable-hdpi | |
| 54 self.drawable_dir = drawable_dir | |
| 55 # The image's filename, e.g. star.png | |
| 56 self.name = name | |
| 57 | |
| 58 | |
| 59 class ConfigError(Exception): | |
| 60 """Error raised when images can't be mirrored because of problems with the | |
| 61 config file.""" | |
| 62 | |
| 63 def __init__(self, error_messages): | |
| 64 # A list of strings describing the errors in the config file. | |
| 65 self.error_messages = error_messages | |
| 66 | |
| 67 | |
| 68 class Project(object): | |
| 69 """This class knows how to read the config file and mirror images in an | |
| 70 Android project.""" | |
| 71 | |
| 72 def __init__(self, config_file, input_res_dir, output_res_dir): | |
| 73 """Args: | |
| 74 config_file: The config file specifying which images will be mirrored. | |
| 75 input_res_dir: The directory containing source images to be mirrored. | |
| 76 output_res_dir: The directory into which mirrored images can be saved. | |
| 77 """ | |
| 78 self.config_file = config_file | |
| 79 self.input_res_dir = input_res_dir | |
| 80 self.output_res_dir = output_res_dir | |
| 81 | |
| 82 # List of names of images that will be mirrored, from config file. | |
| 83 self.images_to_mirror = None | |
| 84 # List of names of images that will not be mirrored, from config file. | |
| 85 self.images_not_to_mirror = None | |
| 86 # List of all images found in res/drawable* directories. | |
| 87 self.images = None | |
| 88 | |
| 89 def mirror_images(self): | |
| 90 """Mirrors images in the project according to the configuration. | |
| 91 | |
| 92 If the project configuration contains any errors, this will raise a | |
| 93 ConfigError exception containing a list of errors that must be addressed | |
| 94 manually before any images can be mirrored. | |
| 95 """ | |
| 96 self._read_config_file() | |
| 97 self._read_drawable_dirs() | |
| 98 self._verify_config() | |
| 99 self._mirror_images() | |
| 100 | |
| 101 def _read_config_file(self): | |
| 102 """Reads the lists of images that should and should not be mirrored from the | |
| 103 config file. | |
| 104 """ | |
| 105 exec_env = {} | |
| 106 execfile(self.config_file, exec_env) | |
| 107 self.images_to_mirror = exec_env.get('images_to_mirror') | |
| 108 self.images_not_to_mirror = exec_env.get('images_not_to_mirror') | |
| 109 errors = [] | |
| 110 self._verify_config_list_well_formed(self.images_to_mirror, | |
| 111 'images_to_mirror', errors) | |
| 112 self._verify_config_list_well_formed(self.images_not_to_mirror, | |
| 113 'images_not_to_mirror', errors) | |
| 114 if errors: | |
| 115 raise ConfigError(errors) | |
| 116 | |
| 117 def _verify_config_list_well_formed(self, config_list, list_name, errors): | |
| 118 """Checks that config_list is a list of strings. If not, appends error | |
| 119 messages to errors.""" | |
| 120 if type(config_list) != list: | |
| 121 errors.append('The config file must contain a list named ' + list_name) | |
| 122 else: | |
| 123 for item in config_list: | |
| 124 if not isinstance(item, basestring): | |
| 125 errors.append('List {0} contains a non-string item: {1}' | |
| 126 .format(list_name, item)) | |
| 127 | |
| 128 def _read_drawable_dirs(self): | |
| 129 """Gets the list of images in the input drawable directories.""" | |
| 130 self.images = [] | |
| 131 | |
| 132 for dir_name in os.listdir(self.input_res_dir): | |
| 133 dir_components = dir_name.split('-') | |
| 134 if dir_components[0] != 'drawable' or 'ldrtl' in dir_components[1:]: | |
| 135 continue | |
| 136 dir_path = os.path.join(self.input_res_dir, dir_name) | |
| 137 if not os.path.isdir(dir_path): | |
| 138 continue | |
| 139 | |
| 140 for image_name in os.listdir(dir_path): | |
| 141 if image_name.endswith('.png'): | |
| 142 self.images.append(Image(dir_name, image_name)) | |
| 143 | |
| 144 def _verify_config(self): | |
| 145 """Checks the config file for errors. Raises a ConfigError if errors are | |
| 146 found.""" | |
| 147 errors = [] | |
| 148 | |
| 149 # Ensure images_to_mirror and images_not_to_mirror are sorted with no | |
| 150 # duplicates. | |
| 151 for l in self.images_to_mirror, self.images_not_to_mirror: | |
| 152 for i in range(len(l) - 1): | |
| 153 if l[i + 1] == l[i]: | |
| 154 errors.append(l[i + 1] + ' is listed multiple times') | |
| 155 elif l[i + 1] < l[i]: | |
| 156 errors.append(l[i + 1] + ' is not in sorted order') | |
| 157 | |
| 158 # Ensure no overlap between images_to_mirror and images_not_to_mirror. | |
| 159 overlap = set(self.images_to_mirror).intersection(self.images_not_to_mirror) | |
| 160 for item in sorted(overlap): | |
| 161 errors.append(item + ' appears in both lists.') | |
| 162 | |
| 163 # Ensure all images in res/drawable* folders are listed in config file. | |
| 164 images_in_config = set(self.images_to_mirror + self.images_not_to_mirror) | |
| 165 images_in_res_dir = [i.name for i in self.images] | |
| 166 images_missing_from_config = set(images_in_res_dir).difference( | |
| 167 images_in_config) | |
| 168 for image_name in sorted(images_missing_from_config): | |
| 169 errors.append(image_name + ' exists in a res/drawable* folder but is not ' | |
| 170 'listed in the config file. Update the config file to specify ' | |
| 171 'whether this image should be mirrored for right-to-left layouts (or ' | |
| 172 'delete the image).') | |
| 173 | |
| 174 # Ensure only images in res/drawable* folders are listed in config file. | |
| 175 images_not_in_res_dir = set(images_in_config).difference( | |
| 176 images_in_res_dir) | |
| 177 for image_name in sorted(images_not_in_res_dir): | |
| 178 errors.append(image_name + ' is listed in the config file, but does not ' | |
| 179 'exist in any res/drawable* folders. Remove this image name from the ' | |
| 180 'config file (or add the image to a drawable folder).') | |
| 181 | |
| 182 if errors: | |
| 183 raise ConfigError(errors) | |
| 184 | |
| 185 def _mirror_image(self, image): | |
| 186 ltr_path = os.path.join(self.input_res_dir, image.drawable_dir, image.name) | |
| 187 rtl_path = os.path.join(self.output_res_dir, | |
| 188 get_rtl_dir(image.drawable_dir), image.name) | |
| 189 build_utils.MakeDirectory(os.path.dirname(rtl_path)) | |
| 190 mirror_image(ltr_path, rtl_path) | |
| 191 | |
| 192 def _mirror_images(self): | |
| 193 pool = multiprocessing.pool.ThreadPool() | |
| 194 images_to_mirror = [i for i in self.images if | |
| 195 i.name in self.images_to_mirror] | |
| 196 pool.map(self._mirror_image, images_to_mirror) | |
| 197 | |
| 198 | |
| 199 def get_rtl_dir(drawable_dir_ltr): | |
| 200 """Returns the RTL drawable directory corresponding to drawable_dir_ltr. | |
| 201 | |
| 202 Example: | |
| 203 drawable-hdpi -> drawable-ldrtl-hdpi | |
| 204 """ | |
| 205 dir_components = drawable_dir_ltr.split('-') | |
| 206 assert 'ldrtl' not in dir_components | |
| 207 # ldrtl is always the first qualifier, as long as mobile country code or | |
| 208 # language and region aren't used as qualifiers: | |
| 209 # http://developer.android.com/guide/topics/resources/providing-resources.html | |
| 210 dir_components.insert(1, 'ldrtl') | |
| 211 return '-'.join(dir_components) | |
| 212 | |
| 213 | |
| 214 def mirror_image(src_path, dst_path): | |
| 215 """Mirrors a single image horizontally. 9-patches are treated specially: the | |
| 216 left and right edges of a 9-patch are not mirrored. | |
| 217 | |
| 218 Args: | |
| 219 src_path: The image to be mirrored. | |
| 220 dst_path: The path where the mirrored image will be saved. | |
| 221 """ | |
| 222 try: | |
| 223 if src_path.endswith('.9.png'): | |
| 224 build_utils.CheckOutput(['convert', src_path, | |
| 225 '(', '+clone', '-flop', '-shave', '1x0', ')', | |
| 226 '-compose', 'Copy', | |
| 227 '-geometry', '+1+0', | |
| 228 '-composite', dst_path]) | |
| 229 else: | |
| 230 build_utils.CheckOutput(['convert', '-flop', src_path, dst_path]) | |
| 231 except OSError as e: | |
| 232 if e.errno == errno.ENOENT: | |
| 233 raise Exception('Executable "convert" (from the imagemagick package) not ' | |
| 234 'found. Run build/install-build-deps-android.sh and ensure ' | |
| 235 'that "convert" is on your path.') | |
| 236 raise | |
| 237 | |
| 238 | |
| 239 def parse_args(args=None): | |
| 240 parser = optparse.OptionParser() | |
| 241 parser.add_option('--config-file', help='Configuration file specifying which ' | |
| 242 'images should be mirrored') | |
| 243 parser.add_option('--input-res-dir', help='The res folder containing the ' | |
| 244 'source images.') | |
| 245 parser.add_option('--output-res-dir', help='The res folder into which ' | |
| 246 'mirrored images will be saved.') | |
| 247 | |
| 248 if args is None: | |
| 249 args = sys.argv[1:] | |
| 250 options, args = parser.parse_args(args) | |
| 251 | |
| 252 # Check that required options have been provided. | |
| 253 required_options = ('config_file', 'input_res_dir', 'output_res_dir') | |
| 254 build_utils.CheckOptions(options, parser, required=required_options) | |
| 255 | |
| 256 return options | |
| 257 | |
| 258 | |
| 259 def main(args=None): | |
| 260 options = parse_args(args) | |
| 261 project = Project(options.config_file, options.input_res_dir, | |
| 262 options.output_res_dir) | |
| 263 try: | |
| 264 project.mirror_images() | |
| 265 except ConfigError as e: | |
| 266 sys.stderr.write('\nFailed to mirror images for RTL layouts.\n') | |
| 267 sys.stderr.write('{0} error(s) in config file {1}:\n'.format( | |
| 268 len(e.error_messages), | |
| 269 os.path.relpath(options.config_file, constants.DIR_SOURCE_ROOT))) | |
| 270 for error_message in e.error_messages: | |
| 271 sys.stderr.write(' - {0}\n'.format(error_message)) | |
| 272 sys.stderr.write('For more information on mirroring images, read the ' | |
| 273 'header comment in build/android/gyp/mirror_images.py.\n') | |
| 274 sys.exit(1) | |
| 275 | |
| 276 | |
| 277 if __name__ == '__main__': | |
| 278 main() | |
| OLD | NEW |