3 # Copyright (c) 2013 Intel Corporation. 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 import compress_js_and_css
17 from app_info import AppInfo
18 from customize_launch_screen import CustomizeLaunchScreen
19 from handle_xml import AddElementAttribute
20 from handle_xml import AddElementAttributeAndText
21 from handle_xml import EditElementAttribute
22 from handle_xml import EditElementValueByNodeName
23 from handle_permissions import HandlePermissions
24 from xml.dom import minidom
27 def VerifyAppName(value, mode='default'):
29 sample = 'helloworld, hello world, hello_world, hello_world1'
30 regex = r'[a-zA-Z][\w ]*$'
33 print('To be safe, the length of package name or app name '
34 'should be less than 128.')
36 if mode == 'packagename':
37 regex = r'^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$'
38 descrpt = 'Each part of package'
39 sample = 'org.xwalk.example, org.xwalk.example_'
41 if not re.match(regex, value):
42 print('Error: %s name should be started with letters and should not '
43 'contain invalid characters.\n'
44 'It may contain letters, numbers, blank spaces and underscores\n'
45 'Sample: %s' % (descrpt, sample))
49 def ReplaceSpaceWithUnderscore(value):
50 return value.replace(' ', '_')
53 def ReplaceInvalidChars(value, mode='default'):
54 """ Replace the invalid chars with '_' for input string.
56 value: the original string.
57 mode: the target usage mode of original string.
60 invalid_chars = '\/:*?"<>|- '
61 elif mode == 'apkname':
62 invalid_chars = '\/:.*?"<>|- '
63 for c in invalid_chars:
64 if mode == 'apkname' and c in value:
65 print("Illegal character: '%s' is replaced with '_'" % c)
66 value = value.replace(c, '_')
70 def GetFilesByExt(path, ext, sub_dir=True):
71 if os.path.exists(path):
73 for name in os.listdir(path):
74 full_name = os.path.join(path, name)
75 st = os.lstat(full_name)
76 if stat.S_ISDIR(st.st_mode) and sub_dir:
77 file_list += GetFilesByExt(full_name, ext)
78 elif os.path.isfile(full_name):
79 if fnmatch.fnmatch(full_name, ext):
80 file_list.append(full_name)
86 def ParseParameterForCompressor(option, value, values, parser):
87 if ((not values or values.startswith('-'))
88 and value.find('--compressor') != -1):
91 if parser.rargs and not parser.rargs[0].startswith('-'):
94 setattr(parser.values, option.dest, val)
97 def CompressSourceFiles(app_root, compressor):
103 if compressor == 'all' or compressor == 'js':
104 js_list = GetFilesByExt(app_root, js_ext)
105 compress_js_and_css.CompressJavaScript(js_list)
107 if compressor == 'all' or compressor == 'css':
108 css_list = GetFilesByExt(app_root, css_ext)
109 compress_js_and_css.CompressCss(css_list)
112 def Prepare(app_info, compressor):
114 package = app_info.package
115 app_root = app_info.app_root
116 if os.path.exists(name):
118 shutil.copytree('app_src', name)
119 shutil.rmtree(os.path.join(name, 'src'))
120 src_root = os.path.join('app_src', 'src', 'org', 'xwalk', 'app', 'template')
121 src_activity = os.path.join(src_root, 'AppTemplateActivity.java')
122 if not os.path.isfile(src_activity):
123 print ('Please make sure that the java file'
124 ' of activity does exist.')
126 root_path = os.path.join(name, 'src', package.replace('.', os.path.sep))
127 if not os.path.exists(root_path):
128 os.makedirs(root_path)
129 dest_activity = name + 'Activity.java'
130 shutil.copyfile(src_activity, os.path.join(root_path, dest_activity))
132 assets_path = os.path.join(name, 'assets')
133 shutil.rmtree(assets_path)
134 os.makedirs(assets_path)
135 app_src_path = os.path.join(assets_path, 'www')
136 shutil.copytree(app_root, app_src_path)
138 CompressSourceFiles(app_src_path, compressor)
141 def CustomizeStringXML(name, description):
142 strings_path = os.path.join(name, 'res', 'values', 'strings.xml')
143 if not os.path.isfile(strings_path):
144 print ('Please make sure strings_xml'
145 ' exists under app_src folder.')
149 xmldoc = minidom.parse(strings_path)
150 AddElementAttributeAndText(xmldoc, 'string', 'name', 'description',
152 strings_file = open(strings_path, 'w')
153 xmldoc.writexml(strings_file, encoding='utf-8')
157 def CustomizeThemeXML(name, fullscreen, app_manifest):
158 theme_path = os.path.join(name, 'res', 'values', 'theme.xml')
159 if not os.path.isfile(theme_path):
160 print('Error: theme.xml is missing in the build tool.')
163 theme_xmldoc = minidom.parse(theme_path)
165 EditElementValueByNodeName(theme_xmldoc, 'item',
166 'android:windowFullscreen', 'true')
167 has_background = CustomizeLaunchScreen(app_manifest, name)
169 EditElementValueByNodeName(theme_xmldoc, 'item',
170 'android:windowBackground',
171 '@drawable/launchscreen_bg')
172 theme_file = open(theme_path, 'w')
173 theme_xmldoc.writexml(theme_file, encoding='utf-8')
177 def CustomizeXML(app_info, description, icon_dict, app_manifest, permissions):
178 app_version = app_info.app_version
179 app_versionCode = app_info.app_versionCode
181 orientation = app_info.orientation
182 package = app_info.package
183 original_name = app_info.original_name
184 manifest_path = os.path.join(name, 'AndroidManifest.xml')
185 if not os.path.isfile(manifest_path):
186 print ('Please make sure AndroidManifest.xml'
187 ' exists under app_src folder.')
190 CustomizeStringXML(name, description)
191 CustomizeThemeXML(name, app_info.fullscreen_flag, app_manifest)
192 xmldoc = minidom.parse(manifest_path)
193 EditElementAttribute(xmldoc, 'manifest', 'package', package)
195 EditElementAttribute(xmldoc, 'manifest', 'android:versionCode',
196 str(app_versionCode))
198 EditElementAttribute(xmldoc, 'manifest', 'android:versionName',
201 EditElementAttribute(xmldoc, 'manifest', 'android:description',
202 "@string/description")
203 HandlePermissions(permissions, xmldoc)
204 EditElementAttribute(xmldoc, 'application', 'android:label', original_name)
205 activity_name = package + '.' + name + 'Activity'
206 EditElementAttribute(xmldoc, 'activity', 'android:name', activity_name)
207 EditElementAttribute(xmldoc, 'activity', 'android:label', original_name)
209 EditElementAttribute(xmldoc, 'activity', 'android:screenOrientation',
211 icon_name = CustomizeIcon(name, app_info.app_root, app_info.icon, icon_dict)
213 EditElementAttribute(xmldoc, 'application', 'android:icon',
214 '@drawable/%s' % icon_name)
216 file_handle = open(os.path.join(name, 'AndroidManifest.xml'), 'w')
217 xmldoc.writexml(file_handle, encoding='utf-8')
221 def ReplaceString(file_path, src, dest):
222 file_handle = open(file_path, 'r')
223 src_content = file_handle.read()
225 file_handle = open(file_path, 'w')
226 dest_content = src_content.replace(src, dest)
227 file_handle.write(dest_content)
231 def SetVariable(file_path, string_line, variable, value):
232 function_string = ('%sset%s(%s);\n' %
233 (' ', variable, value))
234 temp_file_path = file_path + '.backup'
235 file_handle = open(temp_file_path, 'w+')
236 for line in open(file_path):
237 file_handle.write(line)
238 if (line.find(string_line) >= 0):
239 file_handle.write(function_string)
241 shutil.move(temp_file_path, file_path)
244 def CustomizeJava(app_info, app_url, app_local_path, keep_screen_on):
246 package = app_info.package
247 root_path = os.path.join(name, 'src', package.replace('.', os.path.sep))
248 dest_activity = os.path.join(root_path, name + 'Activity.java')
249 ReplaceString(dest_activity, 'org.xwalk.app.template', package)
250 ReplaceString(dest_activity, 'AppTemplate', name)
251 manifest_file = os.path.join(name, 'assets/www', 'manifest.json')
252 if os.path.isfile(manifest_file):
255 'loadAppFromUrl("file:///android_asset/www/index.html")',
256 'loadAppFromManifest("file:///android_asset/www/manifest.json")')
259 if re.search(r'^http(|s)', app_url):
260 ReplaceString(dest_activity, 'file:///android_asset/www/index.html',
263 if os.path.isfile(os.path.join(name, 'assets/www', app_local_path)):
264 ReplaceString(dest_activity, 'file:///android_asset/www/index.html',
265 'app://' + package + '/' + app_local_path)
267 print ('Please make sure that the relative path of entry file'
271 if app_info.remote_debugging:
272 SetVariable(dest_activity,
273 'public void onCreate(Bundle savedInstanceState)',
274 'RemoteDebugging', 'true')
275 if app_info.fullscreen_flag:
276 SetVariable(dest_activity,
277 'super.onCreate(savedInstanceState)',
278 'IsFullscreen', 'true')
282 'super.onCreate(savedInstanceState);',
283 'super.onCreate(savedInstanceState);\n ' +
284 'getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);')
287 def CopyExtensionFile(extension_name, suffix, src_path, dest_path):
288 # Copy the file from src_path into dest_path.
289 dest_extension_path = os.path.join(dest_path, extension_name)
290 if os.path.exists(dest_extension_path):
291 # TODO: Refine it by renaming it internally.
292 print('Error: duplicated extension names "%s" are found. Please rename it.'
296 os.mkdir(dest_extension_path)
298 file_name = extension_name + suffix
299 src_file = os.path.join(src_path, file_name)
300 dest_file = os.path.join(dest_extension_path, file_name)
301 if not os.path.isfile(src_file):
303 print('Error: %s is not found in %s.' % (file_name, src_path))
305 shutil.copyfile(src_file, dest_file)
308 def CustomizeExtensions(app_info, extensions):
309 """Copy the files from external extensions and merge them into APK.
311 The directory of one external extension should be like:
316 That means the name of the internal files should be the same as the
318 For .jar files, they'll be copied to xwalk-extensions/ and then
319 built into classes.dex in make_apk.py.
320 For .js files, they'll be copied into assets/xwalk-extensions/.
321 For .json files, the'll be merged into one file called
322 extensions-config.json and copied into assets/.
328 apk_assets_path = os.path.join(apk_path, 'assets')
329 extensions_string = 'xwalk-extensions'
331 # Set up the target directories and files.
332 dest_jar_path = os.path.join(apk_path, extensions_string)
333 os.mkdir(dest_jar_path)
334 dest_js_path = os.path.join(apk_assets_path, extensions_string)
335 os.mkdir(dest_js_path)
336 apk_extensions_json_path = os.path.join(apk_assets_path,
337 'extensions-config.json')
339 # Split the paths into a list.
340 extension_paths = extensions.split(os.pathsep)
341 extension_json_list = []
342 for source_path in extension_paths:
343 if not os.path.exists(source_path):
344 print('Error: can\'t find the extension directory \'%s\'.' % source_path)
346 # Remove redundant separators to avoid empty basename.
347 source_path = os.path.normpath(source_path)
348 extension_name = os.path.basename(source_path)
350 # Copy .jar file into xwalk-extensions.
351 CopyExtensionFile(extension_name, '.jar', source_path, dest_jar_path)
353 # Copy .js file into assets/xwalk-extensions.
354 CopyExtensionFile(extension_name, '.js', source_path, dest_js_path)
356 # Merge .json file into assets/xwalk-extensions.
357 file_name = extension_name + '.json'
358 src_file = os.path.join(source_path, file_name)
359 if not os.path.isfile(src_file):
360 print('Error: %s is not found in %s.' % (file_name, source_path))
363 src_file_handle = file(src_file)
364 src_file_content = src_file_handle.read()
365 json_output = json.JSONDecoder().decode(src_file_content)
366 # Below 3 properties are used by runtime. See extension manager.
367 # And 'permissions' will be merged.
368 if not ('name' in json_output and
369 'class' in json_output and
370 'jsapi' in json_output):
371 print ('Error: properties \'name\', \'class\' and \'jsapi\' in a json '
372 'file are mandatory.')
374 # Reset the path for JavaScript.
375 js_path_prefix = extensions_string + '/' + extension_name + '/'
376 json_output['jsapi'] = js_path_prefix + json_output['jsapi']
377 extension_json_list.append(json_output)
378 # Merge the permissions of extensions into AndroidManifest.xml.
379 manifest_path = os.path.join(name, 'AndroidManifest.xml')
380 xmldoc = minidom.parse(manifest_path)
381 if ('permissions' in json_output):
382 # Get used permission list to avoid repetition as "--permissions"
383 # option can also be used to declare used permissions.
385 usedPermissions = xmldoc.getElementsByTagName("uses-permission")
386 for used in usedPermissions:
387 existingList.append(used.getAttribute("android:name"))
389 # Add the permissions to manifest file if not used yet.
390 for p in json_output['permissions']:
391 if p in existingList:
393 AddElementAttribute(xmldoc, 'uses-permission', 'android:name', p)
394 existingList.append(p)
396 # Write to the manifest file to save the update.
397 file_handle = open(manifest_path, 'w')
398 xmldoc.writexml(file_handle, encoding='utf-8')
401 # Write configuration of extensions into the target extensions-config.json.
402 if extension_json_list:
403 extensions_string = json.JSONEncoder().encode(extension_json_list)
404 extension_json_file = open(apk_extensions_json_path, 'w')
405 extension_json_file.write(extensions_string)
406 extension_json_file.close()
409 def GenerateCommandLineFile(app_info, xwalk_command_line):
410 if xwalk_command_line == '':
412 assets_path = os.path.join(app_info.name, 'assets')
413 file_path = os.path.join(assets_path, 'xwalk-command-line')
414 command_line_file = open(file_path, 'w')
415 command_line_file.write('xwalk ' + xwalk_command_line)
418 def CustomizeIconByDict(name, app_root, icon_dict):
420 drawable_dict = {'ldpi': [1, 37], 'mdpi': [37, 72], 'hdpi': [72, 96],
421 'xhdpi': [96, 120], 'xxhdpi': [120, 144],
422 'xxxhdpi': [144, 168]}
427 icon_dict = dict((int(k), v) for k, v in icon_dict.items())
429 print('The key of icon in the manifest file should be a number.')
431 if len(icon_dict) > 0:
432 icon_list = sorted(icon_dict.iteritems(), key=lambda d: d[0])
433 for kd, vd in drawable_dict.iteritems():
434 for item in icon_list:
435 if item[0] >= vd[0] and item[0] < vd[1]:
436 drawable_path = os.path.join(name, 'res', 'drawable-' + kd)
437 if not os.path.exists(drawable_path):
438 os.makedirs(drawable_path)
439 icon = os.path.join(app_root, item[1])
440 if icon and os.path.isfile(icon):
441 icon_name = os.path.basename(icon)
442 icon_suffix = icon_name.split('.')[-1]
443 shutil.copyfile(icon, os.path.join(drawable_path,
444 'icon.' + icon_suffix))
446 elif icon and (not os.path.isfile(icon)):
447 print ('Error: Please make sure \"' + icon + '\" does exist!')
453 def CustomizeIconByOption(name, icon):
454 if os.path.isfile(icon):
455 drawable_path = os.path.join(name, 'res', 'drawable')
456 if not os.path.exists(drawable_path):
457 os.makedirs(drawable_path)
458 icon_file = os.path.basename(icon)
459 icon_file = ReplaceInvalidChars(icon_file)
460 shutil.copyfile(icon, os.path.join(drawable_path, icon_file))
461 icon_name = os.path.splitext(icon_file)[0]
464 print ('Error: Please make sure \"' + icon + '\" is a file!')
468 def CustomizeIcon(name, app_root, icon, icon_dict):
471 icon_name = CustomizeIconByOption(name, icon)
473 icon_name = CustomizeIconByDict(name, app_root, icon_dict)
477 def CustomizeAll(app_info, description, icon_dict, permissions, app_url,
478 app_local_path, keep_screen_on, extensions, app_manifest,
479 xwalk_command_line='', compressor=None):
481 Prepare(app_info, compressor)
482 CustomizeXML(app_info, description, icon_dict, app_manifest, permissions)
483 CustomizeJava(app_info, app_url, app_local_path, keep_screen_on)
484 CustomizeExtensions(app_info, extensions)
485 GenerateCommandLineFile(app_info, xwalk_command_line)
486 except SystemExit as ec:
487 print('Exiting with error code: %d' % ec.code)
492 parser = optparse.OptionParser()
493 info = ('The package name. Such as: '
494 '--package=com.example.YourPackage')
495 parser.add_option('--package', help=info)
496 info = ('The apk name. Such as: --name="Your Application Name"')
497 parser.add_option('--name', help=info)
498 info = ('The version of the app. Such as: --app-version=TheVersionNumber')
499 parser.add_option('--app-version', help=info)
500 info = ('The versionCode of the app. Such as: --app-versionCode=24')
501 parser.add_option('--app-versionCode', type='int', help=info)
502 info = ('The application description. Such as:'
503 '--description=YourApplicationdDescription')
504 parser.add_option('--description', help=info)
505 info = ('The permission list. Such as: --permissions="geolocation"'
506 'For more permissions, such as:'
507 '--permissions="geolocation:permission2"')
508 parser.add_option('--permissions', help=info)
509 info = ('The url of application. '
510 'This flag allows to package website as apk. Such as: '
511 '--app-url=http://www.intel.com')
512 parser.add_option('--app-url', help=info)
513 info = ('The root path of the web app. '
514 'This flag allows to package local web app as apk. Such as: '
515 '--app-root=/root/path/of/the/web/app')
516 parser.add_option('--app-root', help=info)
517 info = ('The reletive path of entry file based on |app_root|. '
518 'This flag should work with "--app-root" together. '
519 'Such as: --app-local-path=/reletive/path/of/entry/file')
520 parser.add_option('--app-local-path', help=info)
521 parser.add_option('--enable-remote-debugging', action='store_true',
522 dest='enable_remote_debugging', default=False,
523 help='Enable remote debugging.')
524 parser.add_option('-f', '--fullscreen', action='store_true',
525 dest='fullscreen', default=False,
526 help='Make application fullscreen.')
527 parser.add_option('--keep-screen-on', action='store_true', default=False,
528 help='Support keeping screen on')
529 info = ('The path list for external extensions separated by os separator.'
530 'On Linux and Mac, the separator is ":". On Windows, it is ";".'
531 'Such as: --extensions="/path/to/extension1:/path/to/extension2"')
532 parser.add_option('--extensions', help=info)
533 info = ('The orientation of the web app\'s display on the device. '
534 'Such as: --orientation=landscape. The default value is "unspecified"'
535 'The value options are the same as those on the Android: '
536 'http://developer.android.com/guide/topics/manifest/'
537 'activity-element.html#screen')
538 parser.add_option('--orientation', help=info)
539 parser.add_option('--manifest', help='The manifest path')
540 info = ('Use command lines.'
541 'Crosswalk is powered by Chromium and supports Chromium command line.'
543 '--xwalk-command-line=\'--chromium-command-1 --xwalk-command-2\'')
544 parser.add_option('--xwalk-command-line', default='', help=info)
545 info = ('Minify and obfuscate javascript and css.'
546 '--compressor: compress javascript and css.'
547 '--compressor=js: compress javascript.'
548 '--compressor=css: compress css.')
549 parser.add_option('--compressor', dest='compressor', action='callback',
550 callback=ParseParameterForCompressor,
551 type='string', nargs=0, help=info)
552 options, _ = parser.parse_args()
554 icon_dict = {144: 'icons/icon_144.png',
555 72: 'icons/icon_72.png',
556 96: 'icons/icon_96.png',
557 48: 'icons/icon_48.png'}
559 if options.name is not None:
560 app_info.name = options.name
561 if options.app_root is None:
562 app_info.app_root = os.path.join('test_data', 'manifest')
564 app_info.app_root = options.app_root
565 if options.package is not None:
566 app_info.package = options.package
567 if options.orientation is not None:
568 app_info.orientation = options.orientation
569 if options.app_version is not None:
570 app_info.app_version = options.app_version
571 if options.enable_remote_debugging is not None:
572 app_info.remote_debugging = options.enable_remote_debugging
573 if options.fullscreen is not None:
574 app_info.fullscreen_flag = options.fullscreen
575 app_info.icon = os.path.join('test_data', 'manifest', 'icons',
577 CustomizeAll(app_info, options.description, icon_dict,
578 options.permissions, options.app_url, options.app_local_path,
579 options.keep_screen_on, options.extensions, options.manifest,
580 options.xwalk_command_line, options.compressor)
581 except SystemExit as ec:
582 print('Exiting with error code: %d' % ec.code)
587 if __name__ == '__main__':