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