roll libyuv to r1450 from r1444. Adds direct YUY2ToNV12 and UYVYToNV12 conversions...
[chromium-blink-merge.git] / build / android / gyp / generate_v14_compatible_resources.py
blob9c8ff3b4e9d144acd7c1cf92f59e7efb51409480
1 #!/usr/bin/env python
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.
7 """Convert Android xml resources to API 14 compatible.
9 There are two reasons that we cannot just use API 17 attributes,
10 so we are generating another set of resources by this script.
12 1. paddingStart attribute can cause a crash on Galaxy Tab 2.
13 2. There is a bug that paddingStart does not override paddingLeft on
14 JB-MR1. This is fixed on JB-MR2. b/8654490
16 Therefore, this resource generation script can be removed when
17 we drop the support for JB-MR1.
19 Please refer to http://crbug.com/235118 for the details.
20 """
22 import optparse
23 import os
24 import re
25 import shutil
26 import sys
27 import xml.dom.minidom as minidom
29 from util import build_utils
31 # Note that we are assuming 'android:' is an alias of
32 # the namespace 'http://schemas.android.com/apk/res/android'.
34 GRAVITY_ATTRIBUTES = ('android:gravity', 'android:layout_gravity')
36 # Almost all the attributes that has "Start" or "End" in
37 # its name should be mapped.
38 ATTRIBUTES_TO_MAP = {'paddingStart' : 'paddingLeft',
39 'drawableStart' : 'drawableLeft',
40 'layout_alignStart' : 'layout_alignLeft',
41 'layout_marginStart' : 'layout_marginLeft',
42 'layout_alignParentStart' : 'layout_alignParentLeft',
43 'layout_toStartOf' : 'layout_toLeftOf',
44 'paddingEnd' : 'paddingRight',
45 'drawableEnd' : 'drawableRight',
46 'layout_alignEnd' : 'layout_alignRight',
47 'layout_marginEnd' : 'layout_marginRight',
48 'layout_alignParentEnd' : 'layout_alignParentRight',
49 'layout_toEndOf' : 'layout_toRightOf'}
51 ATTRIBUTES_TO_MAP = dict(['android:' + k, 'android:' + v] for k, v
52 in ATTRIBUTES_TO_MAP.iteritems())
54 ATTRIBUTES_TO_MAP_REVERSED = dict([v, k] for k, v
55 in ATTRIBUTES_TO_MAP.iteritems())
58 def IterateXmlElements(node):
59 """minidom helper function that iterates all the element nodes.
60 Iteration order is pre-order depth-first."""
61 if node.nodeType == node.ELEMENT_NODE:
62 yield node
63 for child_node in node.childNodes:
64 for child_node_element in IterateXmlElements(child_node):
65 yield child_node_element
68 def ParseAndReportErrors(filename):
69 try:
70 return minidom.parse(filename)
71 except Exception:
72 import traceback
73 traceback.print_exc()
74 sys.stderr.write('Failed to parse XML file: %s\n' % filename)
75 sys.exit(1)
78 def AssertNotDeprecatedAttribute(name, value, filename):
79 """Raises an exception if the given attribute is deprecated."""
80 msg = None
81 if name in ATTRIBUTES_TO_MAP_REVERSED:
82 msg = '{0} should use {1} instead of {2}'.format(filename,
83 ATTRIBUTES_TO_MAP_REVERSED[name], name)
84 elif name in GRAVITY_ATTRIBUTES and ('left' in value or 'right' in value):
85 msg = '{0} should use start/end instead of left/right for {1}'.format(
86 filename, name)
88 if msg:
89 msg += ('\nFor background, see: http://android-developers.blogspot.com/'
90 '2013/03/native-rtl-support-in-android-42.html\n'
91 'If you have a legitimate need for this attribute, discuss with '
92 'kkimlabs@chromium.org or newt@chromium.org')
93 raise Exception(msg)
96 def WriteDomToFile(dom, filename):
97 """Write the given dom to filename."""
98 build_utils.MakeDirectory(os.path.dirname(filename))
99 with open(filename, 'w') as f:
100 dom.writexml(f, '', ' ', '\n', encoding='utf-8')
103 def HasStyleResource(dom):
104 """Return True if the dom is a style resource, False otherwise."""
105 root_node = IterateXmlElements(dom).next()
106 return bool(root_node.nodeName == 'resources' and
107 list(root_node.getElementsByTagName('style')))
110 def ErrorIfStyleResourceExistsInDir(input_dir):
111 """If a style resource is in input_dir, raises an exception."""
112 for input_filename in build_utils.FindInDirectory(input_dir, '*.xml'):
113 dom = ParseAndReportErrors(input_filename)
114 if HasStyleResource(dom):
115 raise Exception('error: style file ' + input_filename +
116 ' should be under ' + input_dir +
117 '-v17 directory. Please refer to '
118 'http://crbug.com/243952 for the details.')
121 def GenerateV14LayoutResourceDom(dom, filename, assert_not_deprecated=True):
122 """Convert layout resource to API 14 compatible layout resource.
124 Args:
125 dom: Parsed minidom object to be modified.
126 filename: Filename that the DOM was parsed from.
127 assert_not_deprecated: Whether deprecated attributes (e.g. paddingLeft) will
128 cause an exception to be thrown.
130 Returns:
131 True if dom is modified, False otherwise.
133 is_modified = False
135 # Iterate all the elements' attributes to find attributes to convert.
136 for element in IterateXmlElements(dom):
137 for name, value in list(element.attributes.items()):
138 # Convert any API 17 Start/End attributes to Left/Right attributes.
139 # For example, from paddingStart="10dp" to paddingLeft="10dp"
140 # Note: gravity attributes are not necessary to convert because
141 # start/end values are backward-compatible. Explained at
142 # https://plus.sandbox.google.com/+RomanNurik/posts/huuJd8iVVXY?e=Showroom
143 if name in ATTRIBUTES_TO_MAP:
144 element.setAttribute(ATTRIBUTES_TO_MAP[name], value)
145 del element.attributes[name]
146 is_modified = True
147 elif assert_not_deprecated:
148 AssertNotDeprecatedAttribute(name, value, filename)
150 return is_modified
153 def GenerateV14StyleResourceDom(dom, filename, assert_not_deprecated=True):
154 """Convert style resource to API 14 compatible style resource.
156 Args:
157 dom: Parsed minidom object to be modified.
158 filename: Filename that the DOM was parsed from.
159 assert_not_deprecated: Whether deprecated attributes (e.g. paddingLeft) will
160 cause an exception to be thrown.
162 Returns:
163 True if dom is modified, False otherwise.
165 is_modified = False
167 for style_element in dom.getElementsByTagName('style'):
168 for item_element in style_element.getElementsByTagName('item'):
169 name = item_element.attributes['name'].value
170 value = item_element.childNodes[0].nodeValue
171 if name in ATTRIBUTES_TO_MAP:
172 item_element.attributes['name'].value = ATTRIBUTES_TO_MAP[name]
173 is_modified = True
174 elif assert_not_deprecated:
175 AssertNotDeprecatedAttribute(name, value, filename)
177 return is_modified
180 def GenerateV14LayoutResource(input_filename, output_v14_filename,
181 output_v17_filename):
182 """Convert API 17 layout resource to API 14 compatible layout resource.
184 It's mostly a simple replacement, s/Start/Left s/End/Right,
185 on the attribute names.
186 If the generated resource is identical to the original resource,
187 don't do anything. If not, write the generated resource to
188 output_v14_filename, and copy the original resource to output_v17_filename.
190 dom = ParseAndReportErrors(input_filename)
191 is_modified = GenerateV14LayoutResourceDom(dom, input_filename)
193 if is_modified:
194 # Write the generated resource.
195 WriteDomToFile(dom, output_v14_filename)
197 # Copy the original resource.
198 build_utils.MakeDirectory(os.path.dirname(output_v17_filename))
199 shutil.copy2(input_filename, output_v17_filename)
202 def GenerateV14StyleResource(input_filename, output_v14_filename):
203 """Convert API 17 style resources to API 14 compatible style resource.
205 Write the generated style resource to output_v14_filename.
206 It's mostly a simple replacement, s/Start/Left s/End/Right,
207 on the attribute names.
209 dom = ParseAndReportErrors(input_filename)
210 GenerateV14StyleResourceDom(dom, input_filename)
212 # Write the generated resource.
213 WriteDomToFile(dom, output_v14_filename)
216 def GenerateV14LayoutResourcesInDir(input_dir, output_v14_dir, output_v17_dir):
217 """Convert layout resources to API 14 compatible resources in input_dir."""
218 for input_filename in build_utils.FindInDirectory(input_dir, '*.xml'):
219 rel_filename = os.path.relpath(input_filename, input_dir)
220 output_v14_filename = os.path.join(output_v14_dir, rel_filename)
221 output_v17_filename = os.path.join(output_v17_dir, rel_filename)
222 GenerateV14LayoutResource(input_filename, output_v14_filename,
223 output_v17_filename)
226 def GenerateV14StyleResourcesInDir(input_dir, output_v14_dir):
227 """Convert style resources to API 14 compatible resources in input_dir."""
228 for input_filename in build_utils.FindInDirectory(input_dir, '*.xml'):
229 rel_filename = os.path.relpath(input_filename, input_dir)
230 output_v14_filename = os.path.join(output_v14_dir, rel_filename)
231 GenerateV14StyleResource(input_filename, output_v14_filename)
234 def ParseArgs():
235 """Parses command line options.
237 Returns:
238 An options object as from optparse.OptionsParser.parse_args()
240 parser = optparse.OptionParser()
241 parser.add_option('--res-dir',
242 help='directory containing resources '
243 'used to generate v14 compatible resources')
244 parser.add_option('--res-v14-compatibility-dir',
245 help='output directory into which '
246 'v14 compatible resources will be generated')
247 parser.add_option('--stamp', help='File to touch on success')
249 options, args = parser.parse_args()
251 if args:
252 parser.error('No positional arguments should be given.')
254 # Check that required options have been provided.
255 required_options = ('res_dir', 'res_v14_compatibility_dir')
256 build_utils.CheckOptions(options, parser, required=required_options)
257 return options
259 def GenerateV14Resources(res_dir, res_v14_dir):
260 for name in os.listdir(res_dir):
261 if not os.path.isdir(os.path.join(res_dir, name)):
262 continue
264 dir_pieces = name.split('-')
265 resource_type = dir_pieces[0]
266 qualifiers = dir_pieces[1:]
268 api_level_qualifier_index = -1
269 api_level_qualifier = ''
270 for index, qualifier in enumerate(qualifiers):
271 if re.match('v[0-9]+$', qualifier):
272 api_level_qualifier_index = index
273 api_level_qualifier = qualifier
274 break
276 # Android pre-v17 API doesn't support RTL. Skip.
277 if 'ldrtl' in qualifiers:
278 continue
280 input_dir = os.path.abspath(os.path.join(res_dir, name))
282 # We also need to copy the original v17 resource to *-v17 directory
283 # because the generated v14 resource will hide the original resource.
284 output_v14_dir = os.path.join(res_v14_dir, name)
285 output_v17_dir = os.path.join(res_v14_dir, name + '-v17')
287 # We only convert layout resources under layout*/, xml*/,
288 # and style resources under values*/.
289 if resource_type in ('layout', 'xml'):
290 if not api_level_qualifier:
291 GenerateV14LayoutResourcesInDir(input_dir, output_v14_dir,
292 output_v17_dir)
293 elif resource_type == 'values':
294 if api_level_qualifier == 'v17':
295 output_qualifiers = qualifiers[:]
296 del output_qualifiers[api_level_qualifier_index]
297 output_v14_dir = os.path.join(res_v14_dir,
298 '-'.join([resource_type] +
299 output_qualifiers))
300 GenerateV14StyleResourcesInDir(input_dir, output_v14_dir)
301 elif not api_level_qualifier:
302 ErrorIfStyleResourceExistsInDir(input_dir)
304 def main():
305 options = ParseArgs()
307 res_v14_dir = options.res_v14_compatibility_dir
309 build_utils.DeleteDirectory(res_v14_dir)
310 build_utils.MakeDirectory(res_v14_dir)
312 GenerateV14Resources(options.res_dir, res_v14_dir)
314 if options.stamp:
315 build_utils.Touch(options.stamp)
317 if __name__ == '__main__':
318 sys.exit(main())