Commit b99472e9 authored by Ian Vollick's avatar Ian Vollick Committed by Commit Bot

Share strings between native and Java

Creates a script that can be used to generate Java files to
expose native strings to Java, giving us a single source of
truth for these constants.

Bug: 937280
Change-Id: I1f0804bdfff8101dfd149612acd44360ae0dc2c0
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1495747
Commit-Queue: Ian Vollick <vollick@chromium.org>
Auto-Submit: Ian Vollick <vollick@chromium.org>
Reviewed-by: default avatarScott Violet <sky@chromium.org>
Reviewed-by: default avatarAndrew Grieve <agrieve@chromium.org>
Cr-Commit-Position: refs/heads/master@{#638754}
parent a9528b2d
...@@ -678,6 +678,7 @@ _ANDROID_SPECIFIC_PYDEPS_FILES = [ ...@@ -678,6 +678,7 @@ _ANDROID_SPECIFIC_PYDEPS_FILES = [
'build/android/gyp/generate_linker_version_script.pydeps', 'build/android/gyp/generate_linker_version_script.pydeps',
'build/android/gyp/ijar.pydeps', 'build/android/gyp/ijar.pydeps',
'build/android/gyp/java_cpp_enum.pydeps', 'build/android/gyp/java_cpp_enum.pydeps',
'build/android/gyp/java_cpp_strings.pydeps',
'build/android/gyp/javac.pydeps', 'build/android/gyp/javac.pydeps',
'build/android/gyp/jinja_template.pydeps', 'build/android/gyp/jinja_template.pydeps',
'build/android/gyp/lint.pydeps', 'build/android/gyp/lint.pydeps',
......
...@@ -15,6 +15,7 @@ import textwrap ...@@ -15,6 +15,7 @@ import textwrap
import zipfile import zipfile
from util import build_utils from util import build_utils
from util import java_cpp_utils
# List of C++ types that are compatible with the Java code generated by this # List of C++ types that are compatible with the Java code generated by this
# script. # script.
...@@ -115,8 +116,8 @@ class EnumDefinition(object): ...@@ -115,8 +116,8 @@ class EnumDefinition(object):
self.comments = StripEntries(self.comments) self.comments = StripEntries(self.comments)
def _NormalizeNames(self): def _NormalizeNames(self):
self.entries = _TransformKeys(self.entries, _KCamelToShouty) self.entries = _TransformKeys(self.entries, java_cpp_utils.KCamelToShouty)
self.comments = _TransformKeys(self.comments, _KCamelToShouty) self.comments = _TransformKeys(self.comments, java_cpp_utils.KCamelToShouty)
def _TransformKeys(d, func): def _TransformKeys(d, func):
...@@ -133,25 +134,6 @@ def _TransformKeys(d, func): ...@@ -133,25 +134,6 @@ def _TransformKeys(d, func):
return ret return ret
def _KCamelToShouty(s):
"""Convert |s| from kCamelCase or CamelCase to SHOUTY_CASE.
kFooBar -> FOO_BAR
FooBar -> FOO_BAR
FooBAR9 -> FOO_BAR9
FooBARBaz -> FOO_BAR_BAZ
"""
if not re.match(r'^k?([A-Z][^A-Z]+|[A-Z0-9]+)+$', s):
return s
# Strip the leading k.
s = re.sub(r'^k', '', s)
# Add _ between title words and anything else.
s = re.sub(r'([^_])([A-Z][^A-Z_0-9]+)', r'\1_\2', s)
# Add _ between lower -> upper transitions.
s = re.sub(r'([^A-Z_0-9])([A-Z])', r'\1_\2', s)
return s.upper()
class DirectiveSet(object): class DirectiveSet(object):
class_name_override_key = 'CLASS_NAME_OVERRIDE' class_name_override_key = 'CLASS_NAME_OVERRIDE'
enum_package_key = 'ENUM_PACKAGE' enum_package_key = 'ENUM_PACKAGE'
...@@ -334,8 +316,6 @@ class HeaderParser(object): ...@@ -334,8 +316,6 @@ class HeaderParser(object):
if single_line_enum: if single_line_enum:
self._ParseSingleLineEnum(single_line_enum.group('enum_entries')) self._ParseSingleLineEnum(single_line_enum.group('enum_entries'))
def GetScriptName():
return os.path.basename(os.path.abspath(sys.argv[0]))
def DoGenerate(source_paths): def DoGenerate(source_paths):
for source_path in source_paths: for source_path in source_paths:
...@@ -401,8 +381,8 @@ ${ENUM_ENTRIES} ...@@ -401,8 +381,8 @@ ${ENUM_ENTRIES}
subsequent_indent=enum_comments_indent, subsequent_indent=enum_comments_indent,
width=100) width=100)
enum_entries_string.append(' /**') enum_entries_string.append(' /**')
enum_entries_string.append( enum_entries_string.append('\n'.join(
'\n'.join(comments_line_wrapper.wrap(enum_comments))) comments_line_wrapper.wrap(enum_comments)))
enum_entries_string.append(' */') enum_entries_string.append(' */')
enum_entries_string.append(enum_template.substitute(values)) enum_entries_string.append(enum_template.substitute(values))
enum_names.append(enum_definition.class_name + '.' + enum_name) enum_names.append(enum_definition.class_name + '.' + enum_name)
...@@ -419,7 +399,7 @@ ${ENUM_ENTRIES} ...@@ -419,7 +399,7 @@ ${ENUM_ENTRIES}
'ENUM_ENTRIES': enum_entries_string, 'ENUM_ENTRIES': enum_entries_string,
'PACKAGE': enum_definition.enum_package, 'PACKAGE': enum_definition.enum_package,
'INT_DEF': enum_names_string, 'INT_DEF': enum_names_string,
'SCRIPT_NAME': GetScriptName(), 'SCRIPT_NAME': java_cpp_utils.GetScriptName(),
'SOURCE_PATH': source_path, 'SOURCE_PATH': source_path,
'YEAR': str(date.today().year) 'YEAR': str(date.today().year)
} }
......
...@@ -4,4 +4,5 @@ ...@@ -4,4 +4,5 @@
java_cpp_enum.py java_cpp_enum.py
util/__init__.py util/__init__.py
util/build_utils.py util/build_utils.py
util/java_cpp_utils.py
util/md5_check.py util/md5_check.py
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
"""Tests for enum_preprocess.py. """Tests for enum_preprocess.py.
This test suite containss various tests for the C++ -> Java enum generator. This test suite contains various tests for the C++ -> Java enum generator.
""" """
import collections import collections
...@@ -13,8 +13,9 @@ from datetime import date ...@@ -13,8 +13,9 @@ from datetime import date
import unittest import unittest
import java_cpp_enum import java_cpp_enum
from java_cpp_enum import EnumDefinition, GenerateOutput, GetScriptName from java_cpp_enum import EnumDefinition, GenerateOutput
from java_cpp_enum import HeaderParser from java_cpp_enum import HeaderParser
from util import java_cpp_utils
class TestPreprocess(unittest.TestCase): class TestPreprocess(unittest.TestCase):
...@@ -65,8 +66,8 @@ public @interface ClassName { ...@@ -65,8 +66,8 @@ public @interface ClassName {
long_comment = ('This is a multiple line comment that is really long. ' long_comment = ('This is a multiple line comment that is really long. '
'This is a multiple line comment that is') 'This is a multiple line comment that is')
self.assertEqual( self.assertEqual(
expected % (date.today().year, GetScriptName(), long_comment), expected % (date.today().year, java_cpp_utils.GetScriptName(),
output) long_comment), output)
def testParseSimpleEnum(self): def testParseSimpleEnum(self):
test_data = """ test_data = """
......
#!/user/bin/env python
#
# Copyright 2019 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.
import argparse
import os
import re
import sys
import zipfile
from util import build_utils
from util import java_cpp_utils
def _ToUpper(match):
return match.group(1).upper()
def _GetClassName(source_path):
name = os.path.basename(os.path.abspath(source_path))
(name, _) = os.path.splitext(name)
name = re.sub(r'_([a-z])', _ToUpper, name)
name = re.sub(r'^(.)', _ToUpper, name)
return name
class _String(object):
def __init__(self, name, value, comments):
self.name = java_cpp_utils.KCamelToShouty(name)
self.value = value
self.comments = '\n'.join(' ' + x for x in comments)
def Format(self):
return '%s\n public static final String %s = %s;' % (
self.comments, self.name, self.value)
def ParseTemplateFile(lines):
package_re = re.compile(r'^package (.*);')
class_re = re.compile(r'.*class (.*) {')
package = ''
class_name = ''
for line in lines:
package_line = package_re.match(line)
if package_line:
package = package_line.groups()[0]
class_line = class_re.match(line)
if class_line:
class_name = class_line.groups()[0]
break
return package, class_name
# TODO(crbug.com/937282): It should be possible to parse a file for more than
# string constants. However, this currently only handles extracting string
# constants from a file (and all string constants from that file). Work will
# be needed if we want to annotate specific constants or non string constants
# in the file to be parsed.
class StringFileParser(object):
SINGLE_LINE_COMMENT_RE = re.compile(r'\s*(// [^\n]*)')
STRING_RE = re.compile(r'\s*const char k(.*)\[\]\s*=\s*(?:(".*"))?')
VALUE_RE = re.compile(r'\s*("[^"]*")')
def __init__(self, lines, path=''):
self._lines = lines
self._path = path
self._in_string = False
self._in_comment = False
self._package = ''
self._current_comments = []
self._current_name = ''
self._current_value = ''
self._strings = []
def _Reset(self):
self._current_comments = []
self._current_name = ''
self._current_value = ''
self._in_string = False
self._in_comment = False
def _AppendString(self):
self._strings.append(
_String(self._current_name, self._current_value,
self._current_comments))
self._Reset()
def _ParseValue(self, line):
value_line = StringFileParser.VALUE_RE.match(line)
if value_line:
self._current_value = value_line.groups()[0]
self._AppendString()
else:
self._Reset()
def _ParseComment(self, line):
comment_line = StringFileParser.SINGLE_LINE_COMMENT_RE.match(line)
if comment_line:
self._current_comments.append(comment_line.groups()[0])
self._in_comment = True
self._in_string = True
return True
else:
self._in_comment = False
return False
def _ParseString(self, line):
string_line = StringFileParser.STRING_RE.match(line)
if string_line:
self._current_name = string_line.groups()[0]
if string_line.groups()[1]:
self._current_value = string_line.groups()[1]
self._AppendString()
return True
else:
self._in_string = False
return False
def _ParseLine(self, line):
if not self._in_string:
self._ParseComment(line)
return
if self._in_comment:
if self._ParseComment(line):
return
if not self._ParseString(line):
self._Reset()
return
if self._in_string:
self._ParseValue(line)
def Parse(self):
for line in self._lines:
self._ParseLine(line)
return self._strings
def _GenerateOutput(template, source_path, template_path, strings):
description_template = """
// This following string constants were inserted by
// {SCRIPT_NAME}
// From
// {SOURCE_PATH}
// Into
// {TEMPLATE_PATH}
"""
values = {
'SCRIPT_NAME': java_cpp_utils.GetScriptName(),
'SOURCE_PATH': source_path,
'TEMPLATE_PATH': template_path,
}
description = description_template.format(**values)
native_strings = '\n\n'.join(x.Format() for x in strings)
values = {
'NATIVE_STRINGS': description + native_strings,
}
return template.format(**values)
def _ParseStringFile(path):
with open(path) as f:
return StringFileParser(f.readlines(), path).Parse()
def _Generate(source_paths, template_path):
with open(template_path) as f:
lines = f.readlines()
template = ''.join(lines)
for source_path in source_paths:
strings = _ParseStringFile(source_path)
package, class_name = ParseTemplateFile(lines)
package_path = package.replace('.', os.path.sep)
file_name = class_name + '.java'
output_path = os.path.join(package_path, file_name)
output = _GenerateOutput(template, source_path, template_path, strings)
yield output, output_path
def _Main(argv):
parser = argparse.ArgumentParser()
parser.add_argument(
'--srcjar',
required=True,
help='When specified, a .srcjar at the given path is '
'created instead of individual .java files.')
parser.add_argument(
'--template',
required=True,
help='Can be used to provide a context into which the'
'new string constants will be inserted.')
parser.add_argument(
'inputs', nargs='+', help='Input file(s)', metavar='INPUTFILE')
args = parser.parse_args(argv)
with build_utils.AtomicOutput(args.srcjar) as f:
with zipfile.ZipFile(f, 'w', zipfile.ZIP_STORED) as srcjar:
for data, path in _Generate(args.inputs, args.template):
build_utils.AddToZipHermetic(srcjar, path, data=data)
if __name__ == '__main__':
_Main(sys.argv[1:])
# Generated by running:
# build/print_python_deps.py --root build/android/gyp --output build/android/gyp/java_cpp_strings.pydeps build/android/gyp/java_cpp_strings.py
../../gn_helpers.py
java_cpp_strings.py
util/__init__.py
util/build_utils.py
util/java_cpp_utils.py
util/md5_check.py
#!/usr/bin/env python
# Copyright 2019 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.
"""Tests for java_cpp_strings.py.
This test suite contains various tests for the C++ -> Java string generator.
"""
import unittest
import java_cpp_strings
class _TestStringsParser(unittest.TestCase):
def testParseComments(self):
test_data = """
/**
* This should be ignored as well.
*/
// Comment followed by a blank line.
// Comment followed by unrelated code.
int foo() { return 3; }
// Real comment.
const char kASwitch[] = "a-value";
// Real comment that spans
// multiple lines.
const char kAnotherSwitch[] = "another-value";
// Comment followed by nothing.
""".split('\n')
strings = java_cpp_strings.StringFileParser(test_data).Parse()
self.assertEqual(2, len(strings))
self.assertEqual('A_SWITCH', strings[0].name)
self.assertEqual('"a-value"', strings[0].value)
self.assertEqual(1, len(strings[0].comments.split('\n')))
self.assertEqual('ANOTHER_SWITCH', strings[1].name)
self.assertEqual('"another-value"', strings[1].value)
self.assertEqual(2, len(strings[1].comments.split('\n')))
def testStringValues(self):
test_data = """
// Single line string constants.
const char kAString[] = "a-value";
// Single line switch with a big space.
const char kAStringWithSpace[] = "a-value";
// Wrapped constant definition.
const char kAStringWithAVeryLongNameThatWillHaveToWrap[] =
"a-string-with-a-very-long-name-that-will-have-to-wrap";
// This is erroneous and should be ignored.
const char kInvalidLineBreak[] =
"invalid-line-break";
""".split('\n')
strings = java_cpp_strings.StringFileParser(test_data).Parse()
self.assertEqual(3, len(strings))
self.assertEqual('A_STRING', strings[0].name)
self.assertEqual('"a-value"', strings[0].value)
self.assertEqual('A_STRING_WITH_SPACE', strings[1].name)
self.assertEqual('"a-value"', strings[1].value)
self.assertEqual('A_STRING_WITH_A_VERY_LONG_NAME_THAT_WILL_HAVE_TO_WRAP',
strings[2].name)
self.assertEqual('"a-string-with-a-very-long-name-that-will-have-to-wrap"',
strings[2].value)
def testTemplateParsing(self):
test_data = """
// Copyright {YEAR} 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 autogenerated by
// {SCRIPT_NAME}
// From
// {SOURCE_PATH}, and
// {TEMPLATE_PATH}
package my.java.package;
public any sort of class MyClass {{
{NATIVE_STRINGS}
}}
""".split('\n')
package, class_name = java_cpp_strings.ParseTemplateFile(test_data)
self.assertEqual('my.java.package', package)
self.assertEqual('MyClass', class_name)
if __name__ == '__main__':
unittest.main()
#!/user/bin/env python
#
# Copyright 2019 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.
import os
import re
import sys
def GetScriptName():
return os.path.basename(os.path.abspath(sys.argv[0]))
def KCamelToShouty(s):
"""Convert |s| from kCamelCase or CamelCase to SHOUTY_CASE.
kFooBar -> FOO_BAR
FooBar -> FOO_BAR
FooBAR9 -> FOO_BAR9
FooBARBaz -> FOO_BAR_BAZ
"""
if not re.match(r'^k?([A-Z][^A-Z]+|[A-Z0-9]+)+$', s):
return s
# Strip the leading k.
s = re.sub(r'^k', '', s)
# Add _ between title words and anything else.
s = re.sub(r'([^_])([A-Z][^A-Z_0-9]+)', r'\1_\2', s)
# Add _ between lower -> upper transitions.
s = re.sub(r'([^A-Z_0-9])([A-Z])', r'\1_\2', s)
return s.upper()
...@@ -130,7 +130,8 @@ UBSAN_OPTIONS = ( ...@@ -130,7 +130,8 @@ UBSAN_OPTIONS = (
# TODO(jbudorick): Rework this into testing/buildbot/ # TODO(jbudorick): Rework this into testing/buildbot/
PYTHON_UNIT_TEST_SUITES = { PYTHON_UNIT_TEST_SUITES = {
'pylib_py_unittests': { 'pylib_py_unittests': {
'path': os.path.join(DIR_SOURCE_ROOT, 'build', 'android'), 'path':
os.path.join(DIR_SOURCE_ROOT, 'build', 'android'),
'test_modules': [ 'test_modules': [
'devil.android.device_utils_test', 'devil.android.device_utils_test',
'devil.android.md5sum_test', 'devil.android.md5sum_test',
...@@ -140,9 +141,11 @@ PYTHON_UNIT_TEST_SUITES = { ...@@ -140,9 +141,11 @@ PYTHON_UNIT_TEST_SUITES = {
] ]
}, },
'gyp_py_unittests': { 'gyp_py_unittests': {
'path': os.path.join(DIR_SOURCE_ROOT, 'build', 'android', 'gyp'), 'path':
os.path.join(DIR_SOURCE_ROOT, 'build', 'android', 'gyp'),
'test_modules': [ 'test_modules': [
'java_cpp_enum_tests', 'java_cpp_enum_tests',
'java_cpp_strings_tests',
'java_google_api_keys_tests', 'java_google_api_keys_tests',
'extract_unwind_tables_tests', 'extract_unwind_tables_tests',
] ]
......
...@@ -635,6 +635,85 @@ if (enable_java_templates) { ...@@ -635,6 +635,85 @@ if (enable_java_templates) {
} }
} }
# Declare a target for generating Java classes with string constants matching
# those found in C++ files using a python script.
#
# This target will create a single .srcjar. Adding this target to an
# android_library target's srcjar_deps will make the generated java files be
# included in that library's final outputs.
#
# Variables
# sources: list of files to be processed by the script. For each string
# constant in the source files, the script will add a corresponding
# Java string to the specified template file.
# Example
# java_cpp_strings("foo_switches") {
# sources = [
# "src/foo_switches.cc",
# ]
# template = "src/templates/FooSwitches.java.tmpl
# }
#
# foo_switches.cc:
#
# // A switch.
# const char kASwitch = "a-switch";
#
# FooSwitches.java.tmpl
#
# // Copyright {YEAR} 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 autogenerated by
# // {SCRIPT_NAME}
# // From
# // {SOURCE_PATH}, and
# // {TEMPLATE_PATH}
#
# package my.java.package;
#
# public abstract class FooSwitches {{
# // ...snip...
# {NATIVE_STRINGS}
# // ...snip...
# }}
#
# result:
# A FooSwitches.java file, defining a class named FooSwitches in the package
# my.java.package.
template("java_cpp_strings") {
set_sources_assignment_filter([])
action_with_pydeps(target_name) {
forward_variables_from(invoker,
[
"sources",
"testonly",
"visibility",
])
# The sources aren't compiled so don't check their dependencies.
check_includes = false
script = "//build/android/gyp/java_cpp_strings.py"
_srcjar_path = "${target_gen_dir}/${target_name}.srcjar"
_rebased_srcjar_path = rebase_path(_srcjar_path, root_build_dir)
_rebased_sources = rebase_path(invoker.sources, root_build_dir)
_rebased_template = rebase_path(invoker.template, root_build_dir)
args = [
"--srcjar=$_rebased_srcjar_path",
"--template=$_rebased_template",
]
args += _rebased_sources
sources += [ invoker.template ]
outputs = [
_srcjar_path,
]
}
}
# Declare a target for processing a Jinja template. # Declare a target for processing a Jinja template.
# #
# Variables # Variables
......
...@@ -355,6 +355,7 @@ android_library("chrome_java") { ...@@ -355,6 +355,7 @@ android_library("chrome_java") {
srcjar_deps = [ srcjar_deps = [
":chrome_android_java_enums_srcjar", ":chrome_android_java_enums_srcjar",
":chrome_android_java_switches_srcjar",
":chrome_android_java_google_api_keys_srcjar", ":chrome_android_java_google_api_keys_srcjar",
":photo_picker_aidl", ":photo_picker_aidl",
":resource_id_javagen", ":resource_id_javagen",
...@@ -496,6 +497,13 @@ java_cpp_enum("chrome_vr_android_java_enums_srcjar") { ...@@ -496,6 +497,13 @@ java_cpp_enum("chrome_vr_android_java_enums_srcjar") {
] ]
} }
java_cpp_strings("chrome_android_java_switches_srcjar") {
sources = [
"//chrome/common/chrome_switches.cc",
]
template = "//chrome/android/java_templates/ChromeSwitches.java.tmpl"
}
proto_java_library("document_tab_model_info_proto_java") { proto_java_library("document_tab_model_info_proto_java") {
proto_path = "java/src/org/chromium/chrome/browser/tabmodel/document" proto_path = "java/src/org/chromium/chrome/browser/tabmodel/document"
sources = [ sources = [
...@@ -718,6 +726,7 @@ android_library("chrome_test_java") { ...@@ -718,6 +726,7 @@ android_library("chrome_test_java") {
"//components/web_restrictions:provider_java", "//components/web_restrictions:provider_java",
"//content/public/android:content_java", "//content/public/android:content_java",
"//content/public/test/android:content_java_test_support", "//content/public/test/android:content_java_test_support",
"//media/base/android:java_switches",
"//media/base/android:media_java", "//media/base/android:media_java",
"//mojo/public/java:bindings_java", "//mojo/public/java:bindings_java",
"//mojo/public/java:system_java", "//mojo/public/java:system_java",
......
...@@ -37,7 +37,6 @@ chrome_java_sources = [ ...@@ -37,7 +37,6 @@ chrome_java_sources = [
"java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java", "java/src/org/chromium/chrome/browser/ChromeKeyboardVisibilityDelegate.java",
"java/src/org/chromium/chrome/browser/ChromeStrictMode.java", "java/src/org/chromium/chrome/browser/ChromeStrictMode.java",
"java/src/org/chromium/chrome/browser/ChromeStringConstants.java", "java/src/org/chromium/chrome/browser/ChromeStringConstants.java",
"java/src/org/chromium/chrome/browser/ChromeSwitches.java",
"java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java", "java/src/org/chromium/chrome/browser/ChromeTabbedActivity.java",
"java/src/org/chromium/chrome/browser/ChromeTabbedActivity2.java", "java/src/org/chromium/chrome/browser/ChromeTabbedActivity2.java",
"java/src/org/chromium/chrome/browser/ChromeVersionInfo.java", "java/src/org/chromium/chrome/browser/ChromeVersionInfo.java",
......
...@@ -8,14 +8,10 @@ package org.chromium.chrome.browser; ...@@ -8,14 +8,10 @@ package org.chromium.chrome.browser;
* Contains all of the command line switches that are specific to the chrome/ * Contains all of the command line switches that are specific to the chrome/
* portion of Chromium on Android. * portion of Chromium on Android.
*/ */
public abstract class ChromeSwitches { public abstract class ChromeSwitches {{
// Switches used from Java. Please continue switch style used Chrome where // Switches used from Java. Please continue switch style used Chrome where
// options-have-hyphens and are_not_split_with_underscores. // options-have-hyphens and are_not_split_with_underscores.
/** Mimic a low end device */
public static final String ENABLE_ACCESSIBILITY_TAB_SWITCHER =
"enable-accessibility-tab-switcher";
/** Whether fullscreen support is disabled (auto hiding controls, etc...). */ /** Whether fullscreen support is disabled (auto hiding controls, etc...). */
public static final String DISABLE_FULLSCREEN = "disable-fullscreen"; public static final String DISABLE_FULLSCREEN = "disable-fullscreen";
...@@ -68,29 +64,14 @@ public abstract class ChromeSwitches { ...@@ -68,29 +64,14 @@ public abstract class ChromeSwitches {
public static final String DISABLE_LOFI_SNACKBAR = "disable-lo-fi-snackbar"; public static final String DISABLE_LOFI_SNACKBAR = "disable-lo-fi-snackbar";
/** /**
* Forces the update state to be set to the given state if the value is {@link * Forces the update state to be set to the given state if the value is {{@link
* org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#NONE_SWITCH_VALUE}, {@link * org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#NONE_SWITCH_VALUE}}, {{@link
* org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#UPDATE_AVAILABLE_SWITCH_VALUE}, * org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#UPDATE_AVAILABLE_SWITCH_VALUE}},
* {@link * {{@link
* org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#UNSUPPORTED_OS_VERSION_SWITCH_VALUE}. * org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#UNSUPPORTED_OS_VERSION_SWITCH_VALUE}}.
*/ */
public static final String FORCE_UPDATE_MENU_UPDATE_TYPE = "force-update-menu-type"; public static final String FORCE_UPDATE_MENU_UPDATE_TYPE = "force-update-menu-type";
/**
* Forces the update menu badge to show. This requires the update type to be valid as well.
*
* @see #FORCE_UPDATE_MENU_UPDATE_TYPE
*/
public static final String FORCE_SHOW_UPDATE_MENU_BADGE = "force-show-update-menu-badge";
/**
* Sets the market URL for Chrome for use in testing. This requires setting {@link
* #FORCE_UPDATE_MENU_UPDATE_TYPE} to {@link
* org.chromium.chrome.browser.omaha.UpdateMenuItemHelper#UPDATE_AVAILABLE_SWITCH_VALUE}.
* @see #FORCE_UPDATE_MENU_UPDATE_TYPE
*/
public static final String MARKET_URL_FOR_TESTING = "market-url-for-testing";
/** /**
* Disable multiwindow tab merging for testing. * Disable multiwindow tab merging for testing.
*/ */
...@@ -121,18 +102,6 @@ public abstract class ChromeSwitches { ...@@ -121,18 +102,6 @@ public abstract class ChromeSwitches {
*/ */
public static final String GOOGLE_BASE_URL = "google-base-url"; public static final String GOOGLE_BASE_URL = "google-base-url";
/**
* Disable domain reliability
* Native switch - switches::kDisableDomainReliability
*/
public static final String DISABLE_DOMAIN_RELIABILITY = "disable-domain-reliability";
/**
* Specifies Android phone page loading progress bar animation.
* Native switch - switches::kProgressBarAnimation
*/
public static final String PROGRESS_BAR_ANIMATION = "progress-bar-animation";
/** /**
* Enables overscroll of the on screen keyboard. With this flag on, the OSK will only resize the * Enables overscroll of the on screen keyboard. With this flag on, the OSK will only resize the
* visual viewport. * visual viewport.
...@@ -229,6 +198,8 @@ public abstract class ChromeSwitches { ...@@ -229,6 +198,8 @@ public abstract class ChromeSwitches {
public static final String DISABLE_GOOGLE_PLAY_SERVICES_FOR_TESTING = public static final String DISABLE_GOOGLE_PLAY_SERVICES_FOR_TESTING =
"disable-google-play-services-for-testing"; "disable-google-play-services-for-testing";
{NATIVE_STRINGS}
// Prevent instantiation. // Prevent instantiation.
private ChromeSwitches() {} private ChromeSwitches() {{}}
} }}
...@@ -8,7 +8,7 @@ package org.chromium.content_public.common; ...@@ -8,7 +8,7 @@ package org.chromium.content_public.common;
* Contains all of the command line switches that are specific to the content/ * Contains all of the command line switches that are specific to the content/
* portion of Chromium on Android. * portion of Chromium on Android.
*/ */
public final class ContentSwitches { public final class ContentSwitches {{
// Tell Java to use the official command line, loaded from the // Tell Java to use the official command line, loaded from the
// official-command-line.xml files. WARNING this is not done // official-command-line.xml files. WARNING this is not done
// immediately on startup, so early running Java code will not see // immediately on startup, so early running Java code will not see
...@@ -27,9 +27,6 @@ public final class ContentSwitches { ...@@ -27,9 +27,6 @@ public final class ContentSwitches {
// Change the url of the JavaScript that gets injected when accessibility mode is enabled. // Change the url of the JavaScript that gets injected when accessibility mode is enabled.
public static final String ACCESSIBILITY_JAVASCRIPT_URL = "accessibility-js-url"; public static final String ACCESSIBILITY_JAVASCRIPT_URL = "accessibility-js-url";
// Sets the ISO country code that will be used for phone number detection.
public static final String NETWORK_COUNTRY_ISO = "network-country-iso";
// How much of the browser controls need to be shown before they will auto show. // How much of the browser controls need to be shown before they will auto show.
public static final String TOP_CONTROLS_SHOW_THRESHOLD = "top-controls-show-threshold"; public static final String TOP_CONTROLS_SHOW_THRESHOLD = "top-controls-show-threshold";
...@@ -39,16 +36,9 @@ public final class ContentSwitches { ...@@ -39,16 +36,9 @@ public final class ContentSwitches {
// Native switch - chrome_switches::kDisablePopupBlocking // Native switch - chrome_switches::kDisablePopupBlocking
public static final String DISABLE_POPUP_BLOCKING = "disable-popup-blocking"; public static final String DISABLE_POPUP_BLOCKING = "disable-popup-blocking";
// Native switch kDisableGestureRequirementForPresentation
public static final String DISABLE_GESTURE_REQUIREMENT_FOR_PRESENTATION =
"disable-gesture-requirement-for-presentation";
// Native switch kRendererProcessLimit // Native switch kRendererProcessLimit
public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit"; public static final String RENDER_PROCESS_LIMIT = "renderer-process-limit";
// Native switch kInProcessGPU
public static final String IN_PROCESS_GPU = "in-process-gpu";
// Native switch kProcessType // Native switch kProcessType
public static final String SWITCH_PROCESS_TYPE = "type"; public static final String SWITCH_PROCESS_TYPE = "type";
...@@ -74,6 +64,8 @@ public final class ContentSwitches { ...@@ -74,6 +64,8 @@ public final class ContentSwitches {
// Native switch value kNetworkSandbox // Native switch value kNetworkSandbox
public static final String NETWORK_SANDBOX_TYPE = "network"; public static final String NETWORK_SANDBOX_TYPE = "network";
{NATIVE_STRINGS}
// Prevent instantiation. // Prevent instantiation.
private ContentSwitches() {} private ContentSwitches() {{}}
} }}
...@@ -93,6 +93,7 @@ android_library("content_java") { ...@@ -93,6 +93,7 @@ android_library("content_java") {
":generate_sandboxed_service_srcjar", ":generate_sandboxed_service_srcjar",
":is_ready_to_pay_service_aidl", ":is_ready_to_pay_service_aidl",
":content_public_android_java_enums_srcjar", ":content_public_android_java_enums_srcjar",
":content_public_android_java_switches_srcjar",
"//content/browser/accessibility:content_browser_accessibility_java_enums_srcjar", "//content/browser/accessibility:content_browser_accessibility_java_enums_srcjar",
"//ui/touch_selection:ui_touch_selection_enums_srcjar", "//ui/touch_selection:ui_touch_selection_enums_srcjar",
"//ui/touch_selection:ui_touch_handle_orientation_srcjar", "//ui/touch_selection:ui_touch_handle_orientation_srcjar",
...@@ -284,7 +285,6 @@ android_library("content_java") { ...@@ -284,7 +285,6 @@ android_library("content_java") {
"java/src/org/chromium/content_public/browser/WebContentsObserver.java", "java/src/org/chromium/content_public/browser/WebContentsObserver.java",
"java/src/org/chromium/content_public/browser/WebContentsStatics.java", "java/src/org/chromium/content_public/browser/WebContentsStatics.java",
"java/src/org/chromium/content_public/common/ContentProcessInfo.java", "java/src/org/chromium/content_public/common/ContentProcessInfo.java",
"java/src/org/chromium/content_public/common/ContentSwitches.java",
"java/src/org/chromium/content_public/common/ContentUrlConstants.java", "java/src/org/chromium/content_public/common/ContentUrlConstants.java",
"java/src/org/chromium/content_public/common/Referrer.java", "java/src/org/chromium/content_public/common/Referrer.java",
"java/src/org/chromium/content_public/common/ResourceRequestBody.java", "java/src/org/chromium/content_public/common/ResourceRequestBody.java",
...@@ -368,6 +368,13 @@ java_cpp_enum("content_public_android_java_enums_srcjar") { ...@@ -368,6 +368,13 @@ java_cpp_enum("content_public_android_java_enums_srcjar") {
] ]
} }
java_cpp_strings("content_public_android_java_switches_srcjar") {
sources = [
"//content/public/common/content_switches.cc",
]
template = "//content/common/android/java_templates/ContentSwitches.java.tmpl"
}
generate_jar_jni("jar_jni") { generate_jar_jni("jar_jni") {
jni_package = "content" jni_package = "content"
classes = [ classes = [
......
# Accessing C++ Switches In Java
[TOC]
## Introduction
Accessing C++ switches in Java is implemented via a Python script which analyzes
the C++ switches file and spits out the corresponding Java class. The generated
class name will be based upon the switch file name, and the path must be
specified in a comment within the switch file itself.
## Usage
1. Add directives to your C++ switch file
```cpp
// GENERATED_JAVA_PACKAGE: org.chromium.chrome
// ...snip...
// Documentation for the following switch.
const char kSomeSwitch[] = "some-switch";
// ...snip...
```
2. Create a template file
```java
// Copyright {YEAR} 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 autogenerated by
// {SCRIPT_NAME}
// From
// {SOURCE_PATH}, and
// {TEMPLATE_PATH}
package my.java.package
// Be sure to escape any curly braces in your template by doubling as
// follows.
public abstract class MySwitches {{
{NATIVE_SWITCHES}
}}
```
3. Add a new build target
```gn
import("//build/config/android/rules.gni")
java_cpp_strings("foo_generated_switch") {
sources = [
"//base/android/native_foo_switches.cc",
]
template = "//base/android/java_templates/MySwitches.java.tmpl"
}
```
5. Add the new target to the desired android_library targets srcjar_deps:
```gn
android_library("base_java") {
srcjar_deps = [
":foo_generated_switches",
]
}
```
5. The generated file `org/chromium/chrome/NativeFooSwitches.java` would contain:
```java
package org.chromium.chrome;
public final class NativeFooSwitches {
// ...snip...
public static final String SOME_SWITCH = "some-switch";
// ...snip...
}
```
## Code
* [Generator
code](https://cs.chromium.org/chromium/src/build/android/gyp/java_cpp_strings.py?dr=C&sq=package:chromium)
and
[Tests](https://cs.chromium.org/chromium/src/build/android/gyp/java_cpp_strings_tests.py?dr=C&sq=package:chromium)
* [GN
template](https://cs.chromium.org/chromium/src/build/config/android/rules.gni?sq=package:chromium&dr=C)
...@@ -154,6 +154,13 @@ if (is_android) { ...@@ -154,6 +154,13 @@ if (is_android) {
] ]
} }
java_cpp_strings("java_switches") {
sources = [
"//media/base/media_switches.cc",
]
template = "//media/base/android/java_templates/MediaSwitches.java.tmpl"
}
android_resources("media_java_resources") { android_resources("media_java_resources") {
custom_package = "org.chromium.media" custom_package = "org.chromium.media"
resource_dirs = [ "java/res" ] resource_dirs = [ "java/res" ]
...@@ -167,6 +174,7 @@ if (is_android) { ...@@ -167,6 +174,7 @@ if (is_android) {
] ]
srcjar_deps = [ srcjar_deps = [
":java_enums", ":java_enums",
":java_switches",
"//media/base:java_enums", "//media/base:java_enums",
] ]
java_files = [ java_files = [
...@@ -187,7 +195,6 @@ if (is_android) { ...@@ -187,7 +195,6 @@ if (is_android) {
"java/src/org/chromium/media/MediaPlayerBridge.java", "java/src/org/chromium/media/MediaPlayerBridge.java",
"java/src/org/chromium/media/MediaPlayerListener.java", "java/src/org/chromium/media/MediaPlayerListener.java",
"java/src/org/chromium/media/MediaServerCrashListener.java", "java/src/org/chromium/media/MediaServerCrashListener.java",
"java/src/org/chromium/media/MediaSwitches.java",
] ]
} }
......
...@@ -7,7 +7,7 @@ package org.chromium.media; ...@@ -7,7 +7,7 @@ package org.chromium.media;
/** /**
* Contains command line switches that are specific to the media layer. * Contains command line switches that are specific to the media layer.
*/ */
public abstract class MediaSwitches { public abstract class MediaSwitches {{
// Set the autoplay policy to ignore user gesture requirements // Set the autoplay policy to ignore user gesture requirements
public static final String AUTOPLAY_NO_GESTURE_REQUIRED_POLICY = public static final String AUTOPLAY_NO_GESTURE_REQUIRED_POLICY =
"autoplay-policy=no-user-gesture-required"; "autoplay-policy=no-user-gesture-required";
...@@ -15,6 +15,8 @@ public abstract class MediaSwitches { ...@@ -15,6 +15,8 @@ public abstract class MediaSwitches {
// TODO(819383): Remove this and its usage. // TODO(819383): Remove this and its usage.
public static final String USE_MODERN_MEDIA_CONTROLS = "UseModernMediaControls"; public static final String USE_MODERN_MEDIA_CONTROLS = "UseModernMediaControls";
{NATIVE_STRINGS}
// Prevents instantiation. // Prevents instantiation.
private MediaSwitches() {} private MediaSwitches() {{}}
} }}
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