Commit 34ae2788 authored by estevenson's avatar estevenson Committed by Commit bot

Move language pak files to assets.

Language pak files were moved to res/raw when split apks was being implemented.
Moving them to assets with a java constant keeping track of pak file locations
will improve lookup time and save some space (no more xml files and
resources.arsc).

BUG=529604

Review-Url: https://codereview.chromium.org/2345143002
Cr-Commit-Position: refs/heads/master@{#420641}
parent 89ff2d42
...@@ -53,7 +53,8 @@ webview_repack_locales("repack_locales") { ...@@ -53,7 +53,8 @@ webview_repack_locales("repack_locales") {
} }
} }
locale_pak_resources("locale_paks") { locale_pak_assets("locale_pak") {
disable_compression = true
sources = [ sources = [
"$root_out_dir/android_webview/locales/am.pak", "$root_out_dir/android_webview/locales/am.pak",
"$root_out_dir/android_webview/locales/ar.pak", "$root_out_dir/android_webview/locales/ar.pak",
...@@ -186,6 +187,7 @@ android_assets("monochrome_webview_assets") { ...@@ -186,6 +187,7 @@ android_assets("monochrome_webview_assets") {
android_assets("assets") { android_assets("assets") {
deps = [ deps = [
":locale_pak_assets",
":monochrome_webview_assets", ":monochrome_webview_assets",
":pak_file_assets", ":pak_file_assets",
] ]
...@@ -215,7 +217,6 @@ android_resources("resources") { ...@@ -215,7 +217,6 @@ android_resources("resources") {
resource_dirs = [ "java/res" ] resource_dirs = [ "java/res" ]
custom_package = "org.chromium.android_webview" custom_package = "org.chromium.android_webview"
deps = [ deps = [
":locale_paks",
":strings_grd", ":strings_grd",
] ]
} }
......
...@@ -43,11 +43,17 @@ android_library("glue") { ...@@ -43,11 +43,17 @@ android_library("glue") {
deps = glue_library_deps deps = glue_library_deps
srcjar_deps = [ srcjar_deps = [
":glue_resource_rewriter", ":glue_resource_rewriter",
"//android_webview:locale_pak_srcjar",
"//base:base_build_config_gen", "//base:base_build_config_gen",
] ]
# New versions of BuildConfig.java will be created when creating an apk. jar_excluded_patterns = [
jar_excluded_patterns = [ "*/BuildConfig.class" ] # New versions of BuildConfig.java will be created when creating an apk.
"*/BuildConfig.class",
# Allow downstream targets to specify their own locale pak files.
"*/LocalePakFiles.class",
]
# Always build upstream or downstream target with public or internal # Always build upstream or downstream target with public or internal
# framework jar respectively. # framework jar respectively.
......
...@@ -47,7 +47,6 @@ import org.chromium.android_webview.AwResource; ...@@ -47,7 +47,6 @@ import org.chromium.android_webview.AwResource;
import org.chromium.android_webview.AwServiceWorkerController; import org.chromium.android_webview.AwServiceWorkerController;
import org.chromium.android_webview.AwSettings; import org.chromium.android_webview.AwSettings;
import org.chromium.android_webview.HttpAuthDatabase; import org.chromium.android_webview.HttpAuthDatabase;
import org.chromium.android_webview.R;
import org.chromium.android_webview.ResourcesContextWrapperFactory; import org.chromium.android_webview.ResourcesContextWrapperFactory;
import org.chromium.base.BuildConfig; import org.chromium.base.BuildConfig;
import org.chromium.base.CommandLine; import org.chromium.base.CommandLine;
...@@ -63,6 +62,7 @@ import org.chromium.base.library_loader.LibraryProcessType; ...@@ -63,6 +62,7 @@ import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.content.browser.ContentViewStatics; import org.chromium.content.browser.ContentViewStatics;
import org.chromium.net.NetworkChangeNotifier; import org.chromium.net.NetworkChangeNotifier;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ResourceBundle; import org.chromium.ui.base.ResourceBundle;
import java.io.File; import java.io.File;
...@@ -385,7 +385,7 @@ public class WebViewChromiumFactoryProvider implements WebViewFactoryProvider { ...@@ -385,7 +385,7 @@ public class WebViewChromiumFactoryProvider implements WebViewFactoryProvider {
// Make sure that ResourceProvider is initialized before starting the browser process. // Make sure that ResourceProvider is initialized before starting the browser process.
final String webViewPackageName = WebViewFactory.getLoadedPackageInfo().packageName; final String webViewPackageName = WebViewFactory.getLoadedPackageInfo().packageName;
setUpResources(webViewPackageName, context); setUpResources(webViewPackageName, context);
ResourceBundle.initializeLocalePaks(context, R.array.locale_paks); ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
initPlatSupportLibrary(); initPlatSupportLibrary();
initNetworkChangeNotifier(context); initNetworkChangeNotifier(context);
final int extraBindFlags = Context.BIND_EXTERNAL_SERVICE; final int extraBindFlags = Context.BIND_EXTERNAL_SERVICE;
......
...@@ -14,6 +14,8 @@ template("system_webview_apk_tmpl") { ...@@ -14,6 +14,8 @@ template("system_webview_apk_tmpl") {
"//base:base_java", "//base:base_java",
] ]
srcjar_deps = [ "//android_webview:locale_pak_srcjar" ]
if (!defined(alternative_android_sdk_jar)) { if (!defined(alternative_android_sdk_jar)) {
alternative_android_sdk_jar = webview_framework_jar alternative_android_sdk_jar = webview_framework_jar
} }
......
...@@ -48,6 +48,8 @@ android_apk("android_webview_apk") { ...@@ -48,6 +48,8 @@ android_apk("android_webview_apk") {
":libstandalonelibwebviewchromium", ":libstandalonelibwebviewchromium",
] ]
srcjar_deps = [ "//android_webview:locale_pak_srcjar" ]
native_lib_version_rule = "//build/util:chrome_version_json" native_lib_version_rule = "//build/util:chrome_version_json"
_native_lib_file = _native_lib_file =
rebase_path("$root_gen_dir/CHROME_VERSION.json", root_build_dir) rebase_path("$root_gen_dir/CHROME_VERSION.json", root_build_dir)
...@@ -63,6 +65,7 @@ android_resources("android_webview_apk_resources") { ...@@ -63,6 +65,7 @@ android_resources("android_webview_apk_resources") {
android_assets("android_webview_apk_assets") { android_assets("android_webview_apk_assets") {
deps = [ deps = [
"//android_webview:locale_pak_assets",
"//android_webview:pak_file_assets", "//android_webview:pak_file_assets",
"//third_party/icu:icu_assets", "//third_party/icu:icu_assets",
"//v8:v8_external_startup_data_assets", "//v8:v8_external_startup_data_assets",
......
...@@ -4,10 +4,10 @@ ...@@ -4,10 +4,10 @@
package org.chromium.android_webview.shell; package org.chromium.android_webview.shell;
import org.chromium.android_webview.R;
import org.chromium.base.CommandLine; import org.chromium.base.CommandLine;
import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.content.app.ContentApplication; import org.chromium.content.app.ContentApplication;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ResourceBundle; import org.chromium.ui.base.ResourceBundle;
/** /**
...@@ -25,7 +25,7 @@ public class AwShellApplication extends ContentApplication { ...@@ -25,7 +25,7 @@ public class AwShellApplication extends ContentApplication {
@Override @Override
protected void initializeLibraryDependencies() { protected void initializeLibraryDependencies() {
ResourceBundle.initializeLocalePaks(this, R.array.locale_paks); ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
} }
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME") @SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
......
...@@ -24,9 +24,19 @@ public class LocaleUtils { ...@@ -24,9 +24,19 @@ public class LocaleUtils {
* used by Chromium. * used by Chromium.
*/ */
public static String getLocale(Locale locale) { public static String getLocale(Locale locale) {
String language = locale.getLanguage(); String language = getLanguage(locale);
String country = locale.getCountry(); String country = locale.getCountry();
return country.isEmpty() ? language : language + "-" + country;
}
/**
* @return the language for the given locale, translating
* Android deprecated languages codes into modern ones used by Chromium.
*/
public static String getLanguage(Locale locale) {
String language = locale.getLanguage();
// Android uses deprecated lanuages codes for Hebrew and Indonesian but Chromium uses the // Android uses deprecated lanuages codes for Hebrew and Indonesian but Chromium uses the
// updated codes. Also, Android uses "tl" while Chromium uses "fil" for Tagalog/Filipino. // updated codes. Also, Android uses "tl" while Chromium uses "fil" for Tagalog/Filipino.
// So apply a mapping. // So apply a mapping.
...@@ -38,7 +48,7 @@ public class LocaleUtils { ...@@ -38,7 +48,7 @@ public class LocaleUtils {
} else if ("tl".equals(language)) { } else if ("tl".equals(language)) {
language = "fil"; language = "fil";
} }
return country.isEmpty() ? language : language + "-" + country; return language;
} }
/** /**
......
...@@ -36,22 +36,7 @@ public class ResourceExtractor { ...@@ -36,22 +36,7 @@ public class ResourceExtractor {
private static final String V8_SNAPSHOT_DATA_FILENAME = "snapshot_blob.bin"; private static final String V8_SNAPSHOT_DATA_FILENAME = "snapshot_blob.bin";
private static final String APP_VERSION_PREF = "org.chromium.base.ResourceExtractor.Version"; private static final String APP_VERSION_PREF = "org.chromium.base.ResourceExtractor.Version";
private static ResourceEntry[] sResourcesToExtract = new ResourceEntry[0]; private static String[] sResourcesToExtract = new String[0];
/**
* Holds information about a res/raw file (e.g. locale .pak files).
*/
public static final class ResourceEntry {
public final int resourceId;
public final String pathWithinApk;
public final String extractedFileName;
public ResourceEntry(int resourceId, String pathWithinApk, String extractedFileName) {
this.resourceId = resourceId;
this.pathWithinApk = pathWithinApk;
this.extractedFileName = extractedFileName;
}
}
private class ExtractTask extends AsyncTask<Void, Void, Void> { private class ExtractTask extends AsyncTask<Void, Void, Void> {
private static final int BUFFER_SIZE = 16 * 1024; private static final int BUFFER_SIZE = 16 * 1024;
...@@ -107,16 +92,15 @@ public class ResourceExtractor { ...@@ -107,16 +92,15 @@ public class ResourceExtractor {
TraceEvent.begin("WalkAssets"); TraceEvent.begin("WalkAssets");
byte[] buffer = new byte[BUFFER_SIZE]; byte[] buffer = new byte[BUFFER_SIZE];
try { try {
for (ResourceEntry entry : sResourcesToExtract) { for (String resource : sResourcesToExtract) {
File output = new File(outputDir, entry.extractedFileName); File output = new File(outputDir, resource);
// TODO(agrieve): It would be better to check that .length == expectedLength. // TODO(agrieve): It would be better to check that .length == expectedLength.
// http://crbug.com/606413 // http://crbug.com/606413
if (output.length() != 0) { if (output.length() != 0) {
continue; continue;
} }
TraceEvent.begin("ExtractResource"); TraceEvent.begin("ExtractResource");
InputStream inputStream = mContext.getResources().openRawResource( InputStream inputStream = mContext.getAssets().open(resource);
entry.resourceId);
try { try {
extractResourceHelper(inputStream, output, buffer); extractResourceHelper(inputStream, output, buffer);
} finally { } finally {
...@@ -194,10 +178,10 @@ public class ResourceExtractor { ...@@ -194,10 +178,10 @@ public class ResourceExtractor {
* and moved to {@link #getOutputDir()}. * and moved to {@link #getOutputDir()}.
*/ */
@SuppressFBWarnings("EI_EXPOSE_STATIC_REP2") @SuppressFBWarnings("EI_EXPOSE_STATIC_REP2")
public static void setResourcesToExtract(ResourceEntry[] entries) { public static void setResourcesToExtract(String[] resources) {
assert (sInstance == null || sInstance.mExtractTask == null) assert (sInstance == null || sInstance.mExtractTask == null)
: "Must be called before startExtractingResources is called"; : "Must be called before startExtractingResources is called";
sResourcesToExtract = entries; sResourcesToExtract = resources;
} }
private ResourceExtractor(Context context) { private ResourceExtractor(Context context) {
......
...@@ -24,7 +24,7 @@ public class BlimpApplication extends BaseChromiumApplication { ...@@ -24,7 +24,7 @@ public class BlimpApplication extends BaseChromiumApplication {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
ContextUtils.initApplicationContext(this); ContextUtils.initApplicationContext(this);
ResourceExtractor.setResourcesToExtract(new ResourceExtractor.ResourceEntry[0]); ResourceExtractor.setResourcesToExtract(new String[0]);
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX, this); PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX, this);
initCommandLine(); initCommandLine();
} }
......
#!/usr/bin/env python
#
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Creates a srcjar for locale pak file paths.
Creates a srcjar with a class containing an array of locale pak files so that
these assets can be enumerated and extracted as necessary. This is much
more efficient than using AssetManager.list().
The generated class implements:
//base/android/java/src/org/chromium/base/LocalePakFiles.java
Providing access to pak file paths via:
public static String[] getFiles()
"""
import argparse
import collections
import os
import string
import sys
import zipfile
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from pylib.constants import host_paths
from util import build_utils
_CLASSNAME = 'LocalePakFiles'
_PACKAGE = 'org.chromium.ui'
_THIS_FILE = os.path.abspath(__file__)
def _CreateLocalePakFilesJava(pakfiles, package, classname, target):
"""Generate the java file contents for the locale pak file class."""
file_tmpl = string.Template("""
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is generated by:
// ${THIS_FILE}
// From target:
// ${TARGET}
package ${PACKAGE};
import org.chromium.base.annotations.SuppressFBWarnings;
public class LocalePakFiles {
private static String[] pakFiles = {${PAKFILES}};
@SuppressFBWarnings("MS_EXPOSE_REP")
public static String[] getFiles() {
return pakFiles;
}
}
""")
values = {
'TARGET': target,
'PACKAGE': package,
'CLASSNAME': classname,
'THIS_FILE': os.path.relpath(_THIS_FILE, host_paths.DIR_SOURCE_ROOT),
'PAKFILES': ', '.join('"%s"' % p for p in pakfiles),
}
return file_tmpl.substitute(values)
def _WriteJarOutput(output_path, in_zip_path, data):
"""Write file data to a srcjar."""
path = os.path.dirname(output_path)
if path and not os.path.exists(path):
os.makedirs(path)
with zipfile.ZipFile(output_path, 'w') as srcjar:
build_utils.AddToZipHermetic(srcjar, in_zip_path, data=data)
def main():
parser = argparse.ArgumentParser()
build_utils.AddDepfileOption(parser)
parser.add_argument('--locale-paks', required=True,
help='List of pak file paths to be added to srcjar')
parser.add_argument('--srcjar', required=True, help='Path to output srcjar')
parser.add_argument('--target', required=True, help='Target invoking script')
args = parser.parse_args()
sources = build_utils.ParseGnList(args.locale_paks)
if args.depfile:
build_utils.WriteDepfile(args.depfile, args.srcjar)
pakfiles = [os.path.basename(s) for s in sources]
srcjar_contents = _CreateLocalePakFilesJava(
pakfiles, _PACKAGE, _CLASSNAME, args.target)
in_zip_path = os.path.join(_PACKAGE.replace('.', '/'), _CLASSNAME + '.java')
_WriteJarOutput(args.srcjar, in_zip_path, srcjar_contents)
if __name__ == '__main__':
sys.exit(main())
#!/usr/bin/env python
#
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Creates a resources.zip for locale .pak files.
Places the locale.pak files into appropriate resource configs
(e.g. en-GB.pak -> res/raw-en/en_gb.lpak). Also generates a locale_paks
TypedArray so that resource files can be enumerated at runtime.
"""
import collections
import optparse
import os
import sys
import zipfile
from util import build_utils
# This should stay in sync with:
# base/android/java/src/org/chromium/base/LocaleUtils.java
_CHROME_TO_ANDROID_LOCALE_MAP = {
'he': 'iw',
'id': 'in',
'fil': 'tl',
}
def ToResourceFileName(name):
"""Returns the resource-compatible file name for the given file."""
# Resources file names must consist of [a-z0-9_.].
# Changes extension to .lpak so that compression can be toggled separately for
# locale pak files vs other pak files.
return name.replace('-', '_').replace('.pak', '.lpak').lower()
def CreateLocalePaksXml(names):
"""Creates the contents for the locale-paks.xml files."""
VALUES_FILE_TEMPLATE = '''<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="locale_paks">%s
</array>
</resources>
'''
VALUES_ITEM_TEMPLATE = '''
<item>@raw/%s</item>'''
res_names = (os.path.splitext(name)[0] for name in names)
items = ''.join((VALUES_ITEM_TEMPLATE % name for name in res_names))
return VALUES_FILE_TEMPLATE % items
def ComputeMappings(sources):
"""Computes the mappings of sources -> resources.
Returns a tuple of:
- mappings: List of (src, dest) paths
- lang_to_locale_map: Map of language -> list of resource names
e.g. "en" -> ["en_gb.lpak"]
"""
lang_to_locale_map = collections.defaultdict(list)
mappings = []
for src_path in sources:
basename = os.path.basename(src_path)
name = os.path.splitext(basename)[0]
res_name = ToResourceFileName(basename)
if name == 'en-US':
dest_dir = 'raw'
else:
# Chrome's uses different region mapping logic from Android, so include
# all regions for each language.
android_locale = _CHROME_TO_ANDROID_LOCALE_MAP.get(name, name)
lang = android_locale[0:2]
dest_dir = 'raw-' + lang
lang_to_locale_map[lang].append(res_name)
mappings.append((src_path, os.path.join(dest_dir, res_name)))
return mappings, lang_to_locale_map
def main():
parser = optparse.OptionParser()
build_utils.AddDepfileOption(parser)
parser.add_option('--locale-paks', help='List of files for res/raw-LOCALE')
parser.add_option('--resources-zip', help='Path to output resources.zip')
parser.add_option('--print-languages',
action='store_true',
help='Print out the list of languages that cover the given locale paks '
'(using Android\'s language codes)')
options, _ = parser.parse_args()
build_utils.CheckOptions(options, parser,
required=['locale_paks'])
sources = build_utils.ParseGnList(options.locale_paks)
if options.depfile:
assert options.resources_zip
build_utils.WriteDepfile(options.depfile, options.resources_zip, sources)
mappings, lang_to_locale_map = ComputeMappings(sources)
if options.print_languages:
print '\n'.join(sorted(lang_to_locale_map))
if options.resources_zip:
with zipfile.ZipFile(options.resources_zip, 'w', zipfile.ZIP_STORED) as out:
for mapping in mappings:
out.write(mapping[0], mapping[1])
# Create TypedArray resources so ResourceExtractor can enumerate files.
def WriteValuesFile(lang, names):
dest_dir = 'values'
if lang:
dest_dir += '-' + lang
# Always extract en-US.lpak since it's the fallback.
xml = CreateLocalePaksXml(names + ['en_us.lpak'])
out.writestr(os.path.join(dest_dir, 'locale-paks.xml'), xml)
for lang, names in lang_to_locale_map.iteritems():
WriteValuesFile(lang, names)
WriteValuesFile(None, [])
if __name__ == '__main__':
sys.exit(main())
...@@ -233,8 +233,6 @@ def main(argv): ...@@ -233,8 +233,6 @@ def main(argv):
parser.add_option('--package-name', parser.add_option('--package-name',
help='Java package name for these resources.') help='Java package name for these resources.')
parser.add_option('--android-manifest', help='Path to android manifest.') parser.add_option('--android-manifest', help='Path to android manifest.')
parser.add_option('--is-locale-resource', action='store_true',
help='Whether it is locale resource.')
parser.add_option('--resource-dirs', action='append', default=[], parser.add_option('--resource-dirs', action='append', default=[],
help='GYP-list of resource dirs') help='GYP-list of resource dirs')
...@@ -290,8 +288,6 @@ def main(argv): ...@@ -290,8 +288,6 @@ def main(argv):
help='GYP-list of proguard flag files to use in final apk.') help='GYP-list of proguard flag files to use in final apk.')
parser.add_option('--proguard-info', parser.add_option('--proguard-info',
help='Path to the proguard .info output for this apk.') help='Path to the proguard .info output for this apk.')
parser.add_option('--has-alternative-locale-resource', action='store_true',
help='Whether there is alternative-locale-resource in direct deps')
parser.add_option('--fail', parser.add_option('--fail',
help='GYP-list of error message lines to fail with.') help='GYP-list of error message lines to fail with.')
...@@ -339,21 +335,6 @@ def main(argv): ...@@ -339,21 +335,6 @@ def main(argv):
deps = Deps(direct_deps_config_paths) deps = Deps(direct_deps_config_paths)
all_inputs = deps.AllConfigPaths() all_inputs = deps.AllConfigPaths()
# Remove other locale resources if there is alternative_locale_resource in
# direct deps.
if options.has_alternative_locale_resource:
alternative = [r['path'] for r in deps.Direct('android_resources')
if r.get('is_locale_resource')]
# We can only have one locale resources in direct deps.
if len(alternative) != 1:
raise Exception('The number of locale resource in direct deps is wrong %d'
% len(alternative))
unwanted = [r['path'] for r in deps.All('android_resources')
if r.get('is_locale_resource') and r['path'] not in alternative]
for p in unwanted:
deps.RemoveNonDirectDep(p)
direct_library_deps = deps.Direct('java_library') direct_library_deps = deps.Direct('java_library')
all_library_deps = deps.All('java_library') all_library_deps = deps.All('java_library')
...@@ -485,8 +466,6 @@ def main(argv): ...@@ -485,8 +466,6 @@ def main(argv):
deps_info['package_name'] = options.package_name deps_info['package_name'] = options.package_name
if options.r_text: if options.r_text:
deps_info['r_text'] = options.r_text deps_info['r_text'] = options.r_text
if options.is_locale_resource:
deps_info['is_locale_resource'] = True
deps_info['resources_dirs'] = [] deps_info['resources_dirs'] = []
if options.resource_dirs: if options.resource_dirs:
......
...@@ -275,13 +275,6 @@ template("write_build_config") { ...@@ -275,13 +275,6 @@ template("write_build_config") {
rebase_path(invoker.r_text, root_build_dir), rebase_path(invoker.r_text, root_build_dir),
] ]
} }
if (defined(invoker.is_locale_resource) && invoker.is_locale_resource) {
args += [ "--is-locale-resource" ]
}
if (defined(invoker.has_alternative_locale_resource) &&
invoker.has_alternative_locale_resource) {
args += [ "--has-alternative-locale-resource" ]
}
} }
if (is_android_resources && defined(invoker.resource_dirs)) { if (is_android_resources && defined(invoker.resource_dirs)) {
......
...@@ -607,69 +607,6 @@ if (enable_java_templates) { ...@@ -607,69 +607,6 @@ if (enable_java_templates) {
} }
} }
# Creates a resources.zip with locale.pak files placed into appropriate
# resource configs (e.g. en-GB.pak -> res/raw-en/en_gb.pak). Also generates
# a locale_paks TypedArray so that resource files can be enumerated at runtime.
#
# If this target is included in the deps of an android resources/library/apk,
# the resources will be included with that target.
#
# Variables:
# sources: List of .pak files. Names must be of the form "en.pak" or
# "en-US.pak".
# deps: (optional) List of dependencies that might be needed to generate
# the .pak files.
#
# Example
# locale_pak_resources("locale_paks") {
# sources = [ "path/en-US.pak", "path/fr.pak", ... ]
# }
template("locale_pak_resources") {
set_sources_assignment_filter([])
assert(defined(invoker.sources))
_base_path = "$target_gen_dir/$target_name"
_resources_zip = _base_path + ".resources.zip"
_build_config = _base_path + ".build_config"
write_build_config("${target_name}__build_config") {
build_config = _build_config
resources_zip = _resources_zip
type = "android_resources"
is_locale_resource = true
}
action("${target_name}__create_resources_zip") {
forward_variables_from(invoker,
[
"deps",
"sources",
])
script = "//build/android/gyp/locale_pak_resources.py"
depfile = "$target_gen_dir/$target_name.d"
outputs = [
_resources_zip,
]
_rebased_sources = rebase_path(sources, root_build_dir)
args = [
"--locale-paks=${_rebased_sources}",
"--resources-zip",
rebase_path(_resources_zip, root_build_dir),
"--depfile",
rebase_path(depfile, root_build_dir),
]
}
group(target_name) {
public_deps = [
":${target_name}__build_config",
":${target_name}__create_resources_zip",
]
}
}
# Declare an Android resources target # Declare an Android resources target
# #
# This creates a resources zip file that will be used when building an Android # This creates a resources zip file that will be used when building an Android
...@@ -1209,6 +1146,65 @@ if (enable_java_templates) { ...@@ -1209,6 +1146,65 @@ if (enable_java_templates) {
} }
} }
# Creates android assets for locale pak files and a srcjar with a java class
# containing the pak file paths so that they can be extracted as necessary.
#
# Variables:
# sources: List of .pak files. Names must be of the form "en.pak" or
# "en-US.pak".
#
# Example
# locale_pak_assets("chrome_locale_pak") {
# sources = [ "path/en-US.pak", "path/fr.pak", ... ]
# }
#
# android_assets("chrome_public_apk_assets") {
# deps = [ "chrome_locale_pak_assets" ]
# }
#
# chrome_public_apk_tmpl(target_name) {
# srcjar_deps = [ "chrome_locale_pak_srcjar" ]
# }
template("locale_pak_assets") {
set_sources_assignment_filter([])
action("${target_name}_srcjar") {
_output_path = "$target_gen_dir/$target_name.srcjar"
_target = get_label_info(":$target_name", "label_no_toolchain")
forward_variables_from(invoker,
[
"deps",
"sources",
])
script = "//build/android/gyp/locale_pak_assets.py"
depfile = "$target_gen_dir/$target_name.d"
_rebased_sources = rebase_path(sources, root_build_dir)
outputs = [
_output_path,
]
args = [
"--locale-paks=${_rebased_sources}",
"--srcjar",
rebase_path(_output_path, root_build_dir),
"--depfile",
rebase_path(depfile, root_build_dir),
"--target",
_target,
]
}
android_assets("${target_name}_assets") {
forward_variables_from(invoker,
[
"sources",
"disable_compression",
])
}
}
# Declare a java library target for a prebuilt jar # Declare a java library target for a prebuilt jar
# #
# Variables # Variables
...@@ -1437,8 +1433,6 @@ if (enable_java_templates) { ...@@ -1437,8 +1433,6 @@ if (enable_java_templates) {
# testonly: Marks this target as "test-only". # testonly: Marks this target as "test-only".
# write_asset_list: Adds an extra file to the assets, which contains a list of # write_asset_list: Adds an extra file to the assets, which contains a list of
# all other asset files. # all other asset files.
# alternative_locale_resource_dep: The locale resource target which overrides
# any exsting locale resources in dep graph.
# requires_sdk_api_level_23: If defined and true, the apk is intended for # requires_sdk_api_level_23: If defined and true, the apk is intended for
# installation only on Android M or later. In these releases the system # installation only on Android M or later. In these releases the system
# linker does relocation unpacking, so we can enable it unconditionally. # linker does relocation unpacking, so we can enable it unconditionally.
...@@ -1671,11 +1665,6 @@ if (enable_java_templates) { ...@@ -1671,11 +1665,6 @@ if (enable_java_templates) {
possible_config_deps = invoker.deps possible_config_deps = invoker.deps
} }
if (defined(invoker.alternative_locale_resource_dep)) {
possible_config_deps += [ invoker.alternative_locale_resource_dep ]
has_alternative_locale_resource = true
}
# Added emma to the target's classpath via its .build_config. # Added emma to the target's classpath via its .build_config.
if (emma_coverage && !_emma_never_instrument) { if (emma_coverage && !_emma_never_instrument) {
possible_config_deps += [ "//third_party/android_tools:emma_device" ] possible_config_deps += [ "//third_party/android_tools:emma_device" ]
...@@ -1726,9 +1715,6 @@ if (enable_java_templates) { ...@@ -1726,9 +1715,6 @@ if (enable_java_templates) {
if (defined(invoker.deps)) { if (defined(invoker.deps)) {
deps += invoker.deps deps += invoker.deps
} }
if (defined(invoker.alternative_locale_resource_dep)) {
deps += [ invoker.alternative_locale_resource_dep ]
}
} }
_srcjar_deps += [ ":$process_resources_target" ] _srcjar_deps += [ ":$process_resources_target" ]
......
...@@ -66,7 +66,7 @@ jinja_template("chrome_sync_shell_android_manifest") { ...@@ -66,7 +66,7 @@ jinja_template("chrome_sync_shell_android_manifest") {
] ]
} }
locale_pak_resources("chrome_locale_paks") { locale_pak_assets("chrome_locale_pak") {
sources = [ sources = [
"$root_out_dir/locales/am.pak", "$root_out_dir/locales/am.pak",
"$root_out_dir/locales/ar.pak", "$root_out_dir/locales/ar.pak",
...@@ -125,7 +125,6 @@ android_resources("chrome_java_resources") { ...@@ -125,7 +125,6 @@ android_resources("chrome_java_resources") {
"//chrome/android/java/res_chromium", "//chrome/android/java/res_chromium",
] ]
deps = [ deps = [
":chrome_locale_paks",
":chrome_strings_grd", ":chrome_strings_grd",
"//chrome/app:java_strings_grd", "//chrome/app:java_strings_grd",
"//components/policy:app_restrictions_resources", "//components/policy:app_restrictions_resources",
...@@ -263,7 +262,11 @@ android_library("chrome_java") { ...@@ -263,7 +262,11 @@ android_library("chrome_java") {
# From java_sources.gni. # From java_sources.gni.
java_files = chrome_java_sources java_files = chrome_java_sources
# Allow downstream targets to specify their own locale pak files.
jar_excluded_patterns += [ "*/LocalePakFiles.class" ]
srcjar_deps += [ srcjar_deps += [
":chrome_locale_pak_srcjar",
"//chrome:page_info_connection_type_javagen", "//chrome:page_info_connection_type_javagen",
"//chrome:website_settings_action_javagen", "//chrome:website_settings_action_javagen",
"//components/browsing_data/core:browsing_data_utils_java", "//components/browsing_data/core:browsing_data_utils_java",
...@@ -671,9 +674,10 @@ template("chrome_public_apk_tmpl_shared") { ...@@ -671,9 +674,10 @@ template("chrome_public_apk_tmpl_shared") {
forward_variables_from(invoker, "*") forward_variables_from(invoker, "*")
native_lib_version_rule = "//build/util:chrome_version_json" native_lib_version_rule = "//build/util:chrome_version_json"
srcjar_deps = [ ":chrome_locale_pak_srcjar" ]
deps += [ deps += [
":chrome_java", ":chrome_java",
":chrome_locale_pak_assets",
":chrome_public_apk_assets", ":chrome_public_apk_assets",
":chrome_public_apk_resources", ":chrome_public_apk_resources",
"//base:base_java", "//base:base_java",
......
...@@ -24,7 +24,6 @@ import org.chromium.base.TraceEvent; ...@@ -24,7 +24,6 @@ import org.chromium.base.TraceEvent;
import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.library_loader.ProcessInitException; import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.banners.AppDetailsDelegate; import org.chromium.chrome.browser.banners.AppDetailsDelegate;
import org.chromium.chrome.browser.customtabs.CustomTabsConnection; import org.chromium.chrome.browser.customtabs.CustomTabsConnection;
import org.chromium.chrome.browser.datausage.ExternalDataUseObserver; import org.chromium.chrome.browser.datausage.ExternalDataUseObserver;
...@@ -73,6 +72,7 @@ import org.chromium.policy.AppRestrictionsProvider; ...@@ -73,6 +72,7 @@ import org.chromium.policy.AppRestrictionsProvider;
import org.chromium.policy.CombinedPolicyProvider; import org.chromium.policy.CombinedPolicyProvider;
import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener; import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener;
import org.chromium.printing.PrintingController; import org.chromium.printing.PrintingController;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ActivityWindowAndroid; import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.ResourceBundle; import org.chromium.ui.base.ResourceBundle;
...@@ -175,9 +175,7 @@ public class ChromeApplication extends ContentApplication { ...@@ -175,9 +175,7 @@ public class ChromeApplication extends ContentApplication {
@Override @Override
protected void initializeLibraryDependencies() { protected void initializeLibraryDependencies() {
// The ResourceExtractor is only needed by the browser process, but this will have no ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
// impact on the renderer process construction.
ResourceBundle.initializeLocalePaks(this, R.array.locale_paks);
ResourceExtractor.setResourcesToExtract(ResourceBundle.getActiveLocaleResources()); ResourceExtractor.setResourcesToExtract(ResourceBundle.getActiveLocaleResources());
} }
......
...@@ -4966,6 +4966,7 @@ if (is_android) { ...@@ -4966,6 +4966,7 @@ if (is_android) {
"//chrome/android:chrome_java", "//chrome/android:chrome_java",
"//content/public/android:content_java", "//content/public/android:content_java",
] ]
srcjar_deps = [ "//chrome/android:chrome_locale_pak_srcjar" ]
} }
} }
......
...@@ -4,17 +4,14 @@ ...@@ -4,17 +4,14 @@
package org.chromium.ui.base; package org.chromium.ui.base;
import android.content.Context; import org.chromium.base.LocaleUtils;
import android.content.res.Resources;
import android.content.res.TypedArray;
import org.chromium.base.ResourceExtractor;
import org.chromium.base.ThreadUtils; import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative; import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace; import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.SuppressFBWarnings; import org.chromium.base.annotations.SuppressFBWarnings;
import java.io.File; import java.io.File;
import java.util.ArrayList;
import java.util.Locale; import java.util.Locale;
/** /**
...@@ -23,54 +20,31 @@ import java.util.Locale; ...@@ -23,54 +20,31 @@ import java.util.Locale;
*/ */
@JNINamespace("ui") @JNINamespace("ui")
public class ResourceBundle { public class ResourceBundle {
private static ResourceExtractor.ResourceEntry[] sActiveLocaleResources; private static final String ASSET_DIR = "assets";
private static final String FALLBACK_LOCALE = "en-US";
/** private static String[] sActiveLocaleResources;
* Applies the reverse mapping done by locale_pak_resources.py.
*/
private static String toChromeLocaleName(String srcFileName) {
srcFileName = srcFileName.replace(".lpak", ".pak");
String[] parts = srcFileName.split("_");
if (parts.length > 1) {
int dotIdx = parts[1].indexOf('.');
return parts[0] + "-" + parts[1].substring(0, dotIdx).toUpperCase(Locale.ENGLISH)
+ parts[1].substring(dotIdx);
}
return srcFileName;
}
/** /**
* Initializes the list of locale packs for the active locale that are * Initializes the list of locale packs for the active locale that are present within the apk.
* present within the apk.
* *
* @param context Any context * @param localePakFiles An array of pak filenames.
* @param localePaksResId Resource ID locale_paks (generated by
* locale_pak_resources.py)
*/ */
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC") // Not thread-safe. @SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC") // Not thread-safe.
public static void initializeLocalePaks(Context context, int localePaksResId) { public static void initializeLocalePaks(String[] localePakFiles) {
ThreadUtils.assertOnUiThread(); ThreadUtils.assertOnUiThread();
assert sActiveLocaleResources == null; assert sActiveLocaleResources == null;
Resources resources = context.getResources(); String language = LocaleUtils.getLanguage(Locale.getDefault());
TypedArray resIds = resources.obtainTypedArray(localePaksResId); ArrayList<String> activeLocalePakFiles = new ArrayList<String>(localePakFiles.length);
try { for (String pakFileName : localePakFiles) {
int len = resIds.length(); if (pakFileName.startsWith(language) || pakFileName.startsWith(FALLBACK_LOCALE)) {
sActiveLocaleResources = new ResourceExtractor.ResourceEntry[len]; activeLocalePakFiles.add(pakFileName);
for (int i = 0; i < len; ++i) {
int resId = resIds.getResourceId(i, 0);
String resPath = resources.getString(resId);
String srcBaseName = new File(resPath).getName();
String dstBaseName = toChromeLocaleName(srcBaseName);
sActiveLocaleResources[i] = new ResourceExtractor.ResourceEntry(resId, resPath,
dstBaseName);
} }
} finally {
resIds.recycle();
} }
sActiveLocaleResources = activeLocalePakFiles.toArray(new String[0]);
} }
@SuppressFBWarnings("MS_EXPOSE_REP") // Don't modify the array. @SuppressFBWarnings("MS_EXPOSE_REP") // Don't modify the list.
public static ResourceExtractor.ResourceEntry[] getActiveLocaleResources() { public static String[] getActiveLocaleResources() {
return sActiveLocaleResources; return sActiveLocaleResources;
} }
...@@ -80,9 +54,9 @@ public class ResourceBundle { ...@@ -80,9 +54,9 @@ public class ResourceBundle {
return null; return null;
} }
String fileName = locale + ".pak"; String fileName = locale + ".pak";
for (ResourceExtractor.ResourceEntry entry : sActiveLocaleResources) { for (String resName : sActiveLocaleResources) {
if (fileName.equals(entry.extractedFileName)) { if (fileName.equals(resName)) {
return entry.pathWithinApk; return new File(ASSET_DIR, resName).toString();
} }
} }
return null; return null;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment