Commit 32fceb36 authored by khushalsagar's avatar khushalsagar Committed by Commit bot

Revert of Move language pak files to assets. (patchset #13 id:240001 of...

Revert of Move language pak files to assets. (patchset #13 id:240001 of https://codereview.chromium.org/2345143002/ )

Reason for revert:
Broke the internal build, https://uberchromegw.corp.google.com/i/internal.client.clank_tot/builders/instrumentation-mako-clankium-tot/builds/10008

Original issue's description:
> 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
>
> Committed: https://crrev.com/34ae27889dd8c8ffd5f5ca8c7bc10c17e57c12e2
> Cr-Commit-Position: refs/heads/master@{#420641}

TBR=agrieve@chromium.org,michaelbai@chromium.org,nyquist@chromium.org,tedchoc@chromium.org,estevenson@chromium.org
# Skipping CQ checks because original CL landed less than 1 days ago.
NOPRESUBMIT=true
NOTREECHECKS=true
NOTRY=true
BUG=529604

Review-Url: https://codereview.chromium.org/2369683002
Cr-Commit-Position: refs/heads/master@{#420791}
parent 4258ecf0
......@@ -53,8 +53,7 @@ webview_repack_locales("repack_locales") {
}
}
locale_pak_assets("locale_pak") {
disable_compression = true
locale_pak_resources("locale_paks") {
sources = [
"$root_out_dir/android_webview/locales/am.pak",
"$root_out_dir/android_webview/locales/ar.pak",
......@@ -187,7 +186,6 @@ android_assets("monochrome_webview_assets") {
android_assets("assets") {
deps = [
":locale_pak_assets",
":monochrome_webview_assets",
":pak_file_assets",
]
......@@ -217,6 +215,7 @@ android_resources("resources") {
resource_dirs = [ "java/res" ]
custom_package = "org.chromium.android_webview"
deps = [
":locale_paks",
":strings_grd",
]
}
......
......@@ -43,17 +43,11 @@ android_library("glue") {
deps = glue_library_deps
srcjar_deps = [
":glue_resource_rewriter",
"//android_webview:locale_pak_srcjar",
"//base:base_build_config_gen",
]
jar_excluded_patterns = [
# 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",
]
# New versions of BuildConfig.java will be created when creating an apk.
jar_excluded_patterns = [ "*/BuildConfig.class" ]
# Always build upstream or downstream target with public or internal
# framework jar respectively.
......
......@@ -48,6 +48,7 @@ import org.chromium.android_webview.AwResource;
import org.chromium.android_webview.AwServiceWorkerController;
import org.chromium.android_webview.AwSettings;
import org.chromium.android_webview.HttpAuthDatabase;
import org.chromium.android_webview.R;
import org.chromium.android_webview.ResourcesContextWrapperFactory;
import org.chromium.base.BuildConfig;
import org.chromium.base.CommandLine;
......@@ -63,7 +64,6 @@ import org.chromium.base.library_loader.LibraryProcessType;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.content.browser.ContentViewStatics;
import org.chromium.net.NetworkChangeNotifier;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ResourceBundle;
import java.io.File;
......@@ -393,7 +393,7 @@ public class WebViewChromiumFactoryProvider implements WebViewFactoryProvider {
// Make sure that ResourceProvider is initialized before starting the browser process.
final String webViewPackageName = WebViewFactory.getLoadedPackageInfo().packageName;
setUpResources(webViewPackageName, context);
ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
ResourceBundle.initializeLocalePaks(context, R.array.locale_paks);
initPlatSupportLibrary();
initNetworkChangeNotifier(context);
final int extraBindFlags = Context.BIND_EXTERNAL_SERVICE;
......
......@@ -14,8 +14,6 @@ template("system_webview_apk_tmpl") {
"//base:base_java",
]
srcjar_deps = [ "//android_webview:locale_pak_srcjar" ]
if (!defined(alternative_android_sdk_jar)) {
alternative_android_sdk_jar = webview_framework_jar
}
......
......@@ -48,8 +48,6 @@ android_apk("android_webview_apk") {
":libstandalonelibwebviewchromium",
]
srcjar_deps = [ "//android_webview:locale_pak_srcjar" ]
native_lib_version_rule = "//build/util:chrome_version_json"
_native_lib_file =
rebase_path("$root_gen_dir/CHROME_VERSION.json", root_build_dir)
......@@ -65,7 +63,6 @@ android_resources("android_webview_apk_resources") {
android_assets("android_webview_apk_assets") {
deps = [
"//android_webview:locale_pak_assets",
"//android_webview:pak_file_assets",
"//third_party/icu:icu_assets",
"//v8:v8_external_startup_data_assets",
......
......@@ -4,10 +4,10 @@
package org.chromium.android_webview.shell;
import org.chromium.android_webview.R;
import org.chromium.base.CommandLine;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.content.app.ContentApplication;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ResourceBundle;
/**
......@@ -25,7 +25,7 @@ public class AwShellApplication extends ContentApplication {
@Override
protected void initializeLibraryDependencies() {
ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
ResourceBundle.initializeLocalePaks(this, R.array.locale_paks);
}
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
......
......@@ -24,18 +24,8 @@ public class LocaleUtils {
* used by Chromium.
*/
public static String getLocale(Locale locale) {
String language = getLanguage(locale);
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();
String country = locale.getCountry();
// 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.
......@@ -48,7 +38,7 @@ public class LocaleUtils {
} else if ("tl".equals(language)) {
language = "fil";
}
return language;
return country.isEmpty() ? language : language + "-" + country;
}
/**
......
......@@ -36,7 +36,22 @@ public class ResourceExtractor {
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 String[] sResourcesToExtract = new String[0];
private static ResourceEntry[] sResourcesToExtract = new ResourceEntry[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 static final int BUFFER_SIZE = 16 * 1024;
......@@ -92,15 +107,16 @@ public class ResourceExtractor {
TraceEvent.begin("WalkAssets");
byte[] buffer = new byte[BUFFER_SIZE];
try {
for (String resource : sResourcesToExtract) {
File output = new File(outputDir, resource);
for (ResourceEntry entry : sResourcesToExtract) {
File output = new File(outputDir, entry.extractedFileName);
// TODO(agrieve): It would be better to check that .length == expectedLength.
// http://crbug.com/606413
if (output.length() != 0) {
continue;
}
TraceEvent.begin("ExtractResource");
InputStream inputStream = mContext.getAssets().open(resource);
InputStream inputStream = mContext.getResources().openRawResource(
entry.resourceId);
try {
extractResourceHelper(inputStream, output, buffer);
} finally {
......@@ -178,10 +194,10 @@ public class ResourceExtractor {
* and moved to {@link #getOutputDir()}.
*/
@SuppressFBWarnings("EI_EXPOSE_STATIC_REP2")
public static void setResourcesToExtract(String[] resources) {
public static void setResourcesToExtract(ResourceEntry[] entries) {
assert (sInstance == null || sInstance.mExtractTask == null)
: "Must be called before startExtractingResources is called";
sResourcesToExtract = resources;
sResourcesToExtract = entries;
}
private ResourceExtractor(Context context) {
......
......@@ -24,7 +24,7 @@ public class BlimpApplication extends BaseChromiumApplication {
public void onCreate() {
super.onCreate();
ContextUtils.initApplicationContext(this);
ResourceExtractor.setResourcesToExtract(new String[0]);
ResourceExtractor.setResourcesToExtract(new ResourceExtractor.ResourceEntry[0]);
PathUtils.setPrivateDataDirectorySuffix(PRIVATE_DATA_DIRECTORY_SUFFIX, this);
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,6 +233,8 @@ def main(argv):
parser.add_option('--package-name',
help='Java package name for these resources.')
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=[],
help='GYP-list of resource dirs')
......@@ -288,6 +290,8 @@ def main(argv):
help='GYP-list of proguard flag files to use in final apk.')
parser.add_option('--proguard-info',
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',
help='GYP-list of error message lines to fail with.')
......@@ -335,6 +339,21 @@ def main(argv):
deps = Deps(direct_deps_config_paths)
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')
all_library_deps = deps.All('java_library')
......@@ -466,6 +485,8 @@ def main(argv):
deps_info['package_name'] = options.package_name
if 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'] = []
if options.resource_dirs:
......
......@@ -275,6 +275,13 @@ template("write_build_config") {
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)) {
......
......@@ -607,6 +607,69 @@ 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
#
# This creates a resources zip file that will be used when building an Android
......@@ -1146,65 +1209,6 @@ 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
#
# Variables
......@@ -1433,6 +1437,8 @@ if (enable_java_templates) {
# testonly: Marks this target as "test-only".
# write_asset_list: Adds an extra file to the assets, which contains a list of
# 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
# installation only on Android M or later. In these releases the system
# linker does relocation unpacking, so we can enable it unconditionally.
......@@ -1665,6 +1671,11 @@ if (enable_java_templates) {
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.
if (emma_coverage && !_emma_never_instrument) {
possible_config_deps += [ "//third_party/android_tools:emma_device" ]
......@@ -1715,6 +1726,9 @@ if (enable_java_templates) {
if (defined(invoker.deps)) {
deps += invoker.deps
}
if (defined(invoker.alternative_locale_resource_dep)) {
deps += [ invoker.alternative_locale_resource_dep ]
}
}
_srcjar_deps += [ ":$process_resources_target" ]
......
......@@ -66,7 +66,7 @@ jinja_template("chrome_sync_shell_android_manifest") {
]
}
locale_pak_assets("chrome_locale_pak") {
locale_pak_resources("chrome_locale_paks") {
sources = [
"$root_out_dir/locales/am.pak",
"$root_out_dir/locales/ar.pak",
......@@ -125,6 +125,7 @@ android_resources("chrome_java_resources") {
"//chrome/android/java/res_chromium",
]
deps = [
":chrome_locale_paks",
":chrome_strings_grd",
"//chrome/app:java_strings_grd",
"//components/policy:app_restrictions_resources",
......@@ -262,11 +263,7 @@ android_library("chrome_java") {
# From java_sources.gni.
java_files = chrome_java_sources
# Allow downstream targets to specify their own locale pak files.
jar_excluded_patterns += [ "*/LocalePakFiles.class" ]
srcjar_deps += [
":chrome_locale_pak_srcjar",
"//chrome:page_info_connection_type_javagen",
"//chrome:website_settings_action_javagen",
"//components/browsing_data/core:browsing_data_utils_java",
......@@ -674,10 +671,9 @@ template("chrome_public_apk_tmpl_shared") {
forward_variables_from(invoker, "*")
native_lib_version_rule = "//build/util:chrome_version_json"
srcjar_deps = [ ":chrome_locale_pak_srcjar" ]
deps += [
":chrome_java",
":chrome_locale_pak_assets",
":chrome_public_apk_assets",
":chrome_public_apk_resources",
"//base:base_java",
......
......@@ -24,6 +24,7 @@ import org.chromium.base.TraceEvent;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.base.library_loader.ProcessInitException;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.banners.AppDetailsDelegate;
import org.chromium.chrome.browser.customtabs.CustomTabsConnection;
import org.chromium.chrome.browser.datausage.ExternalDataUseObserver;
......@@ -72,7 +73,6 @@ import org.chromium.policy.AppRestrictionsProvider;
import org.chromium.policy.CombinedPolicyProvider;
import org.chromium.policy.CombinedPolicyProvider.PolicyChangeListener;
import org.chromium.printing.PrintingController;
import org.chromium.ui.LocalePakFiles;
import org.chromium.ui.base.ActivityWindowAndroid;
import org.chromium.ui.base.ResourceBundle;
......@@ -175,7 +175,9 @@ public class ChromeApplication extends ContentApplication {
@Override
protected void initializeLibraryDependencies() {
ResourceBundle.initializeLocalePaks(LocalePakFiles.getFiles());
// The ResourceExtractor is only needed by the browser process, but this will have no
// impact on the renderer process construction.
ResourceBundle.initializeLocalePaks(this, R.array.locale_paks);
ResourceExtractor.setResourcesToExtract(ResourceBundle.getActiveLocaleResources());
}
......
......@@ -4967,7 +4967,6 @@ if (is_android) {
"//chrome/android:chrome_java",
"//content/public/android:content_java",
]
srcjar_deps = [ "//chrome/android:chrome_locale_pak_srcjar" ]
}
}
......
......@@ -4,14 +4,17 @@
package org.chromium.ui.base;
import org.chromium.base.LocaleUtils;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import org.chromium.base.ResourceExtractor;
import org.chromium.base.ThreadUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.SuppressFBWarnings;
import java.io.File;
import java.util.ArrayList;
import java.util.Locale;
/**
......@@ -20,31 +23,54 @@ import java.util.Locale;
*/
@JNINamespace("ui")
public class ResourceBundle {
private static final String ASSET_DIR = "assets";
private static final String FALLBACK_LOCALE = "en-US";
private static String[] sActiveLocaleResources;
private static ResourceExtractor.ResourceEntry[] 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 present within the apk.
* Initializes the list of locale packs for the active locale that are
* present within the apk.
*
* @param localePakFiles An array of pak filenames.
* @param context Any context
* @param localePaksResId Resource ID locale_paks (generated by
* locale_pak_resources.py)
*/
@SuppressFBWarnings("LI_LAZY_INIT_UPDATE_STATIC") // Not thread-safe.
public static void initializeLocalePaks(String[] localePakFiles) {
public static void initializeLocalePaks(Context context, int localePaksResId) {
ThreadUtils.assertOnUiThread();
assert sActiveLocaleResources == null;
String language = LocaleUtils.getLanguage(Locale.getDefault());
ArrayList<String> activeLocalePakFiles = new ArrayList<String>(localePakFiles.length);
for (String pakFileName : localePakFiles) {
if (pakFileName.startsWith(language) || pakFileName.startsWith(FALLBACK_LOCALE)) {
activeLocalePakFiles.add(pakFileName);
Resources resources = context.getResources();
TypedArray resIds = resources.obtainTypedArray(localePaksResId);
try {
int len = resIds.length();
sActiveLocaleResources = new ResourceExtractor.ResourceEntry[len];
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 list.
public static String[] getActiveLocaleResources() {
@SuppressFBWarnings("MS_EXPOSE_REP") // Don't modify the array.
public static ResourceExtractor.ResourceEntry[] getActiveLocaleResources() {
return sActiveLocaleResources;
}
......@@ -54,9 +80,9 @@ public class ResourceBundle {
return null;
}
String fileName = locale + ".pak";
for (String resName : sActiveLocaleResources) {
if (fileName.equals(resName)) {
return new File(ASSET_DIR, resName).toString();
for (ResourceExtractor.ResourceEntry entry : sActiveLocaleResources) {
if (fileName.equals(entry.extractedFileName)) {
return entry.pathWithinApk;
}
}
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