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