Upstream version 6.34.113.0
[platform/framework/web/crosswalk.git] / src / xwalk / app / tools / android / make_apk.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2013, 2014 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.
6 # pylint: disable=F0401
7
8 import compress_js_and_css
9 import operator
10 import optparse
11 import os
12 import re
13 import shutil
14 import subprocess
15 import sys
16
17 sys.path.append('scripts/gyp')
18 from customize import ReplaceInvalidChars, CustomizeAll
19 from dex import AddExeExtensions
20 from handle_permissions import permission_mapping_table
21 from manifest_json_parser import HandlePermissionList
22 from manifest_json_parser import ManifestJsonParser
23
24 def CleanDir(path):
25   if os.path.exists(path):
26     shutil.rmtree(path)
27
28
29 def RunCommand(command, verbose=False, shell=False):
30   """Runs the command list, print the output, and propagate its result."""
31   proc = subprocess.Popen(command, stdout=subprocess.PIPE,
32                           stderr=subprocess.STDOUT, shell=shell)
33   if not shell:
34     output = proc.communicate()[0]
35     result = proc.returncode
36     if verbose:
37       print(output.decode("utf-8").strip())
38     if result != 0:
39       print ('Command "%s" exited with non-zero exit code %d'
40              % (' '.join(command), result))
41       sys.exit(result)
42
43
44 def Which(name):
45   """Search PATH for executable files with the given name."""
46   result = []
47   exts = [_f for _f in os.environ.get('PATHEXT', '').split(os.pathsep) if _f]
48   path = os.environ.get('PATH', None)
49   if path is None:
50     return []
51   for p in os.environ.get('PATH', '').split(os.pathsep):
52     p = os.path.join(p, name)
53     if os.access(p, os.X_OK):
54       result.append(p)
55     for e in exts:
56       pext = p + e
57       if os.access(pext, os.X_OK):
58         result.append(pext)
59   return result
60
61
62 def Find(name, path):
63   """Find executable file with the given name
64   and maximum API level under specific path."""
65   result = {}
66   for root, _, files in os.walk(path):
67     if name in files:
68       key = os.path.join(root, name)
69       sdk_version = os.path.basename(os.path.dirname(key))
70       str_num = re.search(r'\d+', sdk_version)
71       if str_num:
72         result[key] = int(str_num.group())
73       else:
74         result[key] = 0
75   if not result:
76     raise Exception()
77   return max(iter(result.items()), key=operator.itemgetter(1))[0]
78
79
80 def GetVersion(path):
81   """Get the version of this python tool."""
82   version_str = 'Crosswalk app packaging tool version is '
83   file_handle = open(path, 'r')
84   src_content = file_handle.read()
85   version_nums = re.findall(r'\d+', src_content)
86   version_str += ('.').join(version_nums)
87   file_handle.close()
88   return version_str
89
90
91 def ParseManifest(options):
92   parser = ManifestJsonParser(os.path.expanduser(options.manifest))
93   if not options.package:
94     options.package = 'org.xwalk.' + parser.GetAppName().lower()
95   if not options.name:
96     options.name = parser.GetAppName()
97   if not options.app_version:
98     options.app_version = parser.GetVersion()
99   if not options.app_versionCode and not options.app_versionCodeBase:
100     options.app_versionCode = 1
101   if parser.GetDescription():
102     options.description = parser.GetDescription()
103   if parser.GetPermissions():
104     options.permissions = parser.GetPermissions()
105   if parser.GetAppUrl():
106     options.app_url = parser.GetAppUrl()
107   elif parser.GetAppLocalPath():
108     options.app_local_path = parser.GetAppLocalPath()
109   else:
110     print('Error: there is no app launch path defined in manifest.json.')
111     sys.exit(9)
112   if parser.GetAppRoot():
113     options.app_root = parser.GetAppRoot()
114     options.icon_dict = parser.GetIcons()
115   if parser.GetFullScreenFlag().lower() == 'true':
116     options.fullscreen = True
117   elif parser.GetFullScreenFlag().lower() == 'false':
118     options.fullscreen = False
119   if parser.GetLaunchScreenImg():
120     options.launch_screen_img  = os.path.join(options.app_root,
121                                               parser.GetLaunchScreenImg())
122
123
124 def ParseXPK(options, out_dir):
125   cmd = ['python', 'parse_xpk.py',
126          '--file=%s' % os.path.expanduser(options.xpk),
127          '--out=%s' % out_dir]
128   RunCommand(cmd)
129   if options.manifest:
130     print ('Use the manifest from XPK by default '
131            'when "--xpk" option is specified, and '
132            'the "--manifest" option would be ignored.')
133     sys.exit(7)
134
135   if os.path.isfile(os.path.join(out_dir, 'manifest.json')):
136     options.manifest = os.path.join(out_dir, 'manifest.json')
137   else:
138     print('XPK doesn\'t contain manifest file.')
139     sys.exit(8)
140
141
142 def FindExtensionJars(root_path):
143   ''' Find all .jar files for external extensions. '''
144   extension_jars = []
145   if not os.path.exists(root_path):
146     return extension_jars
147
148   for afile in os.listdir(root_path):
149     if os.path.isdir(os.path.join(root_path, afile)):
150       base_name = os.path.basename(afile)
151       extension_jar = os.path.join(root_path, afile, base_name + '.jar')
152       if os.path.isfile(extension_jar):
153         extension_jars.append(extension_jar)
154   return extension_jars
155
156
157 # Follows the recommendation from
158 # http://software.intel.com/en-us/blogs/2012/11/12/how-to-publish-
159 # your-apps-on-google-play-for-x86-based-android-devices-using
160 def MakeVersionCode(options):
161   ''' Construct a version code'''
162   if options.app_versionCode:
163     return options.app_versionCode
164
165   # First digit is ABI, ARM=2, x86=6
166   abi = '0'
167   if options.arch == 'arm':
168     abi = '2'
169   if options.arch == 'x86':
170     abi = '6'
171   b = '0'
172   if options.app_versionCodeBase:
173     b = str(options.app_versionCodeBase)
174     if len(b) > 7:
175       print('Version code base must be 7 digits or less: '
176             'versionCodeBase=%s' % (b))
177       sys.exit(12)
178   # zero pad to 7 digits, middle digits can be used for other
179   # features, according to recommendation in URL
180   return '%s%s' % (abi, b.zfill(7))
181
182
183 def Customize(options):
184   package = 'org.xwalk.app.template'
185   if options.package:
186     package = options.package
187   name = 'AppTemplate'
188   if options.name:
189     name = options.name
190   app_version = ''
191   if options.app_version:
192     app_version = options.app_version
193   app_versionCode = MakeVersionCode(options)
194   app_root = ''
195   if options.app_root:
196     app_root = os.path.expanduser(options.app_root)
197   remote_debugging = ''
198   if options.enable_remote_debugging:
199     remote_debugging = '--enable-remote-debugging'
200   fullscreen_flag = ''
201   if options.fullscreen:
202     fullscreen_flag = '-f'
203   orientation = 'unspecified'
204   if options.orientation:
205     orientation = options.orientation
206   CustomizeAll(app_versionCode, options.description, options.icon_dict,
207                options.permissions, options.app_url, app_root,
208                options.app_local_path, remote_debugging,
209                fullscreen_flag, options.extensions,
210                options.launch_screen_img, package, name, app_version,
211                orientation)
212
213
214 def Execution(options, sanitized_name):
215   android_path_array = Which('android')
216   if not android_path_array:
217     print('Please install Android SDK first.')
218     sys.exit(1)
219
220   sdk_root_path = os.path.dirname(os.path.dirname(android_path_array[0]))
221
222   try:
223     sdk_jar_path = Find('android.jar', os.path.join(sdk_root_path, 'platforms'))
224   except Exception:
225     print('Your Android SDK may be ruined, please reinstall it.')
226     sys.exit(2)
227
228   level_string = os.path.basename(os.path.dirname(sdk_jar_path))
229   api_level = int(re.search(r'\d+', level_string).group())
230   if api_level < 14:
231     print('Please install Android API level (>=14) first.')
232     sys.exit(3)
233
234   if options.keystore_path:
235     key_store = os.path.expanduser(options.keystore_path)
236     if options.keystore_alias:
237       key_alias = options.keystore_alias
238     else:
239       print('Please provide an alias name of the developer key.')
240       sys.exit(6)
241     if options.keystore_passcode:
242       key_code = options.keystore_passcode
243     else:
244       print('Please provide the passcode of the developer key.')
245       sys.exit(6)
246   else:
247     print ('Use xwalk\'s keystore by default for debugging. '
248            'Please switch to your keystore when distributing it to app market.')
249     key_store = 'scripts/ant/xwalk-debug.keystore'
250     key_alias = 'xwalkdebugkey'
251     key_code = 'xwalkdebug'
252
253   if not os.path.exists('out'):
254     os.mkdir('out')
255
256   # Make sure to use ant-tasks.jar correctly.
257   # Default Android SDK names it as ant-tasks.jar
258   # Chrome third party Android SDk names it as anttasks.jar
259   ant_tasks_jar_path = os.path.join(sdk_root_path,
260                                     'tools', 'lib', 'ant-tasks.jar')
261   if not os.path.exists(ant_tasks_jar_path):
262     ant_tasks_jar_path = os.path.join(sdk_root_path,
263                                       'tools', 'lib' ,'anttasks.jar')
264
265   aapt_path = ''
266   for aapt_str in AddExeExtensions('aapt'):
267     try:
268       aapt_path = Find(aapt_str, sdk_root_path)
269       print('Use %s in %s.' % (aapt_str, sdk_root_path))
270       break
271     except Exception:
272       print('There doesn\'t exist %s in %s.' % (aapt_str, sdk_root_path))
273   if not aapt_path:
274     print('Your Android SDK may be ruined, please reinstall it.')
275     sys.exit(2)
276
277   # Check whether ant is installed.
278   try:
279     cmd = ['ant', '-version']
280     RunCommand(cmd, shell=True)
281   except EnvironmentError:
282     print('Please install ant first.')
283     sys.exit(4)
284
285   res_dirs = '-DADDITIONAL_RES_DIRS=\'\''
286   res_packages = '-DADDITIONAL_RES_PACKAGES=\'\''
287   res_r_text_files = '-DADDITIONAL_R_TEXT_FILES=\'\''
288   if options.mode == 'embedded':
289     # Prepare the .pak file for embedded mode.
290     pak_src_path = os.path.join('native_libs_res', 'xwalk.pak')
291     pak_des_path = os.path.join(sanitized_name, 'assets', 'xwalk.pak')
292     shutil.copy(pak_src_path, pak_des_path)
293
294     js_src_dir = os.path.join('native_libs_res', 'jsapi')
295     js_des_dir = os.path.join(sanitized_name, 'assets', 'jsapi')
296     if os.path.exists(js_des_dir):
297       shutil.rmtree(js_des_dir)
298     shutil.copytree(js_src_dir, js_des_dir)
299
300     res_ui_java = os.path.join('gen', 'ui_java')
301     res_content_java = os.path.join('gen', 'content_java')
302     res_xwalk_java = os.path.join('gen', 'xwalk_core_java')
303     res_dirs = ('-DADDITIONAL_RES_DIRS='
304                 + os.path.join(res_ui_java, 'res_crunched') + ' '
305                 + os.path.join(res_ui_java, 'res_v14_compatibility') + ' '
306                 + os.path.join(res_ui_java, 'res_grit') + ' '
307                 + os.path.join('libs_res', 'ui') + ' '
308                 + os.path.join(res_content_java, 'res_crunched') + ' '
309                 + os.path.join(res_content_java, 'res_v14_compatibility') + ' '
310                 + os.path.join('libs_res', 'content') + ' '
311                 + os.path.join(res_content_java, 'res_grit') + ' '
312                 + os.path.join(res_xwalk_java, 'res_crunched') + ' '
313                 + os.path.join(res_xwalk_java, 'res_v14_compatibility') + ' '
314                 + os.path.join('libs_res', 'runtime') + ' '
315                 + os.path.join(res_xwalk_java, 'res_grit'))
316     res_packages = ('-DADDITIONAL_RES_PACKAGES=org.chromium.ui '
317                     'org.xwalk.core org.chromium.content')
318     res_r_text_files = ('-DADDITIONAL_R_TEXT_FILES='
319                         + os.path.join(res_ui_java, 'java_R', 'R.txt') + ' '
320                         + os.path.join(res_xwalk_java, 'java_R', 'R.txt') + ' '
321                         + os.path.join(res_content_java, 'java_R', 'R.txt'))
322
323   resource_dir = '-DRESOURCE_DIR=' + os.path.join(sanitized_name, 'res')
324   manifest_path = os.path.join(sanitized_name, 'AndroidManifest.xml')
325   cmd = ['python', os.path.join('scripts', 'gyp', 'ant.py'),
326          '-DAAPT_PATH=%s' % aapt_path,
327          res_dirs,
328          res_packages,
329          res_r_text_files,
330          '-DANDROID_MANIFEST=%s' % manifest_path,
331          '-DANDROID_SDK_JAR=%s' % sdk_jar_path,
332          '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
333          '-DANDROID_SDK_VERSION=%d' % api_level,
334          '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
335          '-DLIBRARY_MANIFEST_PATHS= ',
336          '-DOUT_DIR=out',
337          resource_dir,
338          '-DSTAMP=codegen.stamp',
339          '-Dbasedir=.',
340          '-buildfile',
341          os.path.join('scripts', 'ant', 'apk-codegen.xml')]
342   RunCommand(cmd, options.verbose)
343
344   # Check whether java is installed.
345   try:
346     cmd = ['java', '-version']
347     RunCommand(cmd, shell=True)
348   except EnvironmentError:
349     print('Please install Oracle JDK first.')
350     sys.exit(5)
351
352   # Compile App source code with app runtime code.
353   classpath = '--classpath='
354   classpath += os.path.join(os.getcwd(), 'libs',
355                             'xwalk_app_runtime_java.jar')
356   classpath += ' ' + sdk_jar_path
357   src_dirs = '--src-dirs=' + os.path.join(os.getcwd(), sanitized_name, 'src') +\
358              ' ' + os.path.join(os.getcwd(), 'out', 'gen')
359   cmd = ['python', os.path.join('scripts', 'gyp', 'javac.py'),
360          '--output-dir=%s' % os.path.join('out', 'classes'),
361          classpath,
362          src_dirs,
363          '--javac-includes=',
364          '--chromium-code=0',
365          '--stamp=compile.stam']
366   RunCommand(cmd)
367
368   # Package resources.
369   asset_dir = '-DASSET_DIR=%s' % os.path.join(sanitized_name, 'assets')
370   xml_path = os.path.join('scripts', 'ant', 'apk-package-resources.xml')
371   cmd = ['python', os.path.join('scripts', 'gyp', 'ant.py'),
372          '-DAAPT_PATH=%s' % aapt_path,
373          res_dirs,
374          res_packages,
375          res_r_text_files,
376          '-DANDROID_SDK_JAR=%s' % sdk_jar_path,
377          '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
378          '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
379          '-DAPK_NAME=%s' % sanitized_name,
380          '-DAPP_MANIFEST_VERSION_CODE=0',
381          '-DAPP_MANIFEST_VERSION_NAME=Developer Build',
382          asset_dir,
383          '-DCONFIGURATION_NAME=Release',
384          '-DOUT_DIR=out',
385          resource_dir,
386          '-DSTAMP=package_resources.stamp',
387          '-Dbasedir=.',
388          '-buildfile',
389          xml_path]
390   RunCommand(cmd, options.verbose)
391
392   dex_path = '--dex-path=' + os.path.join(os.getcwd(), 'out', 'classes.dex')
393   app_runtime_jar = os.path.join(os.getcwd(),
394                                  'libs', 'xwalk_app_runtime_java.jar')
395
396   # Check whether external extensions are included.
397   extensions_string = 'xwalk-extensions'
398   extensions_dir = os.path.join(os.getcwd(), sanitized_name, extensions_string)
399   external_extension_jars = FindExtensionJars(extensions_dir)
400   input_jars = []
401   if options.mode == 'embedded':
402     input_jars.append(os.path.join(os.getcwd(), 'libs',
403                                    'xwalk_runtime_embedded.dex.jar'))
404   dex_command_list = ['python', os.path.join('scripts', 'gyp', 'dex.py'),
405                       dex_path,
406                       '--android-sdk-root=%s' % sdk_root_path,
407                       app_runtime_jar,
408                       os.path.join(os.getcwd(), 'out', 'classes')]
409   dex_command_list.extend(external_extension_jars)
410   dex_command_list.extend(input_jars)
411   RunCommand(dex_command_list)
412
413   src_dir = '-DSOURCE_DIR=' + os.path.join(sanitized_name, 'src')
414   apk_path = '-DUNSIGNED_APK_PATH=' + os.path.join('out', 'app-unsigned.apk')
415   native_lib_path = '-DNATIVE_LIBS_DIR='
416   if options.mode == 'embedded':
417     if options.arch == 'x86':
418       x86_native_lib_path = os.path.join('native_libs', 'x86', 'libs',
419                                          'x86', 'libxwalkcore.so')
420       if os.path.isfile(x86_native_lib_path):
421         native_lib_path += os.path.join('native_libs', 'x86', 'libs')
422       else:
423         print('Missing x86 native library for Crosswalk embedded APK. Abort!')
424         sys.exit(10)
425     elif options.arch == 'arm':
426       arm_native_lib_path = os.path.join('native_libs', 'armeabi-v7a', 'libs',
427                                          'armeabi-v7a', 'libxwalkcore.so')
428       if os.path.isfile(arm_native_lib_path):
429         native_lib_path += os.path.join('native_libs', 'armeabi-v7a', 'libs')
430       else:
431         print('Missing ARM native library for Crosswalk embedded APK. Abort!')
432         sys.exit(10)
433   # A space is needed for Windows.
434   native_lib_path += ' '
435   cmd = ['python', 'scripts/gyp/ant.py',
436          '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
437          '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
438          '-DAPK_NAME=%s' % sanitized_name,
439          '-DCONFIGURATION_NAME=Release',
440          native_lib_path,
441          '-DOUT_DIR=out',
442          src_dir,
443          apk_path,
444          '-Dbasedir=.',
445          '-buildfile',
446          'scripts/ant/apk-package.xml']
447   RunCommand(cmd, options.verbose)
448
449   apk_path = '--unsigned-apk-path=' + os.path.join('out', 'app-unsigned.apk')
450   final_apk_path = '--final-apk-path=' + \
451                    os.path.join('out', sanitized_name + '.apk')
452   cmd = ['python', 'scripts/gyp/finalize_apk.py',
453          '--android-sdk-root=%s' % sdk_root_path,
454          apk_path,
455          final_apk_path,
456          '--keystore-path=%s' % key_store,
457          '--keystore-alias=%s' % key_alias,
458          '--keystore-passcode=%s' % key_code]
459   RunCommand(cmd)
460
461   src_file = os.path.join('out', sanitized_name + '.apk')
462   package_name = options.name
463   if options.app_version:
464     package_name += ('_' + options.app_version)
465   if options.mode == 'shared':
466     dst_file = os.path.join(options.target_dir, '%s.apk' % package_name)
467   elif options.mode == 'embedded':
468     dst_file = os.path.join(options.target_dir,
469                             '%s_%s.apk' % (package_name, options.arch))
470   shutil.copyfile(src_file, dst_file)
471   CleanDir('out')
472   if options.mode == 'embedded':
473     os.remove(pak_des_path)
474
475
476 def PrintPackageInfo(target_dir, app_name, app_version, arch = ''):
477   package_name_version = os.path.join(target_dir, app_name)
478   if app_version != '':
479     package_name_version += ('_' + app_version)
480   if arch == '':
481     print ('A non-platform specific APK for the web application "%s" was '
482            'generated successfully at\n%s.apk. It requires a shared Crosswalk '
483            'Runtime to be present.'
484            % (app_name, package_name_version))
485   else:
486     print ('An APK for the web application "%s" including the Crosswalk '
487            'Runtime built for %s was generated successfully, which can be '
488            'found at\n%s_%s.apk.'
489            % (app_name, arch, package_name_version, arch))
490
491
492 def MakeApk(options, sanitized_name):
493   Customize(options)
494   app_version = ''
495   if options.app_version:
496     app_version = options.app_version
497   if options.mode == 'shared':
498     Execution(options, sanitized_name)
499     PrintPackageInfo(options.target_dir, sanitized_name, app_version)
500   elif options.mode == 'embedded':
501     if options.arch:
502       Execution(options, sanitized_name)
503       PrintPackageInfo(options.target_dir, sanitized_name,
504                        app_version, options.arch)
505     else:
506       # If the arch option is unspecified, all of available platform APKs
507       # will be generated.
508       valid_archs = ['x86', 'armeabi-v7a']
509       packaged_archs = []
510       for arch in valid_archs:
511         if os.path.isfile(os.path.join('native_libs', arch, 'libs',
512                                        arch, 'libxwalkcore.so')):
513           if arch.find('x86') != -1:
514             options.arch = 'x86'
515           elif arch.find('arm') != -1:
516             options.arch = 'arm'
517           Execution(options, sanitized_name)
518           packaged_archs.append(options.arch)
519       for arch in packaged_archs:
520         PrintPackageInfo(options.target_dir, sanitized_name,
521                          app_version, arch)
522   else:
523     print('Unknown mode for packaging the application. Abort!')
524     sys.exit(11)
525
526
527 def parse_optional_arg(default_value):
528   def func(option, value, values, parser):
529     del value
530     del values
531     if parser.rargs and not parser.rargs[0].startswith('-'):
532       val = parser.rargs[0]
533       parser.rargs.pop(0)
534     else:
535       val = default_value
536     setattr(parser.values, option.dest, val)
537   return func
538
539
540 def main(argv):
541   parser = optparse.OptionParser()
542   parser.add_option('-v', '--version', action='store_true',
543                     dest='version', default=False,
544                     help='The version of this python tool.')
545   parser.add_option('--verbose', action="store_true",
546                     dest='verbose', default=False,
547                     help='Print debug messages.')
548   info = ('The packaging mode of the web application. The value \'shared\' '
549           'means that the runtime is shared across multiple application '
550           'instances and that the runtime needs to be distributed separately. '
551           'The value \'embedded\' means that the runtime is embedded into the '
552           'application itself and distributed along with it.'
553           'Set the default mode as \'embedded\'. For example: --mode=embedded')
554   parser.add_option('--mode', default='embedded', help=info)
555   info = ('The target architecture of the embedded runtime. Supported values '
556           'are \'x86\' and \'arm\'. Note, if undefined, APKs for all possible '
557           'architestures will be generated.')
558   parser.add_option('--arch', help=info)
559   group = optparse.OptionGroup(parser, 'Application Source Options',
560       'This packaging tool supports 3 kinds of web application source: '
561       '1) XPK package; 2) manifest.json; 3) various command line options, '
562       'for example, \'--app-url\' for website, \'--app-root\' and '
563       '\'--app-local-path\' for local web application.')
564   info = ('The path of the XPK package. For example, --xpk=/path/to/xpk/file')
565   group.add_option('--xpk', help=info)
566   info = ('The manifest file with the detail description of the application. '
567           'For example, --manifest=/path/to/your/manifest/file')
568   group.add_option('--manifest', help=info)
569   info = ('The url of application. '
570           'This flag allows to package website as apk. For example, '
571           '--app-url=http://www.intel.com')
572   group.add_option('--app-url', help=info)
573   info = ('The root path of the web app. '
574           'This flag allows to package local web app as apk. For example, '
575           '--app-root=/root/path/of/the/web/app')
576   group.add_option('--app-root', help=info)
577   info = ('The relative path of entry file based on the value from '
578           '\'app_root\'. This flag should work with \'--app-root\' together. '
579           'For example, --app-local-path=/relative/path/of/entry/file')
580   group.add_option('--app-local-path', help=info)
581   parser.add_option_group(group)
582   group = optparse.OptionGroup(parser, 'Mandatory arguments',
583       'They are used for describing the APK information through '
584       'command line options.')
585   info = ('The apk name. For example, --name="Your Application Name"')
586   group.add_option('--name', help=info)
587   info = ('The package name. For example, '
588           '--package=com.example.YourPackage')
589   group.add_option('--package', help=info)
590   parser.add_option_group(group)
591   group = optparse.OptionGroup(parser, 'Optional arguments',
592       'They are used for various settings for applications through '
593       'command line options.')
594   info = ('The version name of the application. '
595           'For example, --app-version=1.0.0')
596   group.add_option('--app-version', help=info)
597   info = ('The version code of the application. '
598           'For example, --app-versionCode=24')
599   group.add_option('--app-versionCode', type='int', help=info)
600   info = ('The version code base of the application. Version code will '
601           'be made by adding a prefix based on architecture to the version '
602           'code base. For example, --app-versionCodeBase=24')
603   group.add_option('--app-versionCodeBase', type='int', help=info)
604   info = ('The description of the application. For example, '
605           '--description=YourApplicationDescription')
606   group.add_option('--description', help=info)
607   group.add_option('--enable-remote-debugging', action='store_true',
608                     dest='enable_remote_debugging', default=False,
609                     help = 'Enable remote debugging.')
610   info = ('The list of external extension paths splitted by OS separators. '
611           'The separators are \':\' , \';\' and \':\' on Linux, Windows and '
612           'Mac OS respectively. For example, '
613           '--extensions=/path/to/extension1:/path/to/extension2.')
614   group.add_option('--extensions', help=info)
615   group.add_option('-f', '--fullscreen', action='store_true',
616                    dest='fullscreen', default=False,
617                    help='Make application fullscreen.')
618   info = ('The path of application icon. '
619           'Such as: --icon=/path/to/your/customized/icon')
620   group.add_option('--icon', help=info)
621   info = ('The orientation of the web app\'s display on the device. '
622           'For example, --orientation=landscape. The default value is '
623           '\'unspecified\'. The permitted values are from Android: '
624           'http://developer.android.com/guide/topics/manifest/'
625           'activity-element.html#screen')
626   group.add_option('--orientation', help=info)
627   info = ('The list of permissions to be used by web application. For example, '
628           '--permissions=geolocation:webgl')
629   group.add_option('--permissions', help=info)
630   info = ('Packaging tool will move the output APKS to the target directory')
631   group.add_option('--target-dir', default=os.getcwd(), help=info)
632   parser.add_option_group(group)
633   group = optparse.OptionGroup(parser, 'Keystore Options',
634       'The keystore is a signature from web developer, it\'s used when '
635       'developer wants to distribute the applications.')
636   info = ('The path to the developer keystore. For example, '
637           '--keystore-path=/path/to/your/developer/keystore')
638   group.add_option('--keystore-path', help=info)
639   info = ('The alias name of keystore. For example, --keystore-alias=name')
640   group.add_option('--keystore-alias', help=info)
641   info = ('The passcode of keystore. For example, --keystore-passcode=code')
642   group.add_option('--keystore-passcode', help=info)
643   info = ('Minify and obfuscate javascript and css.'
644           '--compressor: compress javascript and css.'
645           '--compressor=js: compress javascript.'
646           '--compressor=css: compress css.')
647   group.add_option('--compressor', dest='compressor', action='callback',
648                    callback=parse_optional_arg('all'), help=info)
649   parser.add_option_group(group)
650   options, _ = parser.parse_args()
651   if len(argv) == 1:
652     parser.print_help()
653     return 0
654
655   # This option will not export to users.
656   # Initialize here and will be read from manifest.json.
657   options.launch_screen_img = ''
658
659   if options.version:
660     if os.path.isfile('VERSION'):
661       print(GetVersion('VERSION'))
662       return 0
663     else:
664       parser.error('Can\'t get version due to the VERSION file missing!')
665
666   xpk_temp_dir = ''
667   if options.xpk:
668     xpk_name = os.path.splitext(os.path.basename(options.xpk))[0]
669     xpk_temp_dir = xpk_name + '_xpk'
670     ParseXPK(options, xpk_temp_dir)
671
672   if options.app_root and not options.manifest:
673     manifest_path = os.path.join(options.app_root, 'manifest.json')
674     if os.path.exists(manifest_path):
675       print('Using manifest.json distributed with the application.')
676       options.manifest = manifest_path
677
678   if not options.manifest:
679     if not options.package:
680       parser.error('The package name is required! '
681                    'Please use "--package" option.')
682     if not options.name:
683       parser.error('The APK name is required! Please use "--name" option.')
684     if not ((options.app_url and not options.app_root
685         and not options.app_local_path) or ((not options.app_url)
686             and options.app_root and options.app_local_path)):
687       parser.error('The entry is required. If the entry is a remote url, '
688                    'please use "--app-url" option; If the entry is local, '
689                    'please use "--app-root" and '
690                    '"--app-local-path" options together!')
691     if options.permissions:
692       permission_list = options.permissions.split(':')
693     else:
694       print('Warning: all supported permissions on Android port are added. '
695             'Refer to https://github.com/crosswalk-project/'
696             'crosswalk-website/wiki/Crosswalk-manifest')
697       permission_list = permission_mapping_table.keys()
698     options.permissions = HandlePermissionList(permission_list)
699     options.icon_dict = {}
700   else:
701     try:
702       ParseManifest(options)
703     except SystemExit as ec:
704       return ec.code
705
706   if (options.app_root and options.app_local_path and not
707       os.path.isfile(os.path.join(options.app_root, options.app_local_path))):
708     print('Please make sure that the local path file of launching app '
709           'does exist.')
710     sys.exit(7)
711
712   options.name = ReplaceInvalidChars(options.name, 'apkname')
713   options.package = ReplaceInvalidChars(options.package)
714   sanitized_name = ReplaceInvalidChars(options.name, 'apkname')
715
716   if options.target_dir:
717     target_dir = os.path.abspath(os.path.expanduser(options.target_dir))
718     options.target_dir = target_dir
719     if not os.path.isdir(target_dir):
720       os.makedirs(target_dir)
721
722   try:
723     compress = compress_js_and_css.CompressJsAndCss(options.app_root)
724     if options.compressor == 'all':
725       compress.CompressJavaScript()
726       compress.CompressCss()
727     elif options.compressor == 'js':
728       compress.CompressJavaScript()
729     elif options.compressor == 'css':
730       compress.CompressCss()
731     MakeApk(options, sanitized_name)
732   except SystemExit as ec:
733     CleanDir(sanitized_name)
734     CleanDir('out')
735     if os.path.exists(xpk_temp_dir):
736       CleanDir(xpk_temp_dir)
737     return ec.code
738   return 0
739
740
741 if __name__ == '__main__':
742   sys.exit(main(sys.argv))