Upstream version 10.38.217.0
[platform/framework/web/crosswalk.git] / src / xwalk / app / tools / android / make_apk.py
index 450da42..b94b6cd 100755 (executable)
@@ -5,47 +5,49 @@
 # found in the LICENSE file.
 # pylint: disable=F0401
 
-import operator
+import json
 import optparse
 import os
 import re
 import shutil
 import subprocess
 import sys
+import tempfile
 
-sys.path.append('scripts/gyp')
+# get xwalk absolute path so we can run this script from any location
+xwalk_dir = os.path.dirname(os.path.abspath(__file__))
+sys.path.append(xwalk_dir)
 
 from app_info import AppInfo
-from customize import VerifyAppName, CustomizeAll, \
-                      ParseParameterForCompressor, ReplaceSpaceWithUnderscore
-from dex import AddExeExtensions
+from customize import VerifyPackageName, CustomizeAll, \
+                      ParseParameterForCompressor
+from extension_manager import GetExtensionList, GetExtensionStatus
 from handle_permissions import permission_mapping_table
+from util import AllArchitectures, CleanDir, GetVersion, RunCommand, \
+                 CreateAndCopyDir
 from manifest_json_parser import HandlePermissionList
 from manifest_json_parser import ManifestJsonParser
 
 
-def CleanDir(path):
-  if os.path.exists(path):
-    shutil.rmtree(path)
+NATIVE_LIBRARY = 'libxwalkcore.so'
 
 
-def AllArchitectures():
-  return ("x86", "arm")
+def ConvertArchNameToArchFolder(arch):
+  arch_dict = {
+      'x86': 'x86',
+      'arm': 'armeabi-v7a'
+  }
+  return arch_dict.get(arch, None)
 
 
-def RunCommand(command, verbose=False, shell=False):
-  """Runs the command list, print the output, and propagate its result."""
-  proc = subprocess.Popen(command, stdout=subprocess.PIPE,
-                          stderr=subprocess.STDOUT, shell=shell)
-  if not shell:
-    output = proc.communicate()[0]
-    result = proc.returncode
-    if verbose:
-      print(output.decode("utf-8").strip())
-    if result != 0:
-      print ('Command "%s" exited with non-zero exit code %d'
-             % (' '.join(command), result))
-      sys.exit(result)
+def AddExeExtensions(name):
+  exts_str = os.environ.get('PATHEXT', '').lower()
+  exts = [_f for _f in exts_str.split(os.pathsep) if _f]
+  result = []
+  for e in exts:
+    result.append(name + e)
+  result.append(name)
+  return result
 
 
 def Which(name):
@@ -60,52 +62,25 @@ def Which(name):
   return None
 
 
-def Find(name, path):
-  """Find executable file with the given name
-  and maximum API level under specific path."""
-  result = {}
-  for root, _, files in os.walk(path):
-    if name in files:
-      key = os.path.join(root, name)
-      sdk_version = os.path.basename(os.path.dirname(key))
-      str_num = re.search(r'\d+', sdk_version)
-      if str_num:
-        result[key] = int(str_num.group())
-      else:
-        result[key] = 0
-  if not result:
-    raise Exception()
-  return max(iter(result.items()), key=operator.itemgetter(1))[0]
+def GetAndroidApiLevel(android_path):
+  """Get Highest Android target level installed.
+     return -1 if no targets have been found.
+  """
+  target_output = RunCommand([android_path, 'list', 'target', '-c'])
+  target_regex = re.compile(r'android-(\d+)')
+  targets = [int(i) for i in target_regex.findall(target_output)]
+  targets.extend([-1])
+  return max(targets)
 
 
-def GetVersion(path):
-  """Get the version of this python tool."""
-  version_str = 'Crosswalk app packaging tool version is '
-  file_handle = open(path, 'r')
-  src_content = file_handle.read()
-  version_nums = re.findall(r'\d+', src_content)
-  version_str += ('.').join(version_nums)
-  file_handle.close()
-  return version_str
+def ContainsNativeLibrary(path):
+  return os.path.isfile(os.path.join(path, NATIVE_LIBRARY))
 
 
-def ParseManifest(options, app_info):
+def ParseManifest(options):
   parser = ManifestJsonParser(os.path.expanduser(options.manifest))
-  original_name = app_info.original_name = parser.GetAppName()
-  app_name = None
-  if options.package:
-    VerifyAppName(options.package, 'packagename')
-  else:
-    VerifyAppName(original_name)
-    app_name = ReplaceSpaceWithUnderscore(original_name)
-    options.package = 'org.xwalk.' + app_name.lower()
-  if options.name:
-    VerifyAppName(options.name)
-    app_info.original_name = options.name
-    options.name = ReplaceSpaceWithUnderscore(options.name)
-  else:
-    VerifyAppName(original_name)
-    options.name = ReplaceSpaceWithUnderscore(original_name)
+  if not options.name:
+    options.name = parser.GetAppName()
   if not options.app_version:
     options.app_version = parser.GetVersion()
   if not options.app_versionCode and not options.app_versionCodeBase:
@@ -130,10 +105,11 @@ def ParseManifest(options, app_info):
     options.fullscreen = True
   elif parser.GetFullScreenFlag().lower() == 'false':
     options.fullscreen = False
+  return parser
 
 
 def ParseXPK(options, out_dir):
-  cmd = ['python', 'parse_xpk.py',
+  cmd = ['python', os.path.join(xwalk_dir, 'parse_xpk.py'),
          '--file=%s' % os.path.expanduser(options.xpk),
          '--out=%s' % out_dir]
   RunCommand(cmd)
@@ -191,11 +167,39 @@ def MakeVersionCode(options):
   return '%s%s' % (abi, b.zfill(7))
 
 
-def Customize(options, app_info):
-  if options.package:
-    app_info.package = options.package
-  if options.name:
-    app_info.name = options.name
+def GetExtensionBinaryPathList():
+  local_extension_list = []
+  extensions_path = os.path.join(os.getcwd(), "extensions")
+  exist_extension_list = GetExtensionList(extensions_path)
+  for item in exist_extension_list:
+    build_json_path = os.path.join(extensions_path, item, "build.json")
+    with open(build_json_path) as fd:
+      data = json.load(fd)
+    if not GetExtensionStatus(item, extensions_path):
+      continue
+    else:
+      if data.get("binary_path", False):
+        extension_binary_path = os.path.join(extensions_path,
+                                             item,
+                                             data["binary_path"])
+      else:
+        print("The extension \"%s\" doesn't exists." % item)
+        sys.exit(1)
+    if os.path.isdir(extension_binary_path):
+      local_extension_list.append(extension_binary_path)
+    else:
+      print("The extension \"%s\" doesn't exists." % item)
+      sys.exit(1)
+
+  return local_extension_list
+
+
+def Customize(options, app_info, manifest):
+  app_info.package = options.package
+  app_info.app_name = options.name
+  # 'org.xwalk.my_first_app' => 'MyFirstApp'
+  android_name = options.package.split('.')[-1].split('_')
+  app_info.android_name = ''.join([i.capitalize() for i in android_name if i])
   if options.app_version:
     app_info.app_version = options.app_version
   app_info.app_versionCode = MakeVersionCode(options)
@@ -203,40 +207,44 @@ def Customize(options, app_info):
     app_info.app_root = os.path.expanduser(options.app_root)
   if options.enable_remote_debugging:
     app_info.remote_debugging = '--enable-remote-debugging'
+  if options.use_animatable_view:
+    app_info.use_animatable_view = '--use-animatable-view'
   if options.fullscreen:
     app_info.fullscreen_flag = '-f'
   if options.orientation:
     app_info.orientation = options.orientation
   if options.icon:
     app_info.icon = '%s' % os.path.expanduser(options.icon)
+
+  #Add local extensions to extension list.
+  extension_binary_path_list = GetExtensionBinaryPathList()
+  if len(extension_binary_path_list) > 0:
+    if options.extensions is None:
+      options.extensions = ""
+    else:
+      options.extensions += os.pathsep
+
+    for item in extension_binary_path_list:
+      options.extensions += item
+      options.extensions += os.pathsep
+    #trim final path separator
+    options.extensions = options.extensions[0:-1]
+
   CustomizeAll(app_info, options.description, options.icon_dict,
                options.permissions, options.app_url, options.app_local_path,
-               options.keep_screen_on, options.extensions, options.manifest,
+               options.keep_screen_on, options.extensions, manifest,
                options.xwalk_command_line, options.compressor)
 
 
 def Execution(options, name):
+  arch_string = (' ('+options.arch+')' if options.arch else '')
+  print('\nStarting application build' + arch_string)
+  app_dir = os.path.join(tempfile.gettempdir(), name)
   android_path = Which('android')
-  if android_path is None:
-    print('The "android" binary could not be found. Check your Android SDK '
-          'installation and your PATH environment variable.')
-    sys.exit(1)
-
-  sdk_root_path = os.path.dirname(os.path.dirname(android_path))
-
-  try:
-    sdk_jar_path = Find('android.jar',
-                        os.path.join(sdk_root_path, 'platforms'))
-  except Exception:
-    print('Your Android SDK may be ruined, please reinstall it.')
-    sys.exit(2)
-
-  level_string = os.path.basename(os.path.dirname(sdk_jar_path))
-  api_level = int(re.search(r'\d+', level_string).group())
-  if api_level < 14:
-    print('Please install Android API level (>=14) first.')
-    sys.exit(3)
+  api_level = GetAndroidApiLevel(android_path)
+  target_string = 'android-%d' % api_level
 
+  print (' * Checking keystore for signing')
   if options.keystore_path:
     key_store = os.path.expanduser(options.keystore_path)
     if options.keystore_alias:
@@ -247,247 +255,100 @@ def Execution(options, name):
     if options.keystore_passcode:
       key_code = options.keystore_passcode
     else:
-      print('Please provide the passcode of the developer key.')
-      sys.exit(6)
+      key_code = None
+    if options.keystore_alias_passcode:
+      key_alias_code = options.keystore_alias_passcode
+    else:
+      key_alias_code = None
   else:
-    print ('Use xwalk\'s keystore by default for debugging. '
-           'Please switch to your keystore when distributing it to app market.')
-    key_store = 'scripts/ant/xwalk-debug.keystore'
+    print('   No keystore provided for signing. Using xwalk\'s keystore '
+          'for debugging.\n   Please use a valid keystore when '
+          'distributing to the app market.')
+    key_store = os.path.join(xwalk_dir, 'xwalk-debug.keystore')
     key_alias = 'xwalkdebugkey'
     key_code = 'xwalkdebug'
+    key_alias_code = 'xwalkdebug'
 
-  if not os.path.exists('out'):
-    os.mkdir('out')
-
-  # Make sure to use ant-tasks.jar correctly.
-  # Default Android SDK names it as ant-tasks.jar
-  # Chrome third party Android SDk names it as anttasks.jar
-  ant_tasks_jar_path = os.path.join(sdk_root_path,
-                                    'tools', 'lib', 'ant-tasks.jar')
-  if not os.path.exists(ant_tasks_jar_path):
-    ant_tasks_jar_path = os.path.join(sdk_root_path,
-                                      'tools', 'lib', 'anttasks.jar')
-
-  aapt_path = ''
-  for aapt_str in AddExeExtensions('aapt'):
-    try:
-      aapt_path = Find(aapt_str, sdk_root_path)
-      print('Use %s in %s.' % (aapt_str, sdk_root_path))
-      break
-    except Exception:
-      pass
-  if not aapt_path:
-    print('Your Android SDK may be ruined, please reinstall it.')
-    sys.exit(2)
-
-  # Check whether ant is installed.
-  try:
-    cmd = ['ant', '-version']
-    RunCommand(cmd, shell=True)
-  except EnvironmentError:
-    print('Please install ant first.')
-    sys.exit(4)
-
-  res_dirs = '-DADDITIONAL_RES_DIRS=\'\''
-  res_packages = '-DADDITIONAL_RES_PACKAGES=\'\''
-  res_r_text_files = '-DADDITIONAL_R_TEXT_FILES=\'\''
+  # Update android project for app and xwalk_core_library.
+  update_project_cmd = [android_path, 'update', 'project',
+                        '--path', app_dir,
+                        '--target', target_string,
+                        '--name', name]
   if options.mode == 'embedded':
-    # Prepare the .pak file for embedded mode.
-    pak_src_path = os.path.join('native_libs_res', 'xwalk.pak')
-    pak_des_path = os.path.join(name, 'assets', 'xwalk.pak')
-    shutil.copy(pak_src_path, pak_des_path)
-
-    # Prepare the icudtl.dat for embedded mode.
-    icudtl_src_path = os.path.join('native_libs_res', 'icudtl.dat')
-    icudtl_des_path = os.path.join(name, 'assets', 'icudtl.dat')
-    shutil.copy(icudtl_src_path, icudtl_des_path)
-
-    js_src_dir = os.path.join('native_libs_res', 'jsapi')
-    js_des_dir = os.path.join(name, 'assets', 'jsapi')
-    if os.path.exists(js_des_dir):
-      shutil.rmtree(js_des_dir)
-    shutil.copytree(js_src_dir, js_des_dir)
-
-    res_ui_java = os.path.join('gen', 'ui_java')
-    res_content_java = os.path.join('gen', 'content_java')
-    res_xwalk_java = os.path.join('gen', 'xwalk_core_internal_java')
-    res_dirs = ('-DADDITIONAL_RES_DIRS='
-                + os.path.join(res_ui_java, 'res_crunched') + ' '
-                + os.path.join(res_ui_java, 'res_v14_compatibility') + ' '
-                + os.path.join(res_ui_java, 'res_grit') + ' '
-                + os.path.join('libs_res', 'ui') + ' '
-                + os.path.join(res_content_java, 'res_crunched') + ' '
-                + os.path.join(res_content_java, 'res_v14_compatibility') + ' '
-                + os.path.join('libs_res', 'content') + ' '
-                + os.path.join(res_content_java, 'res_grit') + ' '
-                + os.path.join(res_xwalk_java, 'res_crunched') + ' '
-                + os.path.join(res_xwalk_java, 'res_v14_compatibility') + ' '
-                + os.path.join('libs_res', 'runtime') + ' '
-                + os.path.join(res_xwalk_java, 'res_grit'))
-    res_packages = ('-DADDITIONAL_RES_PACKAGES=org.chromium.ui '
-                    'org.xwalk.core.internal org.chromium.content')
-    res_r_text_files = ('-DADDITIONAL_R_TEXT_FILES='
-                        + os.path.join(res_ui_java, 'java_R', 'R.txt') + ' '
-                        + os.path.join(res_xwalk_java, 'java_R', 'R.txt') + ' '
-                        + os.path.join(res_content_java, 'java_R', 'R.txt'))
-
-  resource_dir = '-DRESOURCE_DIR=' + os.path.join(name, 'res')
-  manifest_path = os.path.join(name, 'AndroidManifest.xml')
-  cmd = ['python', os.path.join('scripts', 'gyp', 'ant.py'),
-         '-DAAPT_PATH=%s' % aapt_path,
-         res_dirs,
-         res_packages,
-         res_r_text_files,
-         '-DANDROID_MANIFEST=%s' % manifest_path,
-         '-DANDROID_SDK_JAR=%s' % sdk_jar_path,
-         '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
-         '-DANDROID_SDK_VERSION=%d' % api_level,
-         '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
-         '-DLIBRARY_MANIFEST_PATHS= ',
-         '-DOUT_DIR=out',
-         resource_dir,
-         '-DSTAMP=codegen.stamp',
-         '-Dbasedir=.',
-         '-buildfile',
-         os.path.join('scripts', 'ant', 'apk-codegen.xml')]
-  RunCommand(cmd, options.verbose)
-
-  # Check whether java is installed.
-  try:
-    cmd = ['java', '-version']
-    RunCommand(cmd, shell=True)
-  except EnvironmentError:
-    print('Please install Oracle JDK first.')
-    sys.exit(5)
-
-  # Compile App source code with app runtime code.
-  cmd = ['python', os.path.join('scripts', 'gyp', 'javac.py'),
-         '--output-dir=%s' % os.path.join('out', 'classes'),
-         '--classpath',
-         os.path.join(os.getcwd(), 'libs', 'xwalk_app_runtime_java.jar'),
-         '--classpath',
-         sdk_jar_path,
-         '--src-dirs',
-         os.path.join(os.getcwd(), name, 'src'),
-         '--src-dirs',
-         os.path.join(os.getcwd(), 'out', 'gen'),
-         '--chromium-code=0',
-         '--stamp=compile.stam']
-  RunCommand(cmd, options.verbose)
-
-  # Package resources.
-  asset_dir = '-DASSET_DIR=%s' % os.path.join(name, 'assets')
-  xml_path = os.path.join('scripts', 'ant', 'apk-package-resources.xml')
-  cmd = ['python', os.path.join('scripts', 'gyp', 'ant.py'),
-         '-DAAPT_PATH=%s' % aapt_path,
-         res_dirs,
-         res_packages,
-         res_r_text_files,
-         '-DANDROID_SDK_JAR=%s' % sdk_jar_path,
-         '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
-         '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
-         '-DAPK_NAME=%s' % name,
-         '-DAPP_MANIFEST_VERSION_CODE=0',
-         '-DAPP_MANIFEST_VERSION_NAME=Developer Build',
-         asset_dir,
-         '-DCONFIGURATION_NAME=Release',
-         '-DOUT_DIR=out',
-         resource_dir,
-         '-DSTAMP=package_resources.stamp',
-         '-Dbasedir=.',
-         '-buildfile',
-         xml_path]
-  RunCommand(cmd, options.verbose)
-
-  dex_path = '--dex-path=' + os.path.join(os.getcwd(), 'out', 'classes.dex')
-  app_runtime_jar = os.path.join(os.getcwd(),
-                                 'libs', 'xwalk_app_runtime_java.jar')
+    print(' * Updating project with xwalk_core_library')
+    RunCommand([android_path, 'update', 'lib-project',
+                '--path', os.path.join(app_dir, 'xwalk_core_library'),
+                '--target', target_string])
+    update_project_cmd.extend(['-l', 'xwalk_core_library'])
+  else:
+    print(' * Updating project')
+  RunCommand(update_project_cmd)
 
   # Check whether external extensions are included.
+  print(' * Checking for external extensions')
   extensions_string = 'xwalk-extensions'
-  extensions_dir = os.path.join(os.getcwd(), name, extensions_string)
+  extensions_dir = os.path.join(app_dir, extensions_string)
   external_extension_jars = FindExtensionJars(extensions_dir)
-  input_jars = []
-  if options.mode == 'embedded':
-    input_jars.append(os.path.join(os.getcwd(), 'libs',
-                                   'xwalk_runtime_embedded.dex.jar'))
-  dex_command_list = ['python', os.path.join('scripts', 'gyp', 'dex.py'),
-                      dex_path,
-                      '--android-sdk-root=%s' % sdk_root_path,
-                      app_runtime_jar,
-                      os.path.join(os.getcwd(), 'out', 'classes')]
-  dex_command_list.extend(external_extension_jars)
-  dex_command_list.extend(input_jars)
-  RunCommand(dex_command_list)
-
-  src_dir = '-DSOURCE_DIR=' + os.path.join(name, 'src')
-  apk_path = '-DUNSIGNED_APK_PATH=' + os.path.join('out', 'app-unsigned.apk')
-  native_lib_path = '-DNATIVE_LIBS_DIR='
+  for external_extension_jar in external_extension_jars:
+    shutil.copyfile(external_extension_jar,
+                    os.path.join(app_dir, 'libs',
+                                 os.path.basename(external_extension_jar)))
+
   if options.mode == 'embedded':
-    if options.arch == 'x86':
-      x86_native_lib_path = os.path.join('native_libs', 'x86', 'libs',
-                                         'x86', 'libxwalkcore.so')
-      if os.path.isfile(x86_native_lib_path):
-        native_lib_path += os.path.join('native_libs', 'x86', 'libs')
-      else:
-        print('Missing x86 native library for Crosswalk embedded APK. Abort!')
-        sys.exit(10)
-    elif options.arch == 'arm':
-      arm_native_lib_path = os.path.join('native_libs', 'armeabi-v7a', 'libs',
-                                         'armeabi-v7a', 'libxwalkcore.so')
-      if os.path.isfile(arm_native_lib_path):
-        native_lib_path += os.path.join('native_libs', 'armeabi-v7a', 'libs')
-      else:
-        print('Missing ARM native library for Crosswalk embedded APK. Abort!')
-        sys.exit(10)
-  # A space is needed for Windows.
-  native_lib_path += ' '
-  cmd = ['python', 'scripts/gyp/ant.py',
-         '-DANDROID_SDK_ROOT=%s' % sdk_root_path,
-         '-DANT_TASKS_JAR=%s' % ant_tasks_jar_path,
-         '-DAPK_NAME=%s' % name,
-         '-DCONFIGURATION_NAME=Release',
-         native_lib_path,
-         '-DOUT_DIR=out',
-         src_dir,
-         apk_path,
-         '-Dbasedir=.',
-         '-buildfile',
-         'scripts/ant/apk-package.xml']
-  RunCommand(cmd, options.verbose)
-
-  # Find the path of zipalign.
-  # XWALK-2033: zipalign can be in different locations depending on Android
-  # SDK version that used ((eg. /tools, /build-tools/android-4.4W etc),).
-  # So looking up the location of zipalign here instead of hard coding.
-  # Refer to: https://codereview.chromium.org/238253015
-  zipalign_path = ''
-  for zipalign_str in AddExeExtensions('zipalign'):
-    try:
-      zipalign_path = Find(zipalign_str, sdk_root_path)
-      if options.verbose:
-        print('Use %s in %s.' % (zipalign_str, sdk_root_path))
-      break
-    except Exception:
-      pass
-  if not zipalign_path:
-    print('zipalign could not be found in your Android SDK.'
-          ' Make sure it is installed.')
-    sys.exit(10)
-  apk_path = '--unsigned-apk-path=' + os.path.join('out', 'app-unsigned.apk')
-  final_apk_path = '--final-apk-path=' + \
-                   os.path.join('out', name + '.apk')
-  cmd = ['python', 'scripts/gyp/finalize_apk.py',
-         '--zipalign-path=%s' % zipalign_path,
-         apk_path,
-         final_apk_path,
-         '--keystore-path=%s' % key_store,
-         '--keystore-alias=%s' % key_alias,
-         '--keystore-passcode=%s' % key_code]
-  RunCommand(cmd)
+    print (' * Copying native libraries for %s' % options.arch)
+    # Remove existing native libraries in xwalk_core_library, they are probably
+    # for the last execution to make apk for another CPU arch.
+    # And then copy the native libraries for the specified arch into
+    # xwalk_core_library.
+    arch = ConvertArchNameToArchFolder(options.arch)
+    if not arch:
+      print ('Invalid CPU arch: %s.' % arch)
+      sys.exit(10)
+    library_lib_path = os.path.join(app_dir, 'xwalk_core_library', 'libs')
+    for dir_name in os.listdir(library_lib_path):
+      lib_dir = os.path.join(library_lib_path, dir_name)
+      if ContainsNativeLibrary(lib_dir):
+        shutil.rmtree(lib_dir)
+    native_lib_path = os.path.join(app_dir, 'native_libs', arch)
+    if ContainsNativeLibrary(native_lib_path):
+      shutil.copytree(native_lib_path, os.path.join(library_lib_path, arch))
+    else:
+      print('No %s native library has been found for creating a Crosswalk '
+            'embedded APK.' % arch)
+      sys.exit(10)
+
+  if options.project_only:
+    print (' (Skipping apk package creation)')
+    return
 
-  src_file = os.path.join('out', name + '.apk')
-  package_name = options.name
+  # Build the APK
+  if options.mode == 'embedded':
+    print(' * Building Android apk package with Crosswalk embedded' +
+          arch_string)
+  else:
+    print(' * Building Android apk package')
+  ant_path = Which('ant')
+  ant_cmd = [ant_path, 'release', '-f', os.path.join(app_dir, 'build.xml')]
+  ant_cmd.extend(['-Dkey.store=%s' % os.path.abspath(key_store)])
+  ant_cmd.extend(['-Dkey.alias=%s' % key_alias])
+  if key_code:
+    ant_cmd.extend(['-Dkey.store.password=%s' % key_code])
+  if key_alias_code:
+    ant_cmd.extend(['-Dkey.alias.password=%s' % key_alias_code])
+
+  cmd_display = ' '.join([str(item) for item in ant_cmd])
+  if options.verbose:
+    print('Executing:\n %s\n' % cmd_display)
+  else:
+    ant_cmd.extend(['-quiet'])
+  ant_result = subprocess.call(ant_cmd)
+  if ant_result != 0:
+    print('Command "%s" exited with non-zero exit code %d'
+          % (cmd_display, ant_result))
+    sys.exit(ant_result)
+
+  src_file = os.path.join(app_dir, 'bin', '%s-release.apk' % name)
+  package_name = name
   if options.app_version:
     package_name += ('_' + options.app_version)
   if options.mode == 'shared':
@@ -496,55 +357,91 @@ def Execution(options, name):
     dst_file = os.path.join(options.target_dir,
                             '%s_%s.apk' % (package_name, options.arch))
   shutil.copyfile(src_file, dst_file)
-  CleanDir('out')
-  if options.mode == 'embedded':
-    os.remove(pak_des_path)
+  print(' (Location: %s)' % dst_file)
 
-
-def PrintPackageInfo(options, packaged_archs):
-  package_name_version = os.path.join(options.target_dir, options.name)
+def PrintPackageInfo(options, name, packaged_archs):
+  package_name_version = os.path.join(options.target_dir, name)
   if options.app_version:
     package_name_version += '_' + options.app_version
 
   if len(packaged_archs) == 0:
-    print ('A non-platform specific APK for the web application "%s" was '
-           'generated successfully at\n%s.apk. It requires a shared Crosswalk '
-           'Runtime to be present.'
-           % (options.name, package_name_version))
+    print ('\nA non-platform specific APK for the web application "%s" was '
+           'generated successfully at:\n %s.apk.\nIt requires a shared '
+           'Crosswalk Runtime to be present.'
+           % (name, package_name_version))
     return
 
-  for arch in packaged_archs:
-    print ('An APK for the web application "%s" including the Crosswalk '
-           'Runtime built for %s was generated successfully, which can be '
-           'found at\n%s_%s.apk.'
-           % (options.name, arch, package_name_version, arch))
-
   all_archs = set(AllArchitectures())
 
   if len(packaged_archs) != len(all_archs):
     missed_archs = all_archs - set(packaged_archs)
-    print ('\n\nWARNING: ')
-    print ('This APK will only work on %s based Android devices. Consider '
-           'building for %s as well.' %
+    print ('\nNote: This APK will only work on %s-based Android devices.'
+           ' Consider building\nfor %s as well.' %
            (', '.join(packaged_archs), ', '.join(missed_archs)))
   else:
-    print ('\n\n%d APKs were created for %s devices. '
-           % (len(all_archs), ', '.join(all_archs)))
-    print ('Please install the one that matches the processor architecture '
-           'of your device.\n\n')
-    print ('If you are going to submit this application to an application '
-           'store, please make sure you submit both packages.\nInstructions '
-           'for submitting multiple APKs to Google Play Store are available '
-           'here:\nhttps://software.intel.com/en-us/html5/articles/submitting'
+    print ("\nApplication apk's were created for %d architectures (%s)." %
+           (len(all_archs), (','.join(all_archs))))
+    print ('If you submit this application to an application '
+           'store, please submit both\npackages. Instructions '
+           'for submitting multiple APKs to Google Play Store are\navailable '
+           'here:')
+    print (' https://software.intel.com/en-us/html5/articles/submitting'
            '-multiple-crosswalk-apk-to-google-play-store')
 
-def MakeApk(options, app_info):
-  Customize(options, app_info)
-  name = options.name
+
+def CheckSystemRequirements():
+  ''' Check for android, ant, template dir '''
+  sys.stdout.write('Checking system requirements...')
+  sys.stdout.flush()
+  # check android install
+  android_path = Which('android')
+  if android_path is None:
+    print('failed\nThe "android" binary could not be found. Check your Android '
+          'SDK installation and your PATH environment variable.')
+    sys.exit(1)
+  if GetAndroidApiLevel(android_path) < 14:
+    print('failed\nPlease install Android API level (>=14) first.')
+    sys.exit(3)
+
+  # Check ant install
+  ant_path = Which('ant')
+  if ant_path is None:
+    print('failed\nAnt could not be found. Please make sure it is installed.')
+    sys.exit(4)
+
+  print('ok')
+
+
+def MakeApk(options, app_info, manifest):
+  CheckSystemRequirements()
+  Customize(options, app_info, manifest)
+  name = app_info.android_name
+  app_dir = os.path.join(tempfile.gettempdir(), name)
   packaged_archs = []
   if options.mode == 'shared':
+    # For shared mode, it's not necessary to use the whole xwalk core library,
+    # use xwalk_core_library_java_app_part.jar from it is enough.
+    java_app_part_jar = os.path.join(xwalk_dir, 'xwalk_core_library', 'libs',
+                                     'xwalk_core_library_java_app_part.jar')
+    shutil.copy(java_app_part_jar, os.path.join(app_dir, 'libs'))
     Execution(options, name)
   elif options.mode == 'embedded':
+    # Copy xwalk_core_library into app folder and move the native libraries
+    # out.
+    # When making apk for specified CPU arch, will only include the
+    # corresponding native library by copying it back into xwalk_core_library.
+    target_library_path = os.path.join(app_dir, 'xwalk_core_library')
+    shutil.copytree(os.path.join(xwalk_dir, 'xwalk_core_library'),
+                    target_library_path)
+    library_lib_path = os.path.join(target_library_path, 'libs')
+    native_lib_path = os.path.join(app_dir, 'native_libs')
+    os.makedirs(native_lib_path)
+    available_archs = []
+    for dir_name in os.listdir(library_lib_path):
+      lib_dir = os.path.join(library_lib_path, dir_name)
+      if ContainsNativeLibrary(lib_dir):
+        shutil.move(lib_dir, os.path.join(native_lib_path, dir_name))
+        available_archs.append(dir_name)
     if options.arch:
       Execution(options, name)
       packaged_archs.append(options.arch)
@@ -553,9 +450,7 @@ def MakeApk(options, app_info):
       # will be generated.
       valid_archs = ['x86', 'armeabi-v7a']
       for arch in valid_archs:
-        lib_path = os.path.join('native_libs', arch, 'libs',
-                                arch, 'libxwalkcore.so')
-        if os.path.isfile(lib_path):
+        if arch in available_archs:
           if arch.find('x86') != -1:
             options.arch = 'x86'
           elif arch.find('arm') != -1:
@@ -564,14 +459,32 @@ def MakeApk(options, app_info):
           packaged_archs.append(options.arch)
         else:
           print('Warning: failed to create package for arch "%s" '
-                'due to missing library %s' %
-                (arch, lib_path))
+                'due to missing native library' % arch)
 
       if len(packaged_archs) == 0:
         print('No packages created, aborting')
         sys.exit(13)
 
-  PrintPackageInfo(options, packaged_archs)
+  # if project_dir, save build directory
+  if options.project_dir:
+    print ('\nCreating project directory')
+    save_dir = os.path.join(options.project_dir, name)
+    if CreateAndCopyDir(app_dir, save_dir, True):
+      print ('  A project directory was created successfully in:\n   %s' %
+             os.path.abspath(save_dir))
+      print ('  To manually generate an APK, run the following in that '
+             'directory:')
+      print ('   ant release -f build.xml')
+      print ('  For more information, see:\n'
+             '   http://developer.android.com/tools/building/'
+             'building-cmdline.html')
+    else:
+      print ('Error: Unable to create a project directory during the build. '
+             'Please check the directory passed in --project-dir, '
+             'available disk space, and write permission.')
+
+  if not options.project_only:
+    PrintPackageInfo(options, name, packaged_archs)
 
 def main(argv):
   parser = optparse.OptionParser()
@@ -616,6 +529,7 @@ def main(argv):
           'For example, --app-local-path=/relative/path/of/entry/file')
   group.add_option('--app-local-path', help=info)
   parser.add_option_group(group)
+  # Mandatory options group
   group = optparse.OptionGroup(parser, 'Mandatory arguments',
       'They are used for describing the APK information through '
       'command line options.')
@@ -625,6 +539,7 @@ def main(argv):
           '--package=com.example.YourPackage')
   group.add_option('--package', help=info)
   parser.add_option_group(group)
+  # Optional options group (alphabetical)
   group = optparse.OptionGroup(parser, 'Optional arguments',
       'They are used for various settings for applications through '
       'command line options.')
@@ -638,17 +553,15 @@ def main(argv):
           'be made by adding a prefix based on architecture to the version '
           'code base. For example, --app-versionCodeBase=24')
   group.add_option('--app-versionCodeBase', type='int', help=info)
-  info = ('Use command lines.'
-          'Crosswalk is powered by Chromium and supports Chromium command line.'
-          'For example, '
-          '--xwalk-command-line=\'--chromium-command-1 --xwalk-command-2\'')
-  group.add_option('--xwalk-command-line', default='', help=info)
   info = ('The description of the application. For example, '
           '--description=YourApplicationDescription')
   group.add_option('--description', help=info)
   group.add_option('--enable-remote-debugging', action='store_true',
                    dest='enable_remote_debugging', default=False,
                    help='Enable remote debugging.')
+  group.add_option('--use-animatable-view', action='store_true',
+                   dest='use_animatable_view', default=False,
+                   help='Enable using animatable view (TextureView).')
   info = ('The list of external extension paths splitted by OS separators. '
           'The separators are \':\' , \';\' and \':\' on Linux, Windows and '
           'Mac OS respectively. For example, '
@@ -671,9 +584,22 @@ def main(argv):
   info = ('The list of permissions to be used by web application. For example, '
           '--permissions=geolocation:webgl')
   group.add_option('--permissions', help=info)
-  info = ('Packaging tool will move the output APKS to the target directory')
+  info = ('Create an Android project directory with Crosswalk at this location.'
+          ' (See project-only option below)')
+  group.add_option('--project-dir', help=info)
+  info = ('Must be used with project-dir option. Create an Android project '
+          'directory with Crosswalk but do not build the APK package')
+  group.add_option('--project-only', action='store_true', default=False,
+                   dest='project_only', help=info)
+  info = ('Packaging tool will move the output APKs to the target directory')
   group.add_option('--target-dir', default=os.getcwd(), help=info)
+  info = ('Use command lines.'
+          'Crosswalk is powered by Chromium and supports Chromium command line.'
+          'For example, '
+          '--xwalk-command-line=\'--chromium-command-1 --xwalk-command-2\'')
+  group.add_option('--xwalk-command-line', default='', help=info)
   parser.add_option_group(group)
+  # Keystore options group
   group = optparse.OptionGroup(parser, 'Keystore Options',
       'The keystore is a signature from web developer, it\'s used when '
       'developer wants to distribute the applications.')
@@ -684,6 +610,9 @@ def main(argv):
   group.add_option('--keystore-alias', help=info)
   info = ('The passcode of keystore. For example, --keystore-passcode=code')
   group.add_option('--keystore-passcode', help=info)
+  info = ('Passcode for alias\'s private key in the keystore, '
+          'For example, --keystore-alias-passcode=alias-code')
+  group.add_option('--keystore-alias-passcode', help=info)
   info = ('Minify and obfuscate javascript and css.'
           '--compressor: compress javascript and css.'
           '--compressor=js: compress javascript.'
@@ -702,12 +631,14 @@ def main(argv):
       print(GetVersion('VERSION'))
       return 0
     else:
-      parser.error('Can\'t get version due to the VERSION file missing!')
+      parser.error('VERSION was not found, so Crosswalk\'s version could not '
+                   'be determined.')
 
   xpk_temp_dir = ''
   if options.xpk:
     xpk_name = os.path.splitext(os.path.basename(options.xpk))[0]
-    xpk_temp_dir = xpk_name + '_xpk'
+    xpk_temp_dir = os.path.join(tempfile.gettempdir(), xpk_name + '_xpk')
+    CleanDir(xpk_temp_dir)
     ParseXPK(options, xpk_temp_dir)
 
   if options.app_root and not options.manifest:
@@ -717,19 +648,8 @@ def main(argv):
       options.manifest = manifest_path
 
   app_info = AppInfo()
+  manifest = None
   if not options.manifest:
-    if options.package:
-      VerifyAppName(options.package, 'packagename')
-    else:
-      parser.error('The package name is required! '
-                   'Please use "--package" option.')
-    if options.name:
-      VerifyAppName(options.name)
-      app_info.original_name = options.name
-      options.name = ReplaceSpaceWithUnderscore(options.name)
-    else:
-      parser.error('The APK name is required! Please use "--name" option.')
-
     # The checks here are really convoluted, but at the moment make_apk
     # misbehaves any of the following conditions is true.
     if options.app_url:
@@ -760,10 +680,18 @@ def main(argv):
     options.icon_dict = {}
   else:
     try:
-      ParseManifest(options, app_info)
+      manifest = ParseManifest(options)
     except SystemExit as ec:
       return ec.code
 
+  if not options.name:
+    parser.error('An APK name is required. Please use the "--name" option.')
+
+  if not options.package:
+    parser.error('A package name is required. Please use the "--package" '
+                 'option.')
+  VerifyPackageName(options.package)
+
   if (options.app_root and options.app_local_path and
       not os.path.isfile(os.path.join(options.app_root,
                                       options.app_local_path))):
@@ -777,15 +705,29 @@ def main(argv):
     if not os.path.isdir(target_dir):
       os.makedirs(target_dir)
 
+  if options.project_dir:
+    if options.project_dir == tempfile.gettempdir():
+      print('\nmake_apk.py error: Option --project-dir can not be '
+            'the system temporary\ndirectory.')
+      sys.exit(8)
+  if options.project_only and not options.project_dir:
+    print('\nmake_apk.py error: Option --project-only must be used '
+          'with --project-dir')
+    sys.exit(8)
+
   try:
-    MakeApk(options, app_info)
+    MakeApk(options, app_info, manifest)
   except SystemExit as ec:
-    CleanDir(options.name)
-    CleanDir('out')
-    CleanDir(xpk_temp_dir)
     return ec.code
+  finally:
+    CleanDir(os.path.join(tempfile.gettempdir(), app_info.android_name))
+    CleanDir(xpk_temp_dir)
   return 0
 
 
 if __name__ == '__main__':
-  sys.exit(main(sys.argv))
+  try:
+    sys.exit(main(sys.argv))
+  except KeyboardInterrupt:
+    print('')
+