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