summaryrefslogtreecommitdiff
path: root/chromium/chrome/common
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2020-10-12 14:27:29 +0200
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2020-10-13 09:35:20 +0000
commitc30a6232df03e1efbd9f3b226777b07e087a1122 (patch)
treee992f45784689f373bcc38d1b79a239ebe17ee23 /chromium/chrome/common
parent7b5b123ac58f58ffde0f4f6e488bcd09aa4decd3 (diff)
downloadqtwebengine-chromium-85-based.tar.gz
BASELINE: Update Chromium to 85.0.4183.14085-based
Change-Id: Iaa42f4680837c57725b1344f108c0196741f6057 Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/chrome/common')
-rw-r--r--chromium/chrome/common/BUILD.gn18
-rw-r--r--chromium/chrome/common/DEPS1
-rw-r--r--chromium/chrome/common/apps/platform_apps/api/PRESUBMIT.py28
-rw-r--r--chromium/chrome/common/apps/platform_apps/api/generated_externs_list.txt3
-rw-r--r--chromium/chrome/common/caption.mojom9
-rw-r--r--chromium/chrome/common/chrome_features.cc150
-rw-r--r--chromium/chrome/common/chrome_features.h67
-rw-r--r--chromium/chrome/common/chrome_paths.cc7
-rw-r--r--chromium/chrome/common/chrome_paths.h2
-rw-r--r--chromium/chrome/common/chrome_render_frame.mojom3
-rw-r--r--chromium/chrome/common/chrome_switches.cc11
-rw-r--r--chromium/chrome/common/chrome_switches.h2
-rw-r--r--chromium/chrome/common/chrome_ui_features_prefs.cc17
-rw-r--r--chromium/chrome/common/chrome_ui_features_prefs.h17
-rw-r--r--chromium/chrome/common/cloud_print/cloud_print_helpers.cc1
-rw-r--r--chromium/chrome/common/common_message_generator.h9
-rw-r--r--chromium/chrome/common/component_flash_hint_file_linux.cc1
-rw-r--r--chromium/chrome/common/custom_handlers/protocol_handler.cc9
-rw-r--r--chromium/chrome/common/extensions/api/PRESUBMIT.py35
-rw-r--r--chromium/chrome/common/extensions/api/_api_features.json23
-rw-r--r--chromium/chrome/common/extensions/api/_manifest_features.json2
-rw-r--r--chromium/chrome/common/extensions/api/_permission_features.json101
-rw-r--r--chromium/chrome/common/extensions/api/accessibility_features.json6
-rw-r--r--chromium/chrome/common/extensions/api/accessibility_private.json25
-rw-r--r--chromium/chrome/common/extensions/api/api_sources.gni11
-rw-r--r--chromium/chrome/common/extensions/api/autofill_assistant_private.idl2
-rw-r--r--chromium/chrome/common/extensions/api/autofill_private.idl3
-rw-r--r--chromium/chrome/common/extensions/api/autotest_private.idl26
-rw-r--r--chromium/chrome/common/extensions/api/braille_display_private.idl2
-rw-r--r--chromium/chrome/common/extensions/api/cast_streaming_receiver_session.idl70
-rw-r--r--chromium/chrome/common/extensions/api/cast_streaming_rtp_stream.idl145
-rw-r--r--chromium/chrome/common/extensions/api/cast_streaming_session.idl39
-rw-r--r--chromium/chrome/common/extensions/api/cast_streaming_udp_transport.idl42
-rw-r--r--chromium/chrome/common/extensions/api/chrome_web_view_internal.json2
-rw-r--r--chromium/chrome/common/extensions/api/chromeos_info_private.json13
-rw-r--r--chromium/chrome/common/extensions/api/context_menus.json6
-rw-r--r--chromium/chrome/common/extensions/api/cookies.json4
-rw-r--r--chromium/chrome/common/extensions/api/developer_private.idl3
-rw-r--r--chromium/chrome/common/extensions/api/enterprise_networking_attributes.idl33
-rw-r--r--chromium/chrome/common/extensions/api/enterprise_reporting_private.idl10
-rw-r--r--chromium/chrome/common/extensions/api/extension_action/action_info_test_util.cc16
-rw-r--r--chromium/chrome/common/extensions/api/file_manager_private.idl27
-rw-r--r--chromium/chrome/common/extensions/api/generated_externs_list.txt24
-rw-r--r--chromium/chrome/common/extensions/api/input_ime.json223
-rw-r--r--chromium/chrome/common/extensions/api/input_method_private.json51
-rw-r--r--chromium/chrome/common/extensions/api/login.idl4
-rw-r--r--chromium/chrome/common/extensions/api/passwords_private.idl38
-rw-r--r--chromium/chrome/common/extensions/api/platform_keys.idl38
-rw-r--r--chromium/chrome/common/extensions/api/platform_keys_internal.idl11
-rw-r--r--chromium/chrome/common/extensions/api/printing_metrics.idl3
-rw-r--r--chromium/chrome/common/extensions/api/settings_private.idl11
-rw-r--r--chromium/chrome/common/extensions/api/tab_capture.idl4
-rw-r--r--chromium/chrome/common/extensions/api/tts.json2
-rw-r--r--chromium/chrome/common/extensions/api/webstore_private.json5
-rw-r--r--chromium/chrome/common/extensions/api/webview_tag.json4
-rw-r--r--chromium/chrome/common/extensions/extension_constants.cc11
-rw-r--r--chromium/chrome/common/extensions/extension_constants.h12
-rw-r--r--chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.cc14
-rw-r--r--chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.h2
-rw-r--r--chromium/chrome/common/extensions/permissions/chrome_api_permissions.cc3
-rw-r--r--chromium/chrome/common/extensions/permissions/chrome_permission_message_rules.cc9
-rw-r--r--chromium/chrome/common/extensions/permissions/permission_set_unittest.cc5
-rw-r--r--chromium/chrome/common/features.gni3
-rw-r--r--chromium/chrome/common/google_url_loader_throttle.cc26
-rw-r--r--chromium/chrome/common/google_url_loader_throttle.h4
-rw-r--r--chromium/chrome/common/google_url_loader_throttle_unittest.cc75
-rw-r--r--chromium/chrome/common/mac/app_shim.mojom4
-rw-r--r--chromium/chrome/common/media/cdm_host_file_path.cc2
-rw-r--r--chromium/chrome/common/media/component_widevine_cdm_hint_file_linux.cc2
-rw-r--r--chromium/chrome/common/media/component_widevine_cdm_hint_file_linux_unittest.cc1
-rw-r--r--chromium/chrome/common/media_router/discovery/media_sink_internal.cc1
-rw-r--r--chromium/chrome/common/media_router/discovery/media_sink_service_base.cc1
-rw-r--r--chromium/chrome/common/media_router/issue.h1
-rw-r--r--chromium/chrome/common/media_router/media_route.cc6
-rw-r--r--chromium/chrome/common/media_router/media_route.h11
-rw-r--r--chromium/chrome/common/media_router/media_route_unittest.cc4
-rw-r--r--chromium/chrome/common/media_router/media_source.cc73
-rw-r--r--chromium/chrome/common/media_router/media_source.h25
-rw-r--r--chromium/chrome/common/media_router/media_source_unittest.cc38
-rw-r--r--chromium/chrome/common/media_router/mojom/BUILD.gn6
-rw-r--r--chromium/chrome/common/media_router/mojom/logger.mojom53
-rw-r--r--chromium/chrome/common/media_router/mojom/media_router.mojom33
-rw-r--r--chromium/chrome/common/media_router/mojom/media_router_mojom_traits.cc2
-rw-r--r--chromium/chrome/common/media_router/mojom/media_router_mojom_traits.h13
-rw-r--r--chromium/chrome/common/media_router/providers/cast/cast_media_source.cc53
-rw-r--r--chromium/chrome/common/media_router/providers/cast/cast_media_source.h43
-rw-r--r--chromium/chrome/common/media_router/providers/cast/cast_media_source_unittest.cc13
-rw-r--r--chromium/chrome/common/media_router/route_request_result.h2
-rw-r--r--chromium/chrome/common/net/OWNERS3
-rw-r--r--chromium/chrome/common/net/net_error_page_support.mojom17
-rw-r--r--chromium/chrome/common/performance_manager/OWNERS6
-rw-r--r--chromium/chrome/common/performance_manager/mojom/BUILD.gn5
-rw-r--r--chromium/chrome/common/pref_names.cc98
-rw-r--r--chromium/chrome/common/pref_names.h24
-rw-r--r--chromium/chrome/common/prerender_canceler.mojom15
-rw-r--r--chromium/chrome/common/prerender_messages.h35
-rw-r--r--chromium/chrome/common/prerender_types.h25
-rw-r--r--chromium/chrome/common/prerender_url_loader_throttle.cc17
-rw-r--r--chromium/chrome/common/prerender_url_loader_throttle.h12
-rw-r--r--chromium/chrome/common/prerender_util.cc6
-rw-r--r--chromium/chrome/common/prerender_util.h5
-rw-r--r--chromium/chrome/common/privacy_budget/BUILD.gn50
-rw-r--r--chromium/chrome/common/privacy_budget/DEPS3
-rw-r--r--chromium/chrome/common/privacy_budget/OWNERS4
-rw-r--r--chromium/chrome/common/privacy_budget/README.md6
-rw-r--r--chromium/chrome/common/privacy_budget/container_ops.h83
-rw-r--r--chromium/chrome/common/privacy_budget/container_ops_unittest.cc166
-rw-r--r--chromium/chrome/common/privacy_budget/field_trial_param_conversions.cc48
-rw-r--r--chromium/chrome/common/privacy_budget/field_trial_param_conversions.h121
-rw-r--r--chromium/chrome/common/privacy_budget/field_trial_param_conversions_unittest.cc73
-rw-r--r--chromium/chrome/common/privacy_budget/privacy_budget_features.cc33
-rw-r--r--chromium/chrome/common/privacy_budget/privacy_budget_features.h114
-rw-r--r--chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.cc55
-rw-r--r--chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.h80
-rw-r--r--chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.cc90
-rw-r--r--chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.h94
-rw-r--r--chromium/chrome/common/profiler/stack_sampling_browsertest.cc7
-rw-r--r--chromium/chrome/common/profiler/stack_sampling_configuration.cc15
-rw-r--r--chromium/chrome/common/profiler/thread_profiler.cc93
-rw-r--r--chromium/chrome/common/profiler/thread_profiler.h1
-rw-r--r--chromium/chrome/common/qr_code_generator/qr_code_generator.cc397
-rw-r--r--chromium/chrome/common/qr_code_generator/qr_code_generator.h173
-rw-r--r--chromium/chrome/common/qr_code_generator/qr_code_generator_unittest.cc37
-rw-r--r--chromium/chrome/common/render_messages.h13
-rw-r--r--chromium/chrome/common/safe_browsing/mach_o_image_reader_mac.h1
-rw-r--r--chromium/chrome/common/safe_browsing/mach_o_image_reader_mac_unittest.cc1
-rw-r--r--chromium/chrome/common/search/ntp_logging_events.h5
-rw-r--r--chromium/chrome/common/secure_origin_allowlist.cc (renamed from chromium/chrome/common/secure_origin_whitelist.cc)6
-rw-r--r--chromium/chrome/common/secure_origin_allowlist.h (renamed from chromium/chrome/common/secure_origin_whitelist.h)14
-rw-r--r--chromium/chrome/common/service_process_util.cc2
-rw-r--r--chromium/chrome/common/service_process_util_posix.cc1
-rw-r--r--chromium/chrome/common/service_process_util_win.cc6
-rw-r--r--chromium/chrome/common/string_matching/BUILD.gn34
-rw-r--r--chromium/chrome/common/string_matching/OWNERS2
-rw-r--r--chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.cc331
-rw-r--r--chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.h100
-rw-r--r--chromium/chrome/common/string_matching/fuzzy_tokenized_string_match_unittest.cc296
-rw-r--r--chromium/chrome/common/string_matching/sequence_matcher.cc198
-rw-r--r--chromium/chrome/common/string_matching/sequence_matcher.h78
-rw-r--r--chromium/chrome/common/string_matching/sequence_matcher_unittest.cc137
-rw-r--r--chromium/chrome/common/string_matching/term_break_iterator.cc72
-rw-r--r--chromium/chrome/common/string_matching/term_break_iterator.h68
-rw-r--r--chromium/chrome/common/string_matching/term_break_iterator_unittest.cc87
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string.cc43
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string.h42
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_char_iterator.cc85
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_char_iterator.h76
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_char_iterator_unittest.cc145
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_fuzzer.cc17
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_match.cc248
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_match.h49
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_match_unittest.cc149
-rw-r--r--chromium/chrome/common/string_matching/tokenized_string_unittest.cc81
-rw-r--r--chromium/chrome/common/subresource_redirect_service.mojom18
-rw-r--r--chromium/chrome/common/themes/autogenerated_theme_util.cc2
-rw-r--r--chromium/chrome/common/themes/autogenerated_theme_util.h1
-rw-r--r--chromium/chrome/common/url_constants.cc13
-rw-r--r--chromium/chrome/common/url_constants.h12
-rw-r--r--chromium/chrome/common/web_application_info.cc70
-rw-r--r--chromium/chrome/common/web_application_info.h59
-rw-r--r--chromium/chrome/common/web_components_prefs.cc17
-rw-r--r--chromium/chrome/common/web_components_prefs.h17
-rw-r--r--chromium/chrome/common/webui_url_constants.cc23
-rw-r--r--chromium/chrome/common/webui_url_constants.h28
164 files changed, 3051 insertions, 3577 deletions
diff --git a/chromium/chrome/common/BUILD.gn b/chromium/chrome/common/BUILD.gn
index 57d7ce2fd3e..e6496ae6ef9 100644
--- a/chromium/chrome/common/BUILD.gn
+++ b/chromium/chrome/common/BUILD.gn
@@ -106,8 +106,6 @@ static_library("common") {
"chrome_descriptors.h",
"chrome_isolated_world_ids.h",
"chrome_result_codes.h",
- "chrome_ui_features_prefs.cc",
- "chrome_ui_features_prefs.h",
"common_message_generator.cc",
"common_message_generator.h",
"component_flash_hint_file_linux.cc",
@@ -140,8 +138,6 @@ static_library("common") {
"pdf_util.h",
"pref_names_util.cc",
"pref_names_util.h",
- "prerender_messages.h",
- "prerender_types.h",
"prerender_url_loader_throttle.cc",
"prerender_url_loader_throttle.h",
"prerender_util.cc",
@@ -152,8 +148,8 @@ static_library("common") {
"search/instant_types.cc",
"search/instant_types.h",
"search/ntp_logging_events.h",
- "secure_origin_whitelist.cc",
- "secure_origin_whitelist.h",
+ "secure_origin_allowlist.cc",
+ "secure_origin_allowlist.h",
"ssl_insecure_content.cc",
"ssl_insecure_content.h",
"url_constants.cc",
@@ -161,8 +157,6 @@ static_library("common") {
"web_application_info.cc",
"web_application_info.h",
"web_application_info_provider_param_traits.h",
- "web_components_prefs.cc",
- "web_components_prefs.h",
"webui_url_constants.cc",
"webui_url_constants.h",
]
@@ -184,11 +178,13 @@ static_library("common") {
"//base",
"//base:base_static",
"//base:i18n",
+ "//base/util/values:values_util",
"//chrome:resources",
"//chrome:strings",
"//chrome/app/theme:theme_resources",
"//chrome/common:constants",
"//chrome/common/net",
+ "//chrome/common/privacy_budget",
"//chrome/common/profiler",
"//chrome/common/qr_code_generator",
"//chrome/common/search:mojo_bindings",
@@ -267,6 +263,8 @@ static_library("common") {
"//components/google/core/common",
"//components/metrics:call_stack_profile_builder",
"//components/page_load_metrics/common:common",
+ "//components/prerender/common",
+ "//components/prerender/common:mojo_bindings",
]
if (enable_plugins) {
@@ -698,13 +696,14 @@ mojom("mojo_bindings") {
"media/webrtc_logging.mojom",
"metrics.mojom",
"navigation_corrector.mojom",
+ "net/net_error_page_support.mojom",
"net_benchmarking.mojom",
"network_diagnostics.mojom",
"network_easter_egg.mojom",
"open_search_description_document_handler.mojom",
"plugin.mojom",
- "prerender_canceler.mojom",
"renderer_configuration.mojom",
+ "subresource_redirect_service.mojom",
"sync_encryption_keys_extension.mojom",
]
@@ -727,6 +726,7 @@ mojom("mojo_bindings") {
if (enable_offline_pages) {
sources += [ "mhtml_page_notifier.mojom" ]
deps += [ "//third_party/blink/public/mojom:mojom_mhtml_load_result" ]
+ enabled_features = [ "enable_offline_pages" ]
}
public_deps = [
diff --git a/chromium/chrome/common/DEPS b/chromium/chrome/common/DEPS
index 7073404c5d5..2c35b3b010c 100644
--- a/chromium/chrome/common/DEPS
+++ b/chromium/chrome/common/DEPS
@@ -34,6 +34,7 @@ include_rules = [
"+components/password_manager/core/common",
"+components/policy/core/common",
"+components/prefs",
+ "+components/prerender",
"+components/printing/common",
"+components/safe_browsing/buildflags.h",
"+components/safe_browsing/core/proto/csd.pb.h",
diff --git a/chromium/chrome/common/apps/platform_apps/api/PRESUBMIT.py b/chromium/chrome/common/apps/platform_apps/api/PRESUBMIT.py
new file mode 100644
index 00000000000..28bc319a694
--- /dev/null
+++ b/chromium/chrome/common/apps/platform_apps/api/PRESUBMIT.py
@@ -0,0 +1,28 @@
+# Copyright 2020 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.
+
+"""Chromium presubmit script for src/chrome/common/apps/platform_apps.
+
+See https://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
+for more details on the presubmit API built into depot_tools.
+"""
+
+import sys
+
+
+def _CheckExterns(input_api, output_api):
+ original_sys_path = sys.path
+ join = input_api.os_path.join
+ src_root = input_api.change.RepositoryRoot()
+ try:
+ sys.path.append(join(src_root, 'extensions', 'common', 'api'))
+ from externs_checker import ExternsChecker
+ finally:
+ sys.path = original_sys_path
+
+ return ExternsChecker(input_api, output_api).RunChecks()
+
+
+def CheckChangeOnUpload(input_api, output_api):
+ return _CheckExterns(input_api, output_api)
diff --git a/chromium/chrome/common/apps/platform_apps/api/generated_externs_list.txt b/chromium/chrome/common/apps/platform_apps/api/generated_externs_list.txt
new file mode 100644
index 00000000000..9eca6fbfa1f
--- /dev/null
+++ b/chromium/chrome/common/apps/platform_apps/api/generated_externs_list.txt
@@ -0,0 +1,3 @@
+# All APIs that have their externs generated.
+# TODO(rdevlin.cronin): Add more!
+arc_apps_private.idl
diff --git a/chromium/chrome/common/caption.mojom b/chromium/chrome/common/caption.mojom
index 44a9a95d568..05ca09fe939 100644
--- a/chromium/chrome/common/caption.mojom
+++ b/chromium/chrome/common/caption.mojom
@@ -8,13 +8,18 @@ module chrome.mojom;
// the Live Caption feature.
interface CaptionHost {
// Called when the speech recognition client receives a transcription from the
- // speech service.
- OnTranscription(TranscriptionResult transcription_result);
+ // speech service. Returns whether the transcription result was received
+ // successfully. Transcriptions will halt if this returns false.
+ OnTranscription(TranscriptionResult transcription_result) => (bool success);
};
// A transcription result created by the speech recognition client in the
// renderer and passed to the browser.
struct TranscriptionResult {
string transcription;
+
+ // A flag indicating whether the result is final. If true, the result is
+ // locked in and the next result returned will not overlap with the previous
+ // final result.
bool is_final;
};
diff --git a/chromium/chrome/common/chrome_features.cc b/chromium/chrome/common/chrome_features.cc
index c70c0e041f4..06763a9d46c 100644
--- a/chromium/chrome/common/chrome_features.cc
+++ b/chromium/chrome/common/chrome_features.cc
@@ -49,13 +49,15 @@ const base::Feature kShow10_9ObsoleteInfobar{"Show109ObsoleteInfobar",
#endif // defined(OS_MACOSX)
#if !defined(OS_ANDROID)
-// App Service related flags. See chrome/services/app_service/README.md.
+// App Service related flags. See components/services/app_service/README.md.
const base::Feature kAppServiceContextMenu{"AppServiceContextMenu",
base::FEATURE_ENABLED_BY_DEFAULT};
const base::Feature kAppServiceInstanceRegistry{
"AppServiceInstanceRegistry", base::FEATURE_ENABLED_BY_DEFAULT};
-const base::Feature kAppServiceIntentHandling{
- "AppServiceIntentHandling", base::FEATURE_DISABLED_BY_DEFAULT};
+const base::Feature kAppServiceIntentHandling{"AppServiceIntentHandling",
+ base::FEATURE_ENABLED_BY_DEFAULT};
+const base::Feature kAppServiceAdaptiveIcon{"AppServiceAdaptiveIcon",
+ base::FEATURE_DISABLED_BY_DEFAULT};
#endif // !defined(OS_ANDROID)
// Enables the built-in DNS resolver.
@@ -113,6 +115,12 @@ const base::Feature kCertDualVerificationTrialFeature{
const base::Feature kChangePictureVideoMode{"ChangePictureVideoMode",
base::FEATURE_ENABLED_BY_DEFAULT};
+// Dispatches a dummy fetch event to a service worker to check the offline
+// capability of the PWA site before promoting installation. See
+// https://crbug.com/965802 for more details.
+const base::Feature kCheckOfflineCapability{"CheckOfflineCapability",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
#if defined(OS_CHROMEOS)
// Enables passing additional user authentication in requests to DMServer
// (policy fetch, status report upload).
@@ -129,6 +137,9 @@ const base::Feature kClearOldBrowsingData{"ClearOldBrowsingData",
const base::Feature kClickToOpenPDFPlaceholder{
"ClickToOpenPDFPlaceholder", base::FEATURE_ENABLED_BY_DEFAULT};
+const base::Feature kClientStorageAccessContextAuditing{
+ "ClientStorageAccessContextAuditing", base::FEATURE_DISABLED_BY_DEFAULT};
+
#if defined(OS_MACOSX)
const base::Feature kImmersiveFullscreen{"ImmersiveFullscreen",
base::FEATURE_DISABLED_BY_DEFAULT};
@@ -164,7 +175,7 @@ const base::Feature kCrostiniAnsibleSoftwareManagement{
// Enables custom UI for forcibly closing unresponsive windows.
const base::Feature kCrostiniForceClose{"CrostiniForceClose",
- base::FEATURE_DISABLED_BY_DEFAULT};
+ base::FEATURE_ENABLED_BY_DEFAULT};
// Enables support for sideloading android apps into Arc via crostini.
const base::Feature kCrostiniArcSideload{"CrostiniArcSideload",
@@ -181,6 +192,12 @@ const base::Feature kCryptohomeDistributedModel{
const base::Feature kCryptohomeUserDataAuth{"CryptohomeUserDataAuth",
base::FEATURE_DISABLED_BY_DEFAULT};
+// Kill switch for cryptohome UserDataAuth interface. UserDataAuth is a new
+// dbus interface that is fully protobuf and uses libbrillo for dbus instead
+// instead of the deprecated glib-dbus.
+const base::Feature kCryptohomeUserDataAuthKillswitch{
+ "CryptohomeUserDataAuthKillswitch", base::FEATURE_DISABLED_BY_DEFAULT};
+
// Enable support for "Plugin VMs" on Chrome OS.
const base::Feature kPluginVm{"PluginVm", base::FEATURE_DISABLED_BY_DEFAULT};
@@ -198,10 +215,6 @@ const base::Feature kTerminalSystemApp{"TerminalSystemApp",
const base::Feature kTerminalSystemAppLegacySettings{
"TerminalSystemAppLegacySettings", base::FEATURE_DISABLED_BY_DEFAULT};
-// Enable splits in the Terminal System App.
-const base::Feature kTerminalSystemAppSplits{"TerminalSystemAppSplits",
- base::FEATURE_DISABLED_BY_DEFAULT};
-
// Enable uploading of a zip archive of system logs instead of individual files.
const base::Feature kUploadZippedSystemLogs{"UploadZippedSystemLogs",
base::FEATURE_ENABLED_BY_DEFAULT};
@@ -219,7 +232,7 @@ const base::Feature kDesktopCaptureTabSharingInfobar{
// Enables or disables new Desktop PWAs implementation that does not use
// extensions.
const base::Feature kDesktopPWAsWithoutExtensions{
- "DesktopPWAsWithoutExtensions", base::FEATURE_DISABLED_BY_DEFAULT};
+ "DesktopPWAsWithoutExtensions", base::FEATURE_ENABLED_BY_DEFAULT};
// When installing default installed PWAs, we wait for service workers
// to cache resources.
@@ -245,24 +258,7 @@ const base::Feature kDesktopPWAsTabStripLinkCapturing{
// Enables Desktop PWA installs to have a menu of shortcuts associated with
// the app icon in the taskbar on Windows, or the dock on macOS or Linux.
const base::Feature kDesktopPWAsAppIconShortcutsMenu{
- "DesktopPWAsAppIconShortcutsMenu", base::FEATURE_DISABLED_BY_DEFAULT};
-
-// Enables or disables use of new Desktop PWAs browser controller (that uses the
-// universal web_app::AppRegistrar) by extensions-based bookmark apps. Note that
-// the new Desktop PWAs implementation (not based on extensions) always uses the
-// new browser controller.
-// TODO(crbug.com/877898): Enable and delete this feature flag before
-// kDesktopPWAsWithoutExtensions launch.
-const base::Feature kDesktopPWAsUnifiedUiController{
- "DesktopPWAsUnifiedUiController", base::FEATURE_ENABLED_BY_DEFAULT};
-
-// Enables or disables use of new Desktop PWAs launch manager by
-// extensions-based bookmark apps. (Note that Bookmark apps not based
-// on extensions unconditionally use the new launch manager.)
-// TODO(crbug.com/877898): Enable and delete this feature flag before
-// kDesktopPWAsWithoutExtensions launch.
-const base::Feature kDesktopPWAsUnifiedLaunch{"DesktopPWAsUnifiedLaunch",
- base::FEATURE_ENABLED_BY_DEFAULT};
+ "DesktopPWAsAppIconShortcutsMenu", base::FEATURE_ENABLED_BY_DEFAULT};
// Enables or disables usage of shared LevelDB instance (ModelTypeStoreService).
// If this flag is disabled, the new Web Apps system uses its own isolated
@@ -279,6 +275,10 @@ const base::Feature kDefaultWebAppInstallation{
"DefaultWebAppInstallation", base::FEATURE_ENABLED_BY_DEFAULT};
#endif
+// Enables or disables Desktop PWAs to be auto-started on OS login.
+const base::Feature kDesktopPWAsRunOnOsLogin{"DesktopPWAsRunOnOsLogin",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
// Enable DNS over HTTPS (DoH).
const base::Feature kDnsOverHttps{"DnsOverHttps",
base::FEATURE_DISABLED_BY_DEFAULT};
@@ -409,11 +409,10 @@ const base::Feature kHideCorsLegacyModeEnabledPolicySupport{
const base::Feature kHideCorsMitigationListPolicySupport{
"HideCorsMitigationListPolicySupport", base::FEATURE_ENABLED_BY_DEFAULT};
-// Enables navigation suggestions UI for lookalike URLs (e.g. internationalized
-// domain names that are visually similar to popular domains or to domains with
-// engagement score, such as googlé.com).
-const base::Feature kLookalikeUrlNavigationSuggestionsUI{
- "LookalikeUrlNavigationSuggestionsUI", base::FEATURE_ENABLED_BY_DEFAULT};
+// Enables LiteVideos, a data-saving optimization that throttles media requests
+// to reduce the bitrate of adaptive media streams. Only for Lite mode users
+// (formerly DataSaver).
+const base::Feature kLiteVideo{"LiteVideo", base::FEATURE_DISABLED_BY_DEFAULT};
#if defined(OS_WIN)
// A feature that controls whether Chrome warns about incompatible applications.
@@ -443,11 +442,19 @@ const base::Feature kInstallableAmbientBadgeInfoBar{
#endif
#if !defined(OS_ANDROID)
+// Support sharing in Chrome OS intent handling.
+const base::Feature kIntentHandlingSharing{"IntentHandlingSharing",
+ base::FEATURE_DISABLED_BY_DEFAULT};
// Allow user to have preference for PWA in the intent picker.
const base::Feature kIntentPickerPWAPersistence{
"IntentPickerPWAPersistence", base::FEATURE_DISABLED_BY_DEFAULT};
#endif // !defined(OS_ANDROID)
+// If enabled, CloudPolicyInvalidator and RemoteCommandInvalidator instances
+// will have unique owner name.
+const base::Feature kInvalidatorUniqueOwnerName{
+ "InvalidatorUniqueOwnerName", base::FEATURE_DISABLED_BY_DEFAULT};
+
#if defined(OS_CHROMEOS)
const base::Feature kKernelnextVMs{"KernelnextVMs",
base::FEATURE_DISABLED_BY_DEFAULT};
@@ -481,6 +488,13 @@ const base::Feature kMacSystemScreenCapturePermissionCheck{
"MacSystemScreenCapturePermissionCheck", base::FEATURE_ENABLED_BY_DEFAULT};
#endif
+#if defined(OS_CHROMEOS)
+// Whether to show the Metered toggle in Settings, allowing users to toggle
+// whether to treat a WiFi or Cellular network as 'metered'.
+const base::Feature kMeteredShowToggle{"MeteredShowToggle",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+#endif
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
// Sets whether dismissing the new-tab-page override bubble counts as
// acknowledgement.
@@ -500,12 +514,6 @@ const base::Feature kOnConnectNative{"OnConnectNative",
base::FEATURE_DISABLED_BY_DEFAULT};
#endif
-// Enables the new native file system API permission model. When enabled
-// permissions are no longer scoped to tabs.
-const base::Feature kNativeFileSystemOriginScopedPermissions{
- "NativeFileSystemOriginScopedPermissions",
- base::FEATURE_ENABLED_BY_DEFAULT};
-
// Enables the use of native notification centers instead of using the Message
// Center for displaying the toasts. The feature is hardcoded to enabled for
// Chrome OS.
@@ -539,12 +547,6 @@ const base::Feature kOomIntervention{"OomIntervention",
base::FEATURE_ENABLED_BY_DEFAULT};
#endif
-// Adds the base language code to the Language-Accept headers if at least one
-// corresponding language+region code is present in the user preferences.
-// For example: "en-US, fr-FR" --> "en-US, en, fr-FR, fr".
-const base::Feature kUseNewAcceptLanguageHeader{
- "UseNewAcceptLanguageHeader", base::FEATURE_ENABLED_BY_DEFAULT};
-
#if defined(OS_CHROMEOS)
// Enables usage of Parent Access Code to authorize certain actions on child
// user device.
@@ -568,18 +570,28 @@ const base::Feature kPredictivePrefetchingAllowedOnAllConnectionTypes{
// Allows Chrome to do preconnect when prerender fails.
const base::Feature kPrerenderFallbackToPreconnect{
- "PrerenderFallbackToPreconnect", base::FEATURE_DISABLED_BY_DEFAULT};
+ "PrerenderFallbackToPreconnect", base::FEATURE_ENABLED_BY_DEFAULT};
+
+#if defined(OS_ANDROID)
+const base::Feature kPrivacyElevatedAndroid{"PrivacyElevatedAndroid",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+#endif
// Whether to display redesign of the chrome privacy settings page
// to the user.
const base::Feature kPrivacySettingsRedesign{"PrivacySettingsRedesign",
- base::FEATURE_DISABLED_BY_DEFAULT};
+ base::FEATURE_ENABLED_BY_DEFAULT};
#if defined(OS_ANDROID)
const base::Feature kSafetyCheckAndroid{"SafetyCheckAndroid",
base::FEATURE_DISABLED_BY_DEFAULT};
#endif
+#if defined(OS_WIN)
+const base::Feature kSafetyCheckChromeCleanerChild{
+ "SafetyCheckChromeCleanerChild", base::FEATURE_DISABLED_BY_DEFAULT};
+#endif
+
#if BUILDFLAG(ENABLE_PLUGINS)
// Show Flash deprecation warning to users who have manually enabled Flash.
// https://crbug.com/918428
@@ -606,6 +618,11 @@ const base::Feature kRemoveSupervisedUsersOnStartup{
const base::Feature kSecurityKeyAttestationPrompt{
"SecurityKeyAttestationPrompt", base::FEATURE_ENABLED_BY_DEFAULT};
+#if defined(OS_CHROMEOS)
+const base::Feature kSharesheet{"Sharesheet",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+#endif
+
#if defined(OS_ANDROID)
const base::Feature kShowTrustedPublisherURL{"ShowTrustedPublisherURL",
base::FEATURE_ENABLED_BY_DEFAULT};
@@ -627,37 +644,6 @@ const base::Feature kSitePerProcess {
#endif
};
-// Controls a mode for dynamically process-isolating sites where the user has
-// entered a password. This is intended to be used primarily when full site
-// isolation is turned off. To check whether this mode is enabled, use
-// SiteIsolationPolicy::IsIsolationForPasswordSitesEnabled() rather than
-// checking the feature directly, since that decision is influenced by other
-// factors as well.
-const base::Feature kSiteIsolationForPasswordSites {
- "site-isolation-for-password-sites",
-// Enabled by default on Android; see https://crbug.com/849815. Note that this
-// should not affect Android Webview, which does not include this code.
-#if defined(OS_ANDROID)
- base::FEATURE_ENABLED_BY_DEFAULT
-#else
- base::FEATURE_DISABLED_BY_DEFAULT
-#endif
-};
-
-// kSitePerProcessOnlyForHighMemoryClients is checked before kSitePerProcess,
-// and (if enabled) can restrict if kSitePerProcess feature is checked at all -
-// no check will be made on devices with low memory (these devices will have no
-// Site Isolation via kSitePerProcess trials and won't activate either the
-// control or the experiment group). The threshold for what is considered a
-// "low memory" device is set (in MB) via a field trial param with the name
-// defined below ("site-per-process-low-memory-cutoff-mb") and compared against
-// base::SysInfo::AmountOfPhysicalMemoryMB().
-const base::Feature kSitePerProcessOnlyForHighMemoryClients{
- "site-per-process-only-for-high-memory-clients",
- base::FEATURE_DISABLED_BY_DEFAULT};
-const char kSitePerProcessOnlyForHighMemoryClientsParamName[] =
- "site-per-process-low-memory-cutoff-mb";
-
#if defined(OS_CHROMEOS)
// Enables or disables automatic setup of USB printers.
const base::Feature kStreamlinedUsbPrinterSetup{
@@ -706,6 +692,12 @@ const base::Feature kHeavyAdInterventionWarning{
const base::Feature kHeavyAdPrivacyMitigations{
"HeavyAdPrivacyMitigations", base::FEATURE_ENABLED_BY_DEFAULT};
+// Enables or disables the FlocIdComputed event logging, which happens when a
+// floc id is first computed for a browsing session or is refreshed due to a
+// long period of time has passed since the last computation.
+const base::Feature kFlocIdComputedEventLogging{
+ "FlocIdComputedEventLogging", base::FEATURE_DISABLED_BY_DEFAULT};
+
#if defined(OS_CHROMEOS)
// Enables or disables logging for adaptive screen brightness on Chrome OS.
const base::Feature kAdaptiveScreenBrightnessLogging{
@@ -779,6 +771,10 @@ const base::Feature kSchedulerConfiguration{"SchedulerConfiguration",
#endif // defined(OS_CHROMEOS)
+// Enables the teamfood flags.
+const base::Feature kTeamfoodFlags{"TeamfoodFlags",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
#if !defined(OS_ANDROID)
// Allow capturing of WebRTC event logs, and uploading of those logs to Crash.
// Please note that a Chrome policy must also be set, for this to have effect.
diff --git a/chromium/chrome/common/chrome_features.h b/chromium/chrome/common/chrome_features.h
index 4b652fc862f..7e84fbd0e11 100644
--- a/chromium/chrome/common/chrome_features.h
+++ b/chromium/chrome/common/chrome_features.h
@@ -57,6 +57,8 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kAppServiceInstanceRegistry;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kAppServiceIntentHandling;
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kAppServiceAdaptiveIcon;
#endif // !defined(OS_ANDROID)
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kAsyncDns;
@@ -74,6 +76,9 @@ extern const base::Feature kCertDualVerificationTrialFeature;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kChangePictureVideoMode;
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kCheckOfflineCapability;
+
#if defined(OS_CHROMEOS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kDMServerOAuthForChildUser;
@@ -87,6 +92,9 @@ extern const base::Feature kClearOldBrowsingData;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kClickToOpenPDFPlaceholder;
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kClientStorageAccessContextAuditing;
+
#if defined(OS_MACOSX)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kImmersiveFullscreen;
@@ -112,14 +120,14 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kCryptohomeDistributedModel;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kCryptohomeUserDataAuth;
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kCryptohomeUserDataAuthKillswitch;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kPluginVm;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kPrintServerUi;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kTerminalSystemApp;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kTerminalSystemAppLegacySettings;
COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kTerminalSystemAppSplits;
-COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kUploadZippedSystemLogs;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kWilcoDtc;
#endif
@@ -146,12 +154,6 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kDesktopPWAsAppIconShortcutsMenu;
COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kDesktopPWAsUnifiedUiController;
-
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kDesktopPWAsUnifiedLaunch;
-
-COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kDesktopPWAsSharedStoreService;
#if !defined(OS_ANDROID)
@@ -160,6 +162,9 @@ extern const base::Feature kDefaultWebAppInstallation;
#endif
COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kDesktopPWAsRunOnOsLogin;
+
+COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kDnsOverHttps;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::FeatureParam<bool> kDnsOverHttpsFallbackParam;
@@ -265,16 +270,21 @@ extern const base::Feature kInstallableAmbientBadgeInfoBar;
#if !defined(OS_ANDROID)
COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kIntentHandlingSharing;
+COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kIntentPickerPWAPersistence;
#endif // !defined(OS_ANDROID)
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kInvalidatorUniqueOwnerName;
+
#if defined(OS_CHROMEOS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kKernelnextVMs;
#endif
COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kLookalikeUrlNavigationSuggestionsUI;
+extern const base::Feature kLiteVideo;
#if defined(OS_MACOSX)
COMPONENT_EXPORT(CHROME_FEATURES)
@@ -294,6 +304,11 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kMacSystemScreenCapturePermissionCheck;
#endif
+#if defined(OS_CHROMEOS)
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kMeteredShowToggle;
+#endif
+
#if BUILDFLAG(ENABLE_EXTENSIONS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kAcknowledgeNtpOverrideOnDeactivate;
@@ -306,9 +321,6 @@ extern const base::Feature kMixedContentSiteSetting;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kOnConnectNative;
#endif
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kNativeFileSystemOriginScopedPermissions;
-
#if BUILDFLAG(ENABLE_NATIVE_NOTIFICATIONS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kNativeNotifications;
@@ -329,9 +341,6 @@ COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kNtlmV2Enabled;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kOomIntervention;
#endif
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kUseNewAcceptLanguageHeader;
-
#if defined(OS_CHROMEOS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kParentAccessCode;
@@ -349,6 +358,11 @@ extern const base::Feature kPredictivePrefetchingAllowedOnAllConnectionTypes;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kPrerenderFallbackToPreconnect;
+#if defined(OS_ANDROID)
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kPrivacyElevatedAndroid;
+#endif
+
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kPrivacySettingsRedesign;
@@ -357,6 +371,11 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kSafetyCheckAndroid;
#endif
+#if defined(OS_WIN)
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kSafetyCheckChromeCleanerChild;
+#endif
+
#if BUILDFLAG(ENABLE_PLUGINS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kFlashDeprecationWarning;
@@ -376,6 +395,11 @@ extern const base::Feature kRemoveSupervisedUsersOnStartup;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kSecurityKeyAttestationPrompt;
+#if defined(OS_CHROMEOS)
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kSharesheet;
+#endif
+
#if defined(OS_ANDROID)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kShowTrustedPublisherURL;
@@ -383,14 +407,6 @@ extern const base::Feature kShowTrustedPublisherURL;
COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kSitePerProcess;
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kSiteIsolationForPasswordSites;
-
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const base::Feature kSitePerProcessOnlyForHighMemoryClients;
-COMPONENT_EXPORT(CHROME_FEATURES)
-extern const char kSitePerProcessOnlyForHighMemoryClientsParamName[];
-
#if defined(OS_CHROMEOS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kStreamlinedUsbPrinterSetup;
@@ -433,6 +449,9 @@ extern const base::Feature kHeavyAdInterventionWarning;
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kHeavyAdPrivacyMitigations;
+COMPONENT_EXPORT(CHROME_FEATURES)
+extern const base::Feature kFlocIdComputedEventLogging;
+
#if defined(OS_CHROMEOS)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kAdaptiveScreenBrightnessLogging;
@@ -479,6 +498,8 @@ COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kSchedulerConfiguration;
#endif // defined(OS_CHROMEOS)
+COMPONENT_EXPORT(CHROME_FEATURES) extern const base::Feature kTeamfoodFlags;
+
#if !defined(OS_ANDROID)
COMPONENT_EXPORT(CHROME_FEATURES)
extern const base::Feature kWebRtcRemoteEventLog;
diff --git a/chromium/chrome/common/chrome_paths.cc b/chromium/chrome/common/chrome_paths.cc
index 1ca92ba2c97..69d5427395a 100644
--- a/chromium/chrome/common/chrome_paths.cc
+++ b/chromium/chrome/common/chrome_paths.cc
@@ -8,6 +8,7 @@
#include "base/logging.h"
#include "base/native_library.h"
#include "base/no_destructor.h"
+#include "base/notreached.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/system/sys_info.h"
@@ -273,12 +274,6 @@ bool PathProvider(int key, base::FilePath* result) {
cur = cur.Append(FILE_PATH_LITERAL("resources"));
#endif
break;
- case chrome::DIR_INSPECTOR_DEBUG:
- if (!base::PathService::Get(chrome::DIR_RESOURCES, &cur))
- return false;
- cur = cur.Append(FILE_PATH_LITERAL("inspector"))
- .Append(FILE_PATH_LITERAL("debug"));
- break;
case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_POSIX)
// We can't write into the EXE dir on Linux, so keep dictionaries
diff --git a/chromium/chrome/common/chrome_paths.h b/chromium/chrome/common/chrome_paths.h
index 3f73d868b54..f23bfc49b9b 100644
--- a/chromium/chrome/common/chrome_paths.h
+++ b/chromium/chrome/common/chrome_paths.h
@@ -32,8 +32,6 @@ enum {
#endif
DIR_RESOURCES, // Directory containing separate file resources
// used by Chrome at runtime.
- DIR_INSPECTOR_DEBUG, // Directory where non-bundled and non-minified
- // web inspector is located.
DIR_APP_DICTIONARIES, // Directory where the global dictionaries are.
DIR_USER_DOCUMENTS, // Directory for a user's "My Documents".
DIR_USER_MUSIC, // Directory for a user's music.
diff --git a/chromium/chrome/common/chrome_render_frame.mojom b/chromium/chrome/common/chrome_render_frame.mojom
index dc08a008216..b4157885b16 100644
--- a/chromium/chrome/common/chrome_render_frame.mojom
+++ b/chromium/chrome/common/chrome_render_frame.mojom
@@ -49,9 +49,6 @@ interface ChromeRenderFrame {
// before onload events are fired.
ExecuteWebUIJavaScript(mojo_base.mojom.String16 javascript);
- // Sent when the profile changes the kSafeBrowsingEnabled preference.
- SetClientSidePhishingDetection(bool enable_phishing_detection);
-
// Requests the web application info from the renderer.
GetWebApplicationInfo() => (WebApplicationInfo web_application_info);
diff --git a/chromium/chrome/common/chrome_switches.cc b/chromium/chrome/common/chrome_switches.cc
index f0933503ae1..11beb0e4400 100644
--- a/chromium/chrome/common/chrome_switches.cc
+++ b/chromium/chrome/common/chrome_switches.cc
@@ -55,6 +55,12 @@ const char kApp[] = "app";
// according to its configuration.
const char kAppId[] = "app-id";
+// Overrides the launch url of an app with the specified url. This is used
+// along with kAppId to launch a given app with the url corresponding to an item
+// in the app's shortcuts menu.
+const char kAppLaunchUrlForShortcutsMenuItem[] =
+ "app-launch-url-for-shortcuts-menu-item";
+
// Value of GAIA auth code for --force-app-mode.
const char kAppModeAuthCode[] = "app-mode-auth-code";
@@ -231,11 +237,6 @@ const char kDisablePromptOnRepost[] = "disable-prompt-on-repost";
const char kDisableSearchGeolocationDisclosure[] =
"disable-search-geolocation-disclosure";
-// Disables prompting the user for consent before fulfilling WebXR's
-// requestSession(). Use only when absolutely necessary, such as for perf tests.
-const char kDisableXrDeviceConsentPromptForTesting[] =
- "disable-xr-device-consent-prompt-for-testing";
-
// Some tests seem to require the application to close when the last
// browser window is closed. Thus, we need a switch to force this behavior
// for ChromeOS Aura, disable "zero window mode".
diff --git a/chromium/chrome/common/chrome_switches.h b/chromium/chrome/common/chrome_switches.h
index c014345f4d8..2199d95ac01 100644
--- a/chromium/chrome/common/chrome_switches.h
+++ b/chromium/chrome/common/chrome_switches.h
@@ -37,6 +37,7 @@ extern const char kAllowRunningInsecureContent[];
extern const char kAllowSilentPush[];
extern const char kApp[];
extern const char kAppId[];
+extern const char kAppLaunchUrlForShortcutsMenuItem[];
extern const char kAppModeAuthCode[];
extern const char kAppModeOAuth2Token[];
extern const char kAppsGalleryDownloadURL[];
@@ -78,7 +79,6 @@ extern const char kDisableExtensionsFileAccessCheck[];
extern const char kDisablePrintPreview[];
extern const char kDisablePromptOnRepost[];
extern const char kDisableSearchGeolocationDisclosure[];
-extern const char kDisableXrDeviceConsentPromptForTesting[];
extern const char kDisableZeroBrowsersOpenForTests[];
extern const char kDiskCacheDir[];
extern const char kDiskCacheSize[];
diff --git a/chromium/chrome/common/chrome_ui_features_prefs.cc b/chromium/chrome/common/chrome_ui_features_prefs.cc
deleted file mode 100644
index 7e06f82f0f2..00000000000
--- a/chromium/chrome/common/chrome_ui_features_prefs.cc
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.
-
-#include "chrome/common/chrome_ui_features_prefs.h"
-
-#include "chrome/common/pref_names.h"
-#include "components/prefs/pref_registry_simple.h"
-
-namespace chrome_ui_features_prefs {
-
-void RegisterProfilePrefs(PrefRegistrySimple* registry) {
- registry->RegisterBooleanPref(prefs::kUseLegacyFormControls,
- /*default_value=*/false);
-}
-
-} // namespace chrome_ui_features_prefs
diff --git a/chromium/chrome/common/chrome_ui_features_prefs.h b/chromium/chrome/common/chrome_ui_features_prefs.h
deleted file mode 100644
index 9f18b97820d..00000000000
--- a/chromium/chrome/common/chrome_ui_features_prefs.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_CHROME_UI_FEATURES_PREFS_H_
-#define CHROME_COMMON_CHROME_UI_FEATURES_PREFS_H_
-
-class PrefRegistrySimple;
-
-namespace chrome_ui_features_prefs {
-
-// Register preferences for Chrome UI Features.
-void RegisterProfilePrefs(PrefRegistrySimple* registry);
-
-} // namespace chrome_ui_features_prefs
-
-#endif // CHROME_COMMON_CHROME_UI_FEATURES_PREFS_H_
diff --git a/chromium/chrome/common/cloud_print/cloud_print_helpers.cc b/chromium/chrome/common/cloud_print/cloud_print_helpers.cc
index f6a4aa0bc4f..5a86eb16bb5 100644
--- a/chromium/chrome/common/cloud_print/cloud_print_helpers.cc
+++ b/chromium/chrome/common/cloud_print/cloud_print_helpers.cc
@@ -13,6 +13,7 @@
#include "base/hash/md5.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
+#include "base/notreached.h"
#include "base/strings/stringprintf.h"
#include "base/system/sys_info.h"
#include "base/values.h"
diff --git a/chromium/chrome/common/common_message_generator.h b/chromium/chrome/common/common_message_generator.h
index 45aee861e09..8e1f8513c25 100644
--- a/chromium/chrome/common/common_message_generator.h
+++ b/chromium/chrome/common/common_message_generator.h
@@ -6,10 +6,11 @@
#include "chrome/common/search/instant_mojom_traits.h"
#include "services/network/public/cpp/p2p_param_traits.h"
-#undef CHROME_COMMON_PRERENDER_MESSAGES_H_
-#include "chrome/common/prerender_messages.h"
-#ifndef CHROME_COMMON_PRERENDER_MESSAGES_H_
-#error "Failed to include header chrome/common/prerender_messages.h"
+#undef COMPONENTS_PRERENDER_COMMON_PRERENDER_MESSAGES_H_
+#include "components/prerender/common/prerender_messages.h"
+#ifndef COMPONENTS_PRERENDER_COMMON_PRERENDER_MESSAGES_H_
+#error \
+ "Failed to include header components/prerender/common/prerender_messages.h"
#endif
#undef CHROME_COMMON_RENDER_MESSAGES_H_
#include "chrome/common/render_messages.h"
diff --git a/chromium/chrome/common/component_flash_hint_file_linux.cc b/chromium/chrome/common/component_flash_hint_file_linux.cc
index 8e90d1f7a98..f986d3700b2 100644
--- a/chromium/chrome/common/component_flash_hint_file_linux.cc
+++ b/chromium/chrome/common/component_flash_hint_file_linux.cc
@@ -18,6 +18,7 @@
#include "base/files/memory_mapped_file.h"
#include "base/files/scoped_file.h"
#include "base/json/json_string_value_serializer.h"
+#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/stl_util.h"
diff --git a/chromium/chrome/common/custom_handlers/protocol_handler.cc b/chromium/chrome/common/custom_handlers/protocol_handler.cc
index 9afb863f903..55368f42aaf 100644
--- a/chromium/chrome/common/custom_handlers/protocol_handler.cc
+++ b/chromium/chrome/common/custom_handlers/protocol_handler.cc
@@ -7,7 +7,7 @@
#include "base/macros.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/value_conversions.h"
+#include "base/util/values/values_util.h"
#include "chrome/grit/generated_resources.h"
#include "content/public/common/origin_util.h"
#include "extensions/common/constants.h"
@@ -86,10 +86,11 @@ ProtocolHandler ProtocolHandler::CreateProtocolHandler(
base::Time time;
value->GetString("protocol", &protocol);
value->GetString("url", &url);
- const base::Value* time_value = value->FindKey("last_modified");
+ base::Optional<base::Time> time_value =
+ util::ValueToTime(value->FindKey("last_modified"));
// Treat invalid times as the default value.
if (time_value)
- ignore_result(base::GetValueAsTime(*time_value, &time));
+ time = *time_value;
return ProtocolHandler(protocol, GURL(url), time);
}
@@ -105,7 +106,7 @@ std::unique_ptr<base::DictionaryValue> ProtocolHandler::Encode() const {
auto d = std::make_unique<base::DictionaryValue>();
d->SetString("protocol", protocol_);
d->SetString("url", url_.spec());
- d->SetKey("last_modified", base::CreateTimeValue(last_modified_));
+ d->SetKey("last_modified", util::TimeToValue(last_modified_));
return d;
}
diff --git a/chromium/chrome/common/extensions/api/PRESUBMIT.py b/chromium/chrome/common/extensions/api/PRESUBMIT.py
index 88e6835d021..64d017e6b84 100644
--- a/chromium/chrome/common/extensions/api/PRESUBMIT.py
+++ b/chromium/chrome/common/extensions/api/PRESUBMIT.py
@@ -13,46 +13,15 @@ import sys
def _CheckExterns(input_api, output_api):
original_sys_path = sys.path
-
join = input_api.os_path.join
- api_root = input_api.PresubmitLocalPath()
- src_root = join(api_root, '..', '..', '..', '..')
+ src_root = input_api.change.RepositoryRoot()
try:
sys.path.append(join(src_root, 'extensions', 'common', 'api'))
from externs_checker import ExternsChecker
finally:
sys.path = original_sys_path
- externs_root = join(src_root, 'third_party', 'closure_compiler', 'externs')
-
- api_pair_names = {
- 'accessibility_private.json': 'accessibility_private.js',
- 'activity_log_private.json': 'activity_log_private.js',
- 'autofill_private.idl': 'autofill_private.js',
- 'developer_private.idl': 'developer_private.js',
- 'bookmark_manager_private.json': 'bookmark_manager_private.js',
- 'command_line_private.json': 'command_line_private.js',
- 'file_manager_private.idl': 'file_manager_private.js',
- 'file_system_provider.idl': 'file_system_provider.js',
- 'input_method_private.json': 'input_method_private.js',
- 'language_settings_private.idl': 'language_settings_private.js',
- 'media_player_private.json': 'media_player_private.js',
- 'passwords_private.idl': 'passwords_private.js',
- 'quick_unlock_private.idl': 'quick_unlock_private.js',
- 'resources_private.idl': 'resources_private.js',
- 'safe_browsing_private.idl': 'safe_browsing_private.js',
- 'settings_private.idl': 'settings_private.js',
- 'system_private.json': 'system_private.js',
- 'users_private.idl': 'users_private.js',
- # TODO(rdevlin.cronin): Add more!
- }
- normpath = input_api.os_path.normpath
- api_pairs = {
- normpath(join(api_root, k)):
- normpath(join(externs_root, v)) for k, v in api_pair_names.items()
- }
-
- return ExternsChecker(input_api, output_api, api_pairs).RunChecks()
+ return ExternsChecker(input_api, output_api).RunChecks()
def CheckChangeOnUpload(input_api, output_api):
diff --git a/chromium/chrome/common/extensions/api/_api_features.json b/chromium/chrome/common/extensions/api/_api_features.json
index 5f7d5bf1dcc..ea4b1fa0be1 100644
--- a/chromium/chrome/common/extensions/api/_api_features.json
+++ b/chromium/chrome/common/extensions/api/_api_features.json
@@ -61,9 +61,6 @@
"dependencies": ["manifest:action"],
"contexts": ["blessed_extension"]
},
- "action.setIcon": {
- "disallow_for_service_workers": true
- },
"activityLogPrivate": [{
"dependencies": ["permission:activityLogPrivate"],
"contexts": ["blessed_extension"]
@@ -189,22 +186,6 @@
"dependencies": ["permission:cast"],
"contexts": ["blessed_extension"]
},
- "cast.streaming.rtpStream": {
- "dependencies": ["permission:cast.streaming"],
- "contexts": ["blessed_extension"]
- },
- "cast.streaming.receiverSession": {
- "dependencies": ["permission:cast.streaming"],
- "contexts": ["blessed_extension"]
- },
- "cast.streaming.session": {
- "dependencies": ["permission:cast.streaming"],
- "contexts": ["blessed_extension"]
- },
- "cast.streaming.udpTransport": {
- "dependencies": ["permission:cast.streaming"],
- "contexts": ["blessed_extension"]
- },
"certificateProvider": {
"dependencies": ["permission:certificateProvider"],
"contexts": ["blessed_extension"]
@@ -357,6 +338,10 @@
"dependencies": ["permission:enterprise.deviceAttributes"],
"contexts": ["blessed_extension"]
},
+ "enterprise.networkingAttributes": {
+ "dependencies": ["permission:enterprise.networkingAttributes"],
+ "contexts": ["blessed_extension"]
+ },
"enterprise.platformKeys": {
"dependencies": ["permission:enterprise.platformKeys"],
"contexts": ["blessed_extension"],
diff --git a/chromium/chrome/common/extensions/api/_manifest_features.json b/chromium/chrome/common/extensions/api/_manifest_features.json
index 5e06b7a2e39..7ff07461a19 100644
--- a/chromium/chrome/common/extensions/api/_manifest_features.json
+++ b/chromium/chrome/common/extensions/api/_manifest_features.json
@@ -12,7 +12,7 @@
"extension_types": ["shared_module"]
},
"action": {
- "channel": "trunk",
+ "channel": "canary",
"extension_types": ["extension"]
},
"app.icon_color": {
diff --git a/chromium/chrome/common/extensions/api/_permission_features.json b/chromium/chrome/common/extensions/api/_permission_features.json
index a821970237b..f2fcf969cb5 100644
--- a/chromium/chrome/common/extensions/api/_permission_features.json
+++ b/chromium/chrome/common/extensions/api/_permission_features.json
@@ -59,6 +59,7 @@
"channel": "stable",
"extension_types": ["extension"],
"whitelist": [
+ "05D1DBD6E8B9C4690FFA7D50E6F60C5290DC662A", // http://crbug.com/941107
"0D209B5E4401BB8E7873B5AB5B1346A1CB067015", // http://crbug.com/654525
"93CFDA3681E923AD7AB291CEDD98248396B5496C" // http://crbug.com/803543
]
@@ -82,17 +83,6 @@
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]
},
- "cast.streaming": [{
- "channel": "dev",
- "extension_types": ["extension"]
- }, {
- "channel": "stable",
- "extension_types": ["extension"],
- "whitelist": [
- "63ED55E43214C211F82122ED56407FF1A807F2A3", // Media Router Dev
- "226CF815E39A363090A1E547D53063472B8279FA" // Media Router Stable
- ]
- }],
"certificateProvider": {
"channel": "stable",
"platforms": ["chromeos"],
@@ -284,6 +274,31 @@
"320857126E2180A5751AA384B7B7332A4964BD8C" // Imprivata (login screen) crbug.com/1065112
]
}],
+ "enterprise.networkingAttributes": [{
+ "channel": "stable",
+ "platforms": ["chromeos"],
+ "extension_types": ["extension"],
+ "location": "policy"
+ }, {
+ "channel": "stable",
+ "extension_types": ["login_screen_extension"],
+ "location": "policy",
+ "platforms": ["chromeos"],
+ "whitelist": [
+ "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) crbug.com/1065112
+ "4DBFC1C52D6660DD90791976DF7FEF7B3D360509", // Imprivata (login screen) crbug.com/1065112
+ "CDA6A10BE50CE65C59B766D0CE6A27E8E0A1533F", // Imprivata (login screen) crbug.com/1065112
+ "D85454743B32D9F5ABF3E5F18DF78809F3A0ABD4", // Imprivata (login screen) crbug.com/1065112
+ "04569B963251EB28C0906099668D98EE65ECA2D8", // Imprivata (login screen) crbug.com/1065112
+ "7BF5B69C3ACA9E6ACA5C480661B8073EB9FA32A9", // Imprivata (login screen) crbug.com/1065112
+ "5F2EF8E9F7E975090278D6A0AD039860430C5684", // Imprivata (login screen) crbug.com/1065112
+ "97A4DC8AFC1FCF665C71B624A55675C297AB256C", // Imprivata (login screen) crbug.com/1065112
+ "A00EB72B456C374F1EA86C09833C7DBB6CD95CAE", // Imprivata (login screen) crbug.com/1065112
+ "51DDBADA37EF4D25AD03CB1BB6451799456FE183", // Imprivata (login screen) crbug.com/1065112
+ "DD97CAE4D8658003658140109BC119188A19A5B8", // Imprivata (login screen) crbug.com/1065112
+ "320857126E2180A5751AA384B7B7332A4964BD8C" // Imprivata (login screen) crbug.com/1065112
+ ]
+ }],
"enterprise.hardwarePlatform": {
"channel": "stable",
"extension_types": ["extension"],
@@ -294,7 +309,28 @@
"platforms": ["chromeos"],
"extension_types": ["extension", "platform_app", "legacy_packaged_app"],
"location": "policy"
- }, {
+ },
+ {
+ "channel": "stable",
+ "extension_types": ["login_screen_extension"],
+ "location": "policy",
+ "platforms": ["chromeos"],
+ "whitelist": [
+ "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) crbug.com/1065112
+ "4DBFC1C52D6660DD90791976DF7FEF7B3D360509", // Imprivata (login screen) crbug.com/1065112
+ "CDA6A10BE50CE65C59B766D0CE6A27E8E0A1533F", // Imprivata (login screen) crbug.com/1065112
+ "D85454743B32D9F5ABF3E5F18DF78809F3A0ABD4", // Imprivata (login screen) crbug.com/1065112
+ "04569B963251EB28C0906099668D98EE65ECA2D8", // Imprivata (login screen) crbug.com/1065112
+ "7BF5B69C3ACA9E6ACA5C480661B8073EB9FA32A9", // Imprivata (login screen) crbug.com/1065112
+ "5F2EF8E9F7E975090278D6A0AD039860430C5684", // Imprivata (login screen) crbug.com/1065112
+ "97A4DC8AFC1FCF665C71B624A55675C297AB256C", // Imprivata (login screen) crbug.com/1065112
+ "A00EB72B456C374F1EA86C09833C7DBB6CD95CAE", // Imprivata (login screen) crbug.com/1065112
+ "51DDBADA37EF4D25AD03CB1BB6451799456FE183", // Imprivata (login screen) crbug.com/1065112
+ "DD97CAE4D8658003658140109BC119188A19A5B8", // Imprivata (login screen) crbug.com/1065112
+ "320857126E2180A5751AA384B7B7332A4964BD8C" // Imprivata (login screen) crbug.com/1065112
+ ]
+ },
+ {
"channel": "stable",
"platforms": ["chromeos"],
"extension_types": ["extension"],
@@ -622,6 +658,25 @@
"channel": "stable",
"extension_types": ["platform_app"],
"session_types": ["kiosk"]
+ },
+ {
+ "channel": "stable",
+ "extension_types": ["login_screen_extension"],
+ "min_manifest_version": 2,
+ "whitelist": [
+ "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) crbug.com/1065112
+ "4DBFC1C52D6660DD90791976DF7FEF7B3D360509", // Imprivata (login screen) crbug.com/1065112
+ "CDA6A10BE50CE65C59B766D0CE6A27E8E0A1533F", // Imprivata (login screen) crbug.com/1065112
+ "D85454743B32D9F5ABF3E5F18DF78809F3A0ABD4", // Imprivata (login screen) crbug.com/1065112
+ "04569B963251EB28C0906099668D98EE65ECA2D8", // Imprivata (login screen) crbug.com/1065112
+ "7BF5B69C3ACA9E6ACA5C480661B8073EB9FA32A9", // Imprivata (login screen) crbug.com/1065112
+ "5F2EF8E9F7E975090278D6A0AD039860430C5684", // Imprivata (login screen) crbug.com/1065112
+ "97A4DC8AFC1FCF665C71B624A55675C297AB256C", // Imprivata (login screen) crbug.com/1065112
+ "A00EB72B456C374F1EA86C09833C7DBB6CD95CAE", // Imprivata (login screen) crbug.com/1065112
+ "51DDBADA37EF4D25AD03CB1BB6451799456FE183", // Imprivata (login screen) crbug.com/1065112
+ "DD97CAE4D8658003658140109BC119188A19A5B8", // Imprivata (login screen) crbug.com/1065112
+ "320857126E2180A5751AA384B7B7332A4964BD8C" // Imprivata (login screen) crbug.com/1065112
+ ]
}
],
"mediaPlayerPrivate": {
@@ -678,11 +733,31 @@
"extension_types": ["extension", "platform_app"],
"location": "component"
},
- "platformKeys": {
+ "platformKeys": [{
"channel": "stable",
"platforms": ["chromeos"],
"extension_types": ["extension", "platform_app"]
},
+ {
+ "channel": "stable",
+ "extension_types": ["login_screen_extension"],
+ "location": "policy",
+ "platforms": ["chromeos"],
+ "whitelist": [
+ "E219EE36A3B40612FD2A8CD6937B03EF0C97D3FE", // Imprivata (login screen) crbug.com/1065112
+ "4DBFC1C52D6660DD90791976DF7FEF7B3D360509", // Imprivata (login screen) crbug.com/1065112
+ "CDA6A10BE50CE65C59B766D0CE6A27E8E0A1533F", // Imprivata (login screen) crbug.com/1065112
+ "D85454743B32D9F5ABF3E5F18DF78809F3A0ABD4", // Imprivata (login screen) crbug.com/1065112
+ "04569B963251EB28C0906099668D98EE65ECA2D8", // Imprivata (login screen) crbug.com/1065112
+ "7BF5B69C3ACA9E6ACA5C480661B8073EB9FA32A9", // Imprivata (login screen) crbug.com/1065112
+ "5F2EF8E9F7E975090278D6A0AD039860430C5684", // Imprivata (login screen) crbug.com/1065112
+ "97A4DC8AFC1FCF665C71B624A55675C297AB256C", // Imprivata (login screen) crbug.com/1065112
+ "A00EB72B456C374F1EA86C09833C7DBB6CD95CAE", // Imprivata (login screen) crbug.com/1065112
+ "51DDBADA37EF4D25AD03CB1BB6451799456FE183", // Imprivata (login screen) crbug.com/1065112
+ "DD97CAE4D8658003658140109BC119188A19A5B8", // Imprivata (login screen) crbug.com/1065112
+ "320857126E2180A5751AA384B7B7332A4964BD8C" // Imprivata (login screen) crbug.com/1065112
+ ]
+ }],
"plugin": {
"channel": "stable",
"extension_types": ["extension", "legacy_packaged_app"]
diff --git a/chromium/chrome/common/extensions/api/accessibility_features.json b/chromium/chrome/common/extensions/api/accessibility_features.json
index 499a89a3e91..b6dac608602 100644
--- a/chromium/chrome/common/extensions/api/accessibility_features.json
+++ b/chromium/chrome/common/extensions/api/accessibility_features.json
@@ -61,6 +61,12 @@
"value": ["cursorHighlight", {"type": "boolean"}],
"platforms": ["chromeos"]
},
+ "cursorColor": {
+ "$ref": "types.ChromeSetting",
+ "description": "<p><strong>ChromeOS only.</strong></p><p>Cursor color. The value indicates whether the feature is enabled or not. <code>get()</code> requires <code>accessibilityFeatures.read</code> permission. <code>set()</code> and <code>clear()</code> require <code>accessibilityFeatures.modify</code> permission.</p>",
+ "value": ["cursorColor", {"type": "boolean"}],
+ "platforms": ["chromeos"]
+ },
"focusHighlight": {
"$ref": "types.ChromeSetting",
"description": "<p><strong>ChromeOS only.</strong></p><p>Focus highlighting. The value indicates whether the feature is enabled or not. <code>get()</code> requires <code>accessibilityFeatures.read</code> permission. <code>set()</code> and <code>clear()</code> require <code>accessibilityFeatures.modify</code> permission.</p>",
diff --git a/chromium/chrome/common/extensions/api/accessibility_private.json b/chromium/chrome/common/extensions/api/accessibility_private.json
index c4d778f0fd3..205c2e5b65e 100644
--- a/chromium/chrome/common/extensions/api/accessibility_private.json
+++ b/chromium/chrome/common/extensions/api/accessibility_private.json
@@ -278,29 +278,6 @@
]
},
{
- "name": "setSwitchAccessMenuState",
- "type": "function",
- "description": "Shows or hides the Switch Access menu. If shown, it is at the indicated location.\nTODO(anastasi): Remove this function once the menu refactor is complete.",
- "parameters": [
- {
- "name": "show",
- "type": "boolean",
- "description": "If true, show the menu. If false, hide the menu."
- },
- {
- "name": "element_bounds",
- "$ref": "ScreenRect",
- "description": "Position of an element, in global screen coordinates, to place the menu next to."
- },
- {
- "name": "item_count",
- "type": "integer",
- "description": "The number of items that need to be shown in the menu."
- }
- ],
- "platforms": ["chromeos"]
- },
- {
"name": "forwardKeyEventsToSwitchAccess",
"type": "function",
"description": "When enabled, forwards key events to the Switch Access extension",
@@ -410,7 +387,7 @@
{
"name": "onScrollableBoundsForPointFound",
"type": "function",
- "description": "Called by the Autoclick extension when findScrollableBoundsForPoint has found a scrolling container. |rect| will be the bounds of the nearest scrollable ancestor of the node at the point requested using findScrollableBoundsForPoint.",
+ "description": "Called by the Accessibility Common extension when findScrollableBoundsForPoint has found a scrolling container. |rect| will be the bounds of the nearest scrollable ancestor of the node at the point requested using findScrollableBoundsForPoint.",
"parameters": [
{
"name": "rect",
diff --git a/chromium/chrome/common/extensions/api/api_sources.gni b/chromium/chrome/common/extensions/api/api_sources.gni
index 6cc8b9297ce..b8f3326d699 100644
--- a/chromium/chrome/common/extensions/api/api_sources.gni
+++ b/chromium/chrome/common/extensions/api/api_sources.gni
@@ -11,10 +11,6 @@ schema_sources_ = [
"accessibility_features.json",
"accessibility_private.json",
"activity_log_private.json",
- "cast_streaming_receiver_session.idl",
- "cast_streaming_rtp_stream.idl",
- "cast_streaming_session.idl",
- "cast_streaming_udp_transport.idl",
"autofill_private.idl",
"autotest_private.idl",
"bookmark_manager_private.json",
@@ -86,6 +82,7 @@ if (is_chromeos) {
"certificate_provider_internal.idl",
"echo_private.json",
"enterprise_device_attributes.idl",
+ "enterprise_networking_attributes.idl",
"enterprise_platform_keys.idl",
"enterprise_platform_keys_internal.idl",
"enterprise_platform_keys_private.json",
@@ -103,7 +100,6 @@ if (is_chromeos) {
"login_state.idl",
"platform_keys.idl",
"platform_keys_internal.idl",
- "printing_metrics.idl",
"quick_unlock_private.idl",
"terminal_private.json",
"users_private.idl",
@@ -111,7 +107,10 @@ if (is_chromeos) {
"wallpaper_private.json",
]
if (use_cups) {
- schema_sources_ += [ "printing.idl" ]
+ schema_sources_ += [
+ "printing.idl",
+ "printing_metrics.idl",
+ ]
}
} else if (is_linux || is_win) {
schema_sources_ += [ "input_ime.json" ]
diff --git a/chromium/chrome/common/extensions/api/autofill_assistant_private.idl b/chromium/chrome/common/extensions/api/autofill_assistant_private.idl
index 08ebb415a00..95a2492d19c 100644
--- a/chromium/chrome/common/extensions/api/autofill_assistant_private.idl
+++ b/chromium/chrome/common/extensions/api/autofill_assistant_private.idl
@@ -12,7 +12,7 @@
// and can be executed via <code>performAction</code>.
namespace autofillAssistantPrivate {
// Success or error of a function call will be communicated by setting
- // chrome.runtime.lastError.
+ // $(ref:runtime.lastError).
callback VoidCallback = void ();
dictionary ActionObject {
diff --git a/chromium/chrome/common/extensions/api/autofill_private.idl b/chromium/chrome/common/extensions/api/autofill_private.idl
index 5d00acd41b0..d7980c99df9 100644
--- a/chromium/chrome/common/extensions/api/autofill_private.idl
+++ b/chromium/chrome/common/extensions/api/autofill_private.idl
@@ -161,6 +161,9 @@ namespace autofillPrivate {
// Year as a 4-character string (as in "2015").
DOMString? expirationYear;
+ // Credit card's nickname.
+ DOMString? nickname;
+
AutofillMetadata? metadata;
};
diff --git a/chromium/chrome/common/extensions/api/autotest_private.idl b/chromium/chrome/common/extensions/api/autotest_private.idl
index 06d005ecb8e..3eb6e5ce052 100644
--- a/chromium/chrome/common/extensions/api/autotest_private.idl
+++ b/chromium/chrome/common/extensions/api/autotest_private.idl
@@ -692,6 +692,7 @@ namespace autotestPrivate {
// |callback|: Called when the operation has completed.
static void importCrostini(DOMString path, VoidCallback callback);
+ // TODO(b/156566782): Remove this after M85 branches.
// Installs Plugin VM via the installer and then launches the VM.
// |imageUrl|: URL to the image to install.
// |imageHash|: Hash for the provided image.
@@ -702,6 +703,17 @@ namespace autotestPrivate {
DOMString licenseKey,
VoidCallback callback);
+ // Sets mock Plugin VM policy.
+ // |imageUrl|: URL to the image to install.
+ // |imageHash|: Hash for the provided image.
+ // |licenseKey|: License key for Plugin VM.
+ static void setPluginVMPolicy(DOMString imageUrl,
+ DOMString imageHash,
+ DOMString licenseKey);
+
+ // Shows the Plugin VM installer. Does not start installation.
+ static void showPluginVMInstaller();
+
// Register a component with CrOSComponentManager.
// |name|: The name of the component.
// |path|: Path to the component.
@@ -1012,6 +1024,20 @@ namespace autotestPrivate {
// the display specified by the display id is used.
static void stopSmoothnessTracking(optional DOMString displayId,
StopSmoothnessTrackingCallback callback);
+
+ // When neccesary, disables showing the dialog when Switch Access is disabled.
+ static void disableSwitchAccessDialog();
+
+ // Waits for the completion of photo transition animation in ambient mode.
+ // |photoRefreshInterval|: photo refresh interval in seconds.
+ // |numCompletions|: number of completions of the animation.
+ // |timeout|: the timeout in seconds.
+ // |callback|: Called when the operation has completed.
+ static void waitForAmbientPhotoAnimation(
+ long photoRefreshInterval,
+ long numCompletions,
+ long timeout,
+ VoidCallback callback);
};
interface Events {
diff --git a/chromium/chrome/common/extensions/api/braille_display_private.idl b/chromium/chrome/common/extensions/api/braille_display_private.idl
index 7e5a8956ede..0a7415f5ae6 100644
--- a/chromium/chrome/common/extensions/api/braille_display_private.idl
+++ b/chromium/chrome/common/extensions/api/braille_display_private.idl
@@ -56,6 +56,8 @@ namespace brailleDisplayPrivate {
long? textRowCount;
// Number of columns of braille cells on the currently connected display.
long? textColumnCount;
+ // The number of dots in a braille cell on the currently connected display.
+ long? cellSize;
};
callback DisplayStateCallback = void(DisplayState result);
diff --git a/chromium/chrome/common/extensions/api/cast_streaming_receiver_session.idl b/chromium/chrome/common/extensions/api/cast_streaming_receiver_session.idl
deleted file mode 100644
index 15a7f0a7f49..00000000000
--- a/chromium/chrome/common/extensions/api/cast_streaming_receiver_session.idl
+++ /dev/null
@@ -1,70 +0,0 @@
-// 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.
-
-// The <code>chrome.cast.streaming.receiverSession</code> API creates a Cast
-// receiver session and adds the resulting audio and video tracks to a
-// MediaStream.
-namespace cast.streaming.receiverSession {
- // The UDP socket address and port.
- dictionary IPEndPoint {
- DOMString address;
- long port;
- };
-
- // RTP receiver parameters.
- dictionary RtpReceiverParams {
- // Maximum latency in milliseconds. This parameter controls the logic
- // of flow control. Implementation can adjust latency adaptively and
- // tries to keep it under this threshold. A larger value allows smoother
- // playback at the cost of higher latency.
- long maxLatency;
-
- DOMString codecName;
-
- // Synchronization source identifier for incoming data.
- long senderSsrc;
-
- // The SSRC used to send RTCP reports back to the sender.
- long receiverSsrc;
-
- // RTP time units per second, defaults to 48000 for audio
- // and 90000 for video.
- long? rtpTimebase;
-
- // 32 bytes hex-encoded AES key.
- DOMString? aesKey;
-
- // 32 bytes hex-encoded AES IV (Initialization vector) mask.
- DOMString? aesIvMask;
- };
-
- callback ErrorCallback = void (DOMString error);
-
- interface Functions {
- // Creates a Cast receiver session which receives data from a UDP
- // socket. The receiver will decode the incoming data into an audio
- // and a video track which will be added to the provided media stream.
- // The |audioParams| and |videoParams| are generally provided by the
- // sender through some other messaging channel.
- //
- // |audioParams| : Audio stream parameters.
- // |videoParams| : Video stream parameters.
- // |localEndpoint| : Local IP and port to bind to.
- // |height| : Video height.
- // |width| : Video width.
- // |maxFrameRate| : Max video frame rate.
- // |mediaStreamURL| : URL of MediaStream to add the audio and video to.
- // |transport_options| : Optional transport settings.
- [nocompile] static void createAndBind(
- RtpReceiverParams audioParams,
- RtpReceiverParams videoParams,
- IPEndPoint localEndpoint,
- long maxWidth,
- long maxHeight,
- double maxFrameRate,
- DOMString mediaStreamURL,
- ErrorCallback error_callback,
- optional object transport_options);
- };
-};
diff --git a/chromium/chrome/common/extensions/api/cast_streaming_rtp_stream.idl b/chromium/chrome/common/extensions/api/cast_streaming_rtp_stream.idl
deleted file mode 100644
index 8425609f3f5..00000000000
--- a/chromium/chrome/common/extensions/api/cast_streaming_rtp_stream.idl
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2013 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.
-
-// The <code>chrome.cast.streaming.rtpStream</code> API allows configuration
-// of encoding parameters and RTP parameters used in a Cast streaming
-// session.
-//
-// Valid stream IDs are positive and non-zero.
-namespace cast.streaming.rtpStream {
- // Params for audio and video codec.
- dictionary CodecSpecificParams {
- DOMString key;
- DOMString value;
- };
-
- // RTP payload param.
- dictionary RtpPayloadParams {
- long payloadType;
-
- // Maximum latency in milliseconds. This parameter controls the logic
- // of flow control. Implementation can adjust latency adaptively and
- // tries to keep it under this threshold. A larger value allows smoother
- // playback at the cost of higher latency.
- long maxLatency;
-
- // Minimum latency in milliseconds. Defaults to |maxLatency|.
- long? minLatency;
-
- // Starting latency for animated content in milliseconds.
- // Defaults to |maxLatency|.
- long? animatedLatency;
-
- DOMString codecName;
-
- // Synchronization source identifier.
- long ssrc;
-
- long feedbackSsrc;
-
- long? clockRate;
-
- // Minimum bitrate in kilobits per second.
- long? minBitrate;
-
- // Maximum bitrate in kilobits per second.
- long? maxBitrate;
-
- // The number of channels.
- long? channels;
-
- // The maximum frame rate.
- double? maxFrameRate;
-
- // 32 bytes hex-encoded AES key.
- DOMString? aesKey;
-
- // 32 bytes hex-encoded AES IV (Initialization vector) mask.
- DOMString? aesIvMask;
-
- // A list of codec specific params.
- CodecSpecificParams[] codecSpecificParams;
- };
-
- // Cast RTP parameters.
- dictionary RtpParams {
- // RTP payload params.
- RtpPayloadParams payload;
-
- DOMString[] rtcpFeatures;
- };
-
- // Callback from the <code>create</code> method.
- // |id| : The ID for the RTP stream.
- callback CreateCallback = void (long streamId);
-
- // Callback from the <code>getRawEvents</code> method.
- // |rawEvents|: compressed serialized raw bytes containing raw events
- // recorded for a stream.
- // The compression is in gzip format.
- // The serialization format can be found at
- // media/cast/logging/log_serializer.cc.
- callback GetRawEventsCallback = void (ArrayBuffer rawEvents);
-
- // Callback from the <code>getStats</code> method.
- // |rawEvents|: dictionary object containing stats recorded for a stream.
- // The format can be found at
- // media/cast/logging/stats_event_subscriber.cc.
- callback GetStatsCallback = void (object stats);
-
- interface Functions {
- // Destroys a Cast RTP stream.
- // |streamId| : The RTP stream ID.
- [nocompile] static void destroy(long streamId);
-
- // Returns an array of supported parameters with default values.
- // This includes a list of supported codecs on this platform and
- // corresponding encoding and RTP parameters.
- // |streamId| : The RTP stream ID.
- [nocompile] static RtpParams[] getSupportedParams(long streamId);
-
- // Activates the RTP stream by providing the parameters.
- // |streamId| : The RTP stream ID.
- // |params| : Parameters set for this stream.
- [nocompile] static void start(long streamId, RtpParams params);
-
- // Stops activity on the specified stream.
- // |streamId| : The RTP stream ID.
- [nocompile] static void stop(long streamId);
-
- // Enables / disables logging for a stream.
- // |enable|: If true, enables logging. Otherwise disables logging.
- [nocompile] static void toggleLogging(long streamId, boolean enable);
-
- // Get raw events for a stream in the current session.
- // |streamId|: Stream to get events for.
- // |extraData|: Extra data to attach to the log, e.g. system info or
- // experiment tags, in key-value JSON string format.
- // |callback|: Called with the raw events.
- [nocompile] static void getRawEvents(
- long streamId, optional DOMString extraData,
- GetRawEventsCallback callback);
-
- // Get stats for a stream in the current session.
- // |streamId|: Stream to get stats for.
- // |callback|: Called with the stats.
- [nocompile] static void getStats(
- long streamId, GetStatsCallback callback);
- };
-
- interface Events {
- // Event fired when a Cast RTP stream has started.
- // |streamId| : The ID of the RTP stream.
- static void onStarted(long streamId);
-
- // Event fired when a Cast RTP stream has stopped.
- // |streamId| : The ID of the RTP stream.
- static void onStopped(long streamId);
-
- // Event fired when a Cast RTP stream has error.
- // |streamId| : The ID of the RTP stream.
- // |errorString| : The error info.
- static void onError(long streamId, DOMString errorString);
- };
-};
diff --git a/chromium/chrome/common/extensions/api/cast_streaming_session.idl b/chromium/chrome/common/extensions/api/cast_streaming_session.idl
deleted file mode 100644
index 29d43d9e8a6..00000000000
--- a/chromium/chrome/common/extensions/api/cast_streaming_session.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2013 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.
-
-// The <code>chrome.cast.streaming.session</code> API creates a Cast
-// session using WebMediaStreamTrack as sources. The session is composed
-// by RTP streams and a network transport.
-//
-// Calling this API will generate corresponding resources for use with
-// chrome.cast.streaming.rtpStream and chrome.cast.streaming.udpTransport
-// APIs.
-//
-// Valid resource IDs are positive and non-zero.
-namespace cast.streaming.session {
- // Callback from the <code>create</code> method.
- // |audioStreamId| : The audio RTP stream ID.
- // |videoStreamId| : The video RTP stream ID.
- // |udpTransportId| : The UDP transport ID.
- callback CreateCallback = void (long audioStreamId,
- long videoStreamId,
- long udpTransportId);
-
- interface Functions {
- // Creates a Cast session using the provided audio and video track as
- // source. The tracks must be of type MediaStreamTrack. This will
- // create two RTP streams and a UDP transport that builds the session.
- // Either |audioTrack| or |videoTrack| can be null but not both. This
- // means creating a session with only audio or video. If a given
- // track is null then the created stream ID will be null.
- //
- // |audioTrack| : the source audio track.
- // |videoTrack| : the source video track.
- // |callback| : Called when the sesion has been created.
- [nocompile,allowAmbiguousOptionalArguments] static void create(
- [instanceOf=MediaStreamTrack] optional object audioTrack,
- [instanceOf=MediaStreamTrack] optional object videoTrack,
- CreateCallback callback);
- };
-};
diff --git a/chromium/chrome/common/extensions/api/cast_streaming_udp_transport.idl b/chromium/chrome/common/extensions/api/cast_streaming_udp_transport.idl
deleted file mode 100644
index 8106a58f639..00000000000
--- a/chromium/chrome/common/extensions/api/cast_streaming_udp_transport.idl
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2013 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.
-
-// The <code>chrome.webrtc.castUdpTransport</code> API represents a UDP
-// transport for Cast RTP streams. This API is not useful when standalone
-// since it does not have send and receive methods.
-// It is used to configure the UDP transport used in Cast session.
-//
-// Valid transport IDs are positive and non-zero.
-namespace cast.streaming.udpTransport {
- // The UDP socket address and port.
- dictionary IPEndPoint {
- DOMString address;
- long port;
- };
-
- interface Functions {
- // Destroys a UDP transport.
- // |transportId| : The transport ID.
- [nocompile] static void destroy(long transportId);
-
- // Sets parameters for this UDP transport. This can only be called
- // once per transport.
- // |transportId| : The transport ID.
- // |destination| : The address and port to send packets to.
- [nocompile] static void setDestination(long transportId,
- IPEndPoint destination);
-
- // Sets the options.
- // Attributes of this object will be used to activate optional
- // behaviours in the transport. Normally this is only used for
- // experimentation. Must be called before setDestination.
- // |transportId| : The transport ID that is created by
- // chrome.cast.streaming.session.create().
- // |options| : A dictionary of key-value pairs of options.
- // See media/cast/net/cast_transport_sender_impl.h for supported
- // options.
- [nocompile] static void setOptions(long transportId,
- object options);
- };
-};
diff --git a/chromium/chrome/common/extensions/api/chrome_web_view_internal.json b/chromium/chrome/common/extensions/api/chrome_web_view_internal.json
index de404476af0..6b25a26a2a9 100644
--- a/chromium/chrome/common/extensions/api/chrome_web_view_internal.json
+++ b/chromium/chrome/common/extensions/api/chrome_web_view_internal.json
@@ -127,7 +127,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the item has been created in the browser. If there were any problems creating the item, details will be available in chrome.runtime.lastError.",
+ "description": "Called when the item has been created in the browser. If there were any problems creating the item, details will be available in $(ref:runtime.lastError).",
"parameters": []
}
]
diff --git a/chromium/chrome/common/extensions/api/chromeos_info_private.json b/chromium/chrome/common/extensions/api/chromeos_info_private.json
index 85b85e4e966..6aac013c587 100644
--- a/chromium/chrome/common/extensions/api/chromeos_info_private.json
+++ b/chromium/chrome/common/extensions/api/chromeos_info_private.json
@@ -26,8 +26,8 @@
"a11yFocusHighlightEnabled",
"a11ySelectToSpeakEnabled",
"a11ySwitchAccessEnabled",
- "sendFunctionKeys",
- "cameraMediaConsolidated"],
+ "a11yCursorColorEnabled",
+ "sendFunctionKeys"],
"description": "Chrome OS system property name"
},
{
@@ -107,10 +107,15 @@
"a11ySpokenFeedbackEnabled" : {"type": "boolean", "optional": true, "description": "If enabled, ChromeOS text-to-speech feature is turned on."},
"a11yHighContrastEnabled" : {"type": "boolean", "optional": true, "description": "If true, all displays have high contrast mode turned on."},
"a11yScreenMagnifierEnabled" : {"type": "boolean", "optional": true, "description": "If true, all displays have screen magnifier turned on."},
- "a11yAutoClickEnabled" : {"type": "boolean", "optional": true, "description": "If true, auto mouse click accessibility feature is turned on."},
+ "a11yAutoClickEnabled" : {"type": "boolean", "optional": true, "description": "If true, autoclick accessibility feature is turned on."},
"a11yVirtualKeyboardEnabled" : {"type": "boolean", "optional": true, "description": "If true, virtual keyboard will be enabled."},
+ "a11yCaretHighlightEnabled" : {"type": "boolean", "optional": true, "description": "If true, caret highlighting will be enabled."},
+ "a11yCursorHighlightEnabled" : {"type": "boolean", "optional": true, "description": "If true, cursor highlighting will be enabled."},
+ "a11yFocusHighlightEnabled" : {"type": "boolean", "optional": true, "description": "If true, focus highlighting will be enabled."},
+ "a11ySelectToSpeakEnabled" : {"type": "boolean", "optional": true, "description": "If true, select to speak will be enabled."},
+ "a11ySwitchAccessEnabled" : {"type": "boolean", "optional": true, "description": "If true, switch access will be enabled."},
+ "a11yCursorColorEnabled" : {"type": "boolean", "optional": true, "description": "If true, colorized cursor will be enabled."},
"sendFunctionKeys" : {"type": "boolean", "optional": true, "description": "If true, the ChromeOS top row keys send function keys."},
- "cameraMediaConsolidated" : {"type": "boolean", "optional": true, "description": "True if camera photos and videos have been consolidated to one place."},
"supportedTimezones" : {
"type": "array",
"items": {
diff --git a/chromium/chrome/common/extensions/api/context_menus.json b/chromium/chrome/common/extensions/api/context_menus.json
index fe2f7a1d674..348cba6ae3a 100644
--- a/chromium/chrome/common/extensions/api/context_menus.json
+++ b/chromium/chrome/common/extensions/api/context_menus.json
@@ -16,7 +16,7 @@
{
"id": "ContextType",
"type": "string",
- "enum": ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio", "launcher", "browser_action", "page_action"],
+ "enum": ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio", "launcher", "browser_action", "page_action", "action"],
"description": "The different contexts a menu can appear in. Specifying 'all' is equivalent to the combination of all other contexts except for 'launcher'. The 'launcher' context is only supported by apps and is used to add menu items to the context menu that appears when clicking the app icon in the launcher/taskbar/dock/etc. Different platforms might put limitations on what is actually supported in a launcher context menu."
},
{
@@ -30,7 +30,7 @@
{
"name": "create",
"type": "function",
- "description": "Creates a new context menu item. If an error occurs during creation, it may not be detected until the creation callback fires; details will be in <code>chrome.runtime.lastError</code>.",
+ "description": "Creates a new context menu item. If an error occurs during creation, it may not be detected until the creation callback fires; details will be in $(ref:runtime.lastError).",
"returns": {
"choices": [
{ "type": "integer" },
@@ -125,7 +125,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the item has been created in the browser. If an error occurs during creation, details will be available in <code>chrome.runtime.lastError</code>.",
+ "description": "Called when the item has been created in the browser. If an error occurs during creation, details will be available in $(ref:runtime.lastError).",
"parameters": []
}
]
diff --git a/chromium/chrome/common/extensions/api/cookies.json b/chromium/chrome/common/extensions/api/cookies.json
index a0ba8097915..544d75c0a6b 100644
--- a/chromium/chrome/common/extensions/api/cookies.json
+++ b/chromium/chrome/common/extensions/api/cookies.json
@@ -133,7 +133,7 @@
"min_version": "11.0.674.0",
"parameters": [
{
- "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set. If setting failed for any reason, this will be \"null\", and \"chrome.runtime.lastError\" will be set."
+ "name": "cookie", "$ref": "Cookie", "optional": true, "description": "Contains details about the cookie that's been set. If setting failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set."
}
]
}
@@ -163,7 +163,7 @@
{
"name": "details",
"type": "object",
- "description": "Contains details about the cookie that's been removed. If removal failed for any reason, this will be \"null\", and \"chrome.runtime.lastError\" will be set.",
+ "description": "Contains details about the cookie that's been removed. If removal failed for any reason, this will be \"null\", and $(ref:runtime.lastError) will be set.",
"optional": true,
"properties": {
"url": {"type": "string", "description": "The URL associated with the cookie that's been removed."},
diff --git a/chromium/chrome/common/extensions/api/developer_private.idl b/chromium/chrome/common/extensions/api/developer_private.idl
index b8029a0cf91..2a58e11650d 100644
--- a/chromium/chrome/common/extensions/api/developer_private.idl
+++ b/chromium/chrome/common/extensions/api/developer_private.idl
@@ -162,8 +162,7 @@ namespace developerPrivate {
};
enum ControllerType {
- POLICY,
- SUPERVISED_USER_CUSTODIAN
+ POLICY
};
enum HostAccess {
diff --git a/chromium/chrome/common/extensions/api/enterprise_networking_attributes.idl b/chromium/chrome/common/extensions/api/enterprise_networking_attributes.idl
new file mode 100644
index 00000000000..9e7fffcf16e
--- /dev/null
+++ b/chromium/chrome/common/extensions/api/enterprise_networking_attributes.idl
@@ -0,0 +1,33 @@
+// Copyright 2020 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.
+
+// Use the <code>chrome.enterprise.networkingAttributes</code> API to read
+// information about your current network.
+// Note: This API is only available to extensions force-installed by enterprise
+// policy.
+[platforms = ("chromeos"),
+ implemented_in = "chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_api.h"]
+namespace enterprise.networkingAttributes {
+ [noinline_doc] dictionary NetworkDetails {
+ // The device's MAC address.
+ DOMString macAddress;
+
+ // The device's local IPv4 address (undefined if not configured).
+ DOMString? ipv4;
+
+ // The device's local IPv6 address (undefined if not configured).
+ DOMString? ipv6;
+ };
+
+ callback GetNetworkDetailsCallback = void(NetworkDetails networkAddresses);
+
+ interface Functions {
+ // Retrieves the network details of the device's default network.
+ // If the user is not affiliated or the device is not connected to a
+ // network, $(ref:runtime.lastError) will be set with a failure reason.
+ // |callback| : Called with the device's default network's
+ // $(ref:NetworkDetails).
+ void getNetworkDetails(GetNetworkDetailsCallback callback);
+ };
+};
diff --git a/chromium/chrome/common/extensions/api/enterprise_reporting_private.idl b/chromium/chrome/common/extensions/api/enterprise_reporting_private.idl
index 04e83aedd0f..98ffaabb3b7 100644
--- a/chromium/chrome/common/extensions/api/enterprise_reporting_private.idl
+++ b/chromium/chrome/common/extensions/api/enterprise_reporting_private.idl
@@ -39,7 +39,7 @@ namespace enterprise.reportingPrivate {
interface Functions {
// Uploads the status of Chrome browser to the admin console by sending
- // request to the DMServer. Sets runtime.lastError on failure.
+ // request to the DMServer. Sets $(ref:runtime.lastError) on failure.
static void uploadChromeDesktopReport(
object report,
optional DoneCallback callback);
@@ -52,12 +52,12 @@ namespace enterprise.reportingPrivate {
// can be used to encrypt the data stored with |setDeviceData|.
static void getPersistentSecret(GetPersistentSecretCallback callback);
- // Gets the device data for |id|. Sets runtime.lastError on failure.
+ // Gets the device data for |id|. Sets $(ref:runtime.lastError) on failure.
static void getDeviceData(DOMString id, GetDeviceDataCallback callback);
- // Sets the device data for |id|. Sets runtime.lastError on failure. If the
- // |data| parameter is undefined and there is already data associated with
- // |id| it will be cleared.
+ // Sets the device data for |id|. Sets $(ref:runtime.lastError) on failure.
+ // If the |data| parameter is undefined and there is already data
+ // associated with |id| it will be cleared.
static void setDeviceData(DOMString id,
optional ArrayBuffer data,
optional DoneCallback callback);
diff --git a/chromium/chrome/common/extensions/api/extension_action/action_info_test_util.cc b/chromium/chrome/common/extensions/api/extension_action/action_info_test_util.cc
index a869245fba8..f3ef0aa3029 100644
--- a/chromium/chrome/common/extensions/api/extension_action/action_info_test_util.cc
+++ b/chromium/chrome/common/extensions/api/extension_action/action_info_test_util.cc
@@ -54,13 +54,19 @@ const ActionInfo* GetActionInfoOfType(const Extension& extension,
std::unique_ptr<ScopedCurrentChannel> GetOverrideChannelForActionType(
ActionInfo::Type action_type) {
std::unique_ptr<ScopedCurrentChannel> channel;
- // The "action" key is currently restricted to trunk. Use a fake channel iff
- // we're testing that key, so that we still get multi-channel coverage for
- // browser and page actions.
+ // The "action" key is currently restricted to canary. Use a fake channel iff
+ // it would be restricted otherwise. This way, we still get all-channel
+ // coverage for browser and page actions, and cover all channels that "action"
+ // is supported in.
+ constexpr version_info::Channel kMaxChannelForActionKey =
+ version_info::Channel::CANARY;
+
switch (action_type) {
case ActionInfo::TYPE_ACTION:
- channel = std::make_unique<ScopedCurrentChannel>(
- version_info::Channel::UNKNOWN);
+ if (GetCurrentChannel() > kMaxChannelForActionKey) {
+ channel =
+ std::make_unique<ScopedCurrentChannel>(kMaxChannelForActionKey);
+ }
break;
case ActionInfo::TYPE_PAGE:
case ActionInfo::TYPE_BROWSER:
diff --git a/chromium/chrome/common/extensions/api/file_manager_private.idl b/chromium/chrome/common/extensions/api/file_manager_private.idl
index 6c44f5153be..0945e90f5b1 100644
--- a/chromium/chrome/common/extensions/api/file_manager_private.idl
+++ b/chromium/chrome/common/extensions/api/file_manager_private.idl
@@ -146,7 +146,8 @@ enum DriveSyncErrorType {
misc
};
-// Result of task execution.
+// Result of task execution. If changing, update the strings used in
+// ui/file_manager/file_manager/foreground/js/file_tasks.js
enum TaskResult {
// The task execution succeeded and a new window/tab was opened.
opened,
@@ -156,7 +157,11 @@ enum TaskResult {
// The task execution failed.
failed,
// No URL is specified.
- empty
+ empty,
+ // The task was a |plugin_vm| task, and the file was in a unshared directory
+ failed_plugin_vm_task_directory_not_shared,
+ // The task was a |plugin_vm| task, and the file was in an external drive.
+ failed_plugin_vm_task_external_drive
};
// Drive share type.
@@ -1099,23 +1104,23 @@ interface Functions {
// Returns list of available providers.
static void getProviders(GetProvidersCallback callback);
- // Requests adding a new provided file system. If not possible, then an error
- // via chrome.runtime.lastError is returned.
+ // Requests adding a new provided file system. On failure, sets
+ // $(ref:runtime.lastError).
static void addProvidedFileSystem(DOMString provider_id,
SimpleCallback callback);
- // Requests configuring an existing volume. If not possible, then returns
- // an error via chrome.runtime.lastError.
+ // Requests configuring an existing volume. On failure, sets
+ // $(ref:runtime.lastError).
static void configureVolume(DOMString volumeId, SimpleCallback callback);
- // Requests list of custom actions for the specified entries. If not possible,
- // then an error via chrome.runtime.lastError is returned.
+ // Requests list of custom actions for the specified entries. On failure, sets
+ // $(ref:runtime.lastError).
[nocompile]
static void getCustomActions([instanceof=Entry] object[] entries,
GetCustomActionsCallback callback);
- // Executes a custom action for a set of entries. If not possible, then an
- // error via chrome.runtime.lastError is returned.
+ // Executes a custom action for a set of entries. On failure, sets
+ // $(ref:runtime.lastError).
[nocompile]
static void executeCustomAction([instanceof=Entry] object[] entries,
DOMString actionId,
@@ -1181,7 +1186,7 @@ interface Functions {
[nocompile]
static void importCrostiniImage([instanceof=Entry] object entry);
- // For a file in DriveFS, retrieves its thumbnail. If |cropToSquare| is true,
+ // For a given file entry, retrieves its thumbnail. If |cropToSquare| is true,
// returns a thumbnail appropriate for file list or grid views; otherwise,
// returns a thumbnail appropriate for quickview.
[nocompile]
diff --git a/chromium/chrome/common/extensions/api/generated_externs_list.txt b/chromium/chrome/common/extensions/api/generated_externs_list.txt
new file mode 100644
index 00000000000..4da5bd1f7ff
--- /dev/null
+++ b/chromium/chrome/common/extensions/api/generated_externs_list.txt
@@ -0,0 +1,24 @@
+# All APIs that have their externs generated.
+# TODO(rdevlin.cronin): Add more!
+accessibility_private.json
+activity_log_private.json
+autofill_private.idl
+bookmark_manager_private.json
+chromeos_info_private.json
+command_line_private.json
+developer_private.idl
+file_manager_private.idl
+file_system_provider.idl
+input_method_private.json
+language_settings_private.idl
+login_state.idl
+media_player_private.json
+passwords_private.idl
+quick_unlock_private.idl
+resources_private.idl
+safe_browsing_private.idl
+settings_private.idl
+system_private.json
+terminal_private.json
+users_private.idl
+webview_tag.json
diff --git a/chromium/chrome/common/extensions/api/input_ime.json b/chromium/chrome/common/extensions/api/input_ime.json
index 93339e6fd43..bac699f0bd9 100644
--- a/chromium/chrome/common/extensions/api/input_ime.json
+++ b/chromium/chrome/common/extensions/api/input_ime.json
@@ -104,34 +104,40 @@
"enum": ["left", "middle", "right"]
},
{
- "id": "WindowType",
+ "id": "AssistiveWindowType",
"type": "string",
- "description": "The IME window types.",
- "platforms": ["win", "linux"],
- "enum": ["normal", "followCursor"]
+ "description": "Type of assistive window.",
+ "enum": [
+ "undo"
+ ]
},
{
- "id": "Bounds",
+ "id": "AssistiveWindowProperties",
"type": "object",
- "description": "Describes the screen coordinates of a rect.",
- "platforms": ["win", "linux"],
+ "description": "Properties of the assistive window.",
"properties": {
- "left": {"type": "integer", "description": "The left of the bounds."},
- "top": {"type": "integer", "description": "The top of the bounds."},
- "width": {"type": "integer", "description": "The width of the bounds." },
- "height": {"type": "integer", "description": "The height of the bounds ."}
+ "type": {
+ "$ref": "AssistiveWindowType"
+ },
+ "visible": {
+ "type": "boolean",
+ "description": "Sets true to show AssistiveWindow, sets false to hide."
+ },
+ "announceString" : {
+ "optional": true,
+ "type": "string",
+ "description": "Strings for ChromeVox to announce."
+ }
}
},
{
- "id": "CreateWindowOptions",
- "type": "object",
- "description": "The options to create an IME window",
- "platforms": ["win", "linux"],
- "properties": {
- "windowType": {"$ref": "WindowType"},
- "url": {"type": "string", "optional": true},
- "bounds": {"$ref": "Bounds", "optional": true}
- }
+ "id": "AssistiveWindowButton",
+ "type": "string",
+ "description": "ID of buttons in assistive window.",
+ "enum": [
+ "undo",
+ "addToDictionary"
+ ]
}
],
"functions": [
@@ -139,7 +145,7 @@
"name": "setComposition",
"type": "function",
"description": "Set the current composition. If this extension does not own the active IME, this fails.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"name": "parameters",
@@ -195,7 +201,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set.",
+ "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, $(ref:runtime.lastError) is set.",
"parameters": [
{
"name": "success",
@@ -225,7 +231,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set.",
+ "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, $(ref:runtime.lastError) is set.",
"parameters": [
{
"name": "success",
@@ -239,7 +245,7 @@
"name": "commitText",
"type": "function",
"description": "Commits the provided text to the current input.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"name": "parameters",
@@ -259,7 +265,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set.",
+ "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, $(ref:runtime.lastError) is set.",
"parameters": [
{
"name": "success",
@@ -273,7 +279,7 @@
"name": "sendKeyEvents",
"type": "function",
"description": "Sends the key events. This function is expected to be used by virtual keyboards. When key(s) on a virtual keyboard is pressed by a user, this function is used to propagate that event to the system.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"name": "parameters",
@@ -476,6 +482,40 @@
]
},
{
+ "name": "setAssistiveWindowProperties",
+ "type": "function",
+ "description": "Shows/Hides an assistive window with the given properties.",
+ "platforms": ["chromeos"],
+ "parameters": [
+ {
+ "name": "parameters",
+ "type": "object",
+ "properties": {
+ "contextID": {
+ "description": "ID of the context owning the assistive window.",
+ "type": "integer"
+ },
+ "properties": {
+ "$ref": "AssistiveWindowProperties",
+ "description": "Properties of the assistive window."
+ }
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "description": "Called when the operation completes.",
+ "parameters": [
+ {
+ "name": "success",
+ "type": "boolean"
+ }
+ ]
+ }
+ ]
+ },
+ {
"name": "setMenuItems",
"type": "function",
"description": "Adds the provided menu items to the language menu when this IME is active.",
@@ -581,107 +621,11 @@
"name": "keyEventHandled",
"type": "function",
"description": "Indicates that the key event received by onKeyEvent is handled. This should only be called if the onKeyEvent listener is asynchronous.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{"type": "string", "name": "requestId", "description": "Request id of the event that was handled. This should come from keyEvent.requestId"},
{"type": "boolean", "name": "response", "description": "True if the keystroke was handled, false if not"}
]
- },
- {
- "name": "createWindow",
- "type": "function",
- "description": "Creates IME window.",
- "platforms": ["win", "linux"],
- "parameters": [
- {
- "$ref": "CreateWindowOptions",
- "name": "options",
- "description": "The options of the newly created IME window."
- },
- {
- "type": "function",
- "name": "callback",
- "description": "Called when the operation completes.",
- "parameters": [
- {
- "name": "windowObject",
- "type": "object",
- "isInstanceOf": "Window",
- "description": "The JavaScript 'window' object of the newly created IME window. It contains the additional 'id' property for the parameters of the other functions like showWindow/hideWindow."
- }
- ]
- }
- ]
- },
- {
- "name": "showWindow",
- "type": "function",
- "description": "Shows the IME window. This makes the hidden window visible.",
- "platforms": ["win", "linux"],
- "parameters": [
- {
- "type": "integer",
- "name": "windowId",
- "description": "The ID of the IME window."
- },
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called when the operation completes.",
- "parameters": []
- }
- ]
- },
- {
- "name": "hideWindow",
- "type": "function",
- "description": "Hides the IME window. This doesn't close the window. Instead, it makes the window invisible. The extension can cache the window and show/hide it for better performance.",
- "platforms": ["win", "linux"],
- "parameters": [
- {
- "type": "integer",
- "name": "windowId",
- "description": "The ID of the IME window."
- },
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called when the operation completes.",
- "parameters": []
- }
- ]
- },
- {
- "name": "activate",
- "type": "function",
- "description": "Activates the IME extension so that it can receive events.",
- "platforms": ["win", "linux"],
- "parameters": [
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called when the operation completes.",
- "parameters": []
- }
- ]
- },
- {
- "name": "deactivate",
- "type": "function",
- "description": "Deactivates the IME extension so that it cannot receive events.",
- "platforms": ["win", "linux"],
- "parameters": [
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called when the operation completes.",
- "parameters": []
- }
- ]
}
],
"events": [
@@ -689,7 +633,7 @@
"name": "onActivate",
"type": "function",
"description": "This event is sent when an IME is activated. It signals that the IME will be receiving onKeyPress events.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"type": "string",
@@ -707,7 +651,7 @@
"name": "onDeactivated",
"type": "function",
"description": "This event is sent when an IME is deactivated. It signals that the IME will no longer be receiving onKeyPress events.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"type": "string",
@@ -720,7 +664,7 @@
"name": "onFocus",
"type": "function",
"description": "This event is sent when focus enters a text box. It is sent to all extensions that are listening to this event, and enabled by the user.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"$ref": "InputContext",
@@ -733,7 +677,7 @@
"name": "onBlur",
"type": "function",
"description": "This event is sent when focus leaves a text box. It is sent to all extensions that are listening to this event, and enabled by the user.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"type": "integer",
@@ -759,7 +703,7 @@
"name": "onKeyEvent",
"type": "function",
"description": "Fired when a key event is sent from the operating system. The event will be sent to the extension if this extension owns the active IME. The listener function should return true if the event was handled false if it was not. If the event will be evaluated asynchronously, this function must return undefined and the IME must later call keyEventHandled() with the result.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"options": {
"supportsFilters": false,
"supportsListeners": true,
@@ -870,7 +814,7 @@
"name": "onReset",
"type": "function",
"description": "This event is sent when chrome terminates ongoing text input session.",
- "platforms": ["chromeos", "win", "linux"],
+ "platforms": ["chromeos"],
"parameters": [
{
"type": "string",
@@ -880,16 +824,23 @@
]
},
{
- "name": "onCompositionBoundsChanged",
+ "name": "onAssistiveWindowButtonClicked",
"type": "function",
- "description": "Triggered when the bounds of the IME composition text or cursor are changed. The IME composition text is the instance of text produced in the input method editor.",
- "platforms": ["win", "linux"],
+ "description": "This event is sent when a button in an assistive window is clicked.",
"parameters": [
{
- "type": "array",
- "name": "boundsList",
- "description": "List of bounds information for each character on IME composition text. If there's no composition text in the editor, this array contains the bound information of the cursor.",
- "items": { "$ref": "Bounds" }
+ "name": "details",
+ "type": "object",
+ "properties": {
+ "buttonID": {
+ "$ref": "AssistiveWindowButton",
+ "description": "The ID of the button clicked."
+ },
+ "windowType": {
+ "$ref": "AssistiveWindowType",
+ "description": "The type of the assistive window."
+ }
+ }
}
]
}
diff --git a/chromium/chrome/common/extensions/api/input_method_private.json b/chromium/chrome/common/extensions/api/input_method_private.json
index 13e2d37f371..f1d7b9f7e48 100644
--- a/chromium/chrome/common/extensions/api/input_method_private.json
+++ b/chromium/chrome/common/extensions/api/input_method_private.json
@@ -571,7 +571,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, chrome.runtime.lastError is set.",
+ "description": "Called when the operation completes with a boolean indicating if the text was accepted or not. On failure, $(ref:runtime.lastError) is set.",
"parameters": [
{
"name": "success",
@@ -581,6 +581,41 @@
}
]
}, {
+ "name": "setAutocorrectRange",
+ "type": "function",
+ "description": "Set the autocorrect range and autocorrect word. If this extension does not own the active IME, this fails.",
+ "parameters": [
+ {
+ "name": "parameters",
+ "type": "object",
+ "properties": {
+ "contextID": {
+ "description": "ID of the context to autocorrect.",
+ "type": "integer"
+ },
+ "autocorrectString": {
+ "description": "Autocorrect suggestion to display.",
+ "type": "string"
+ },
+ "selectionStart": {
+ "description": "Start of the selection range.",
+ "type": "integer"
+ },
+ "selectionEnd": {
+ "description": "End of the selection range.",
+ "type": "integer"
+ }
+ }
+ },
+ {
+ "type": "function",
+ "name": "callback",
+ "optional": true,
+ "description": "Called when the operation completes. On failure, chrome.runtime.lastError is set.",
+ "parameters": []
+ }
+ ]
+ }, {
"name": "reset",
"type": "function",
"description": "Resets the current engine to its initial state. Fires an OnReset event.",
@@ -728,6 +763,20 @@
"description": "Whether the screen is projected."
}
]
+ }, {
+ "name": "onSuggestionsChanged",
+ "type": "function",
+ "description": "This event is sent when a new set of suggestions has been generated",
+ "parameters": [
+ {
+ "name": "suggestions",
+ "type": "array",
+ "description": "List of suggestions to display, in order of relevance",
+ "items": {
+ "type": "string"
+ }
+ }
+ ]
}
]
}
diff --git a/chromium/chrome/common/extensions/api/login.idl b/chromium/chrome/common/extensions/api/login.idl
index 83ab63eda4a..256ae873fa9 100644
--- a/chromium/chrome/common/extensions/api/login.idl
+++ b/chromium/chrome/common/extensions/api/login.idl
@@ -19,7 +19,7 @@ namespace login {
// |callback|: Note: If the function succeeds, the callback is not
// guaranteed to be called as the extension will be disabled when the
// session starts. Use this callback only to handle the failure case by
- // checking <code>chrome.runtime.lastError</code>.
+ // checking $(ref:runtime.lastError).
static void launchManagedGuestSession(optional DOMString password,
optional VoidCallback callback);
@@ -48,7 +48,7 @@ namespace login {
// |callback|: Note: If the function succeeds, the callback is not
// guaranteed to be called as the extension will be disabled when the
// session starts. Use this callback only to handle the failure case by
- // checking <code>chrome.runtime.lastError</code>.
+ // checking $(ref:runtime.lastError).
static void unlockManagedGuestSession(DOMString password,
optional VoidCallback callback);
};
diff --git a/chromium/chrome/common/extensions/api/passwords_private.idl b/chromium/chrome/common/extensions/api/passwords_private.idl
index 1887a605224..e028805f801 100644
--- a/chromium/chrome/common/extensions/api/passwords_private.idl
+++ b/chromium/chrome/common/extensions/api/passwords_private.idl
@@ -82,6 +82,10 @@ namespace passwordsPrivate {
// An index to refer back to a unique password entry record.
long id;
+ // An index to refer to an entry displayed by the UI. May correspond to
+ // multiple entries in the backend.
+ long frontendId;
+
// If true, the entry came from the Gaia-account-scoped password store
// rather than from the profile-scoped one.
boolean fromAccountStore;
@@ -94,6 +98,10 @@ namespace passwordsPrivate {
// An id to refer back to a unique exception entry record.
long id;
+ // An index to refer to an exception entry displayed by the UI. May
+ // correspond to multiple entries in the backend.
+ long frontendId;
+
// If true, the entry came from the Gaia-account-scoped password store
// rather than from the profile-scoped one.
boolean fromAccountStore;
@@ -206,12 +214,24 @@ namespace passwordsPrivate {
// password entry being removed.
static void removeSavedPassword(long id);
- // Removes the saved password exception corresponding to |exceptionUrl|. If
- // no exception with this URL exists, this function is a no-op.
+ // Removes the saved password corresponding to |ids|. If no saved password
+ // exists for a certain id, that id is ignored. Undoing this operation via
+ // undoRemoveSavedPasswordOrException will restore all the removed passwords
+ // in the batch.
+ static void removeSavedPasswords(long[] ids);
+
+ // Removes the saved password exception corresponding to |id|. If
+ // no exception with this id exists, this function is a no-op.
// |id|: The id for the exception url entry being removed.
static void removePasswordException(long id);
- // Undoes the last removal of a saved password or exception.
+ // Removes the saved password exceptions corresponding to |ids|. If
+ // no exception exists for a certain id, that id is ignored. Undoing this
+ // operation via undoRemoveSavedPasswordOrException will restore all the
+ // removed exceptions in the batch.
+ static void removePasswordExceptions(long[] ids);
+
+ // Undoes the last removal of saved password(s) or exception(s).
static void undoRemoveSavedPasswordOrException();
// Returns the plaintext password corresponding to |id|. Note that on
@@ -232,14 +252,22 @@ namespace passwordsPrivate {
// |callback|: Called with the list of password exceptions.
static void getPasswordExceptionList(ExceptionListCallback callback);
+ // Moves a password currently stored on the device to being stored in the
+ // signed-in, non-syncing Google Account. The result is a no-op if any of
+ // these is true: |id| is invalid; |id| corresponds to a password already
+ // stored in the account; or the user is not using the account-scoped
+ // password storage.
+ // |id|: The id for the password entry being moved.
+ static void movePasswordToAccount(long id);
+
// Triggers the Password Manager password import functionality.
static void importPasswords();
// Triggers the Password Manager password export functionality. Completion
// Will be signaled by the onPasswordsFileExportProgress event.
// |callback| will be called when the request is started or rejected. If
- // rejected <code>chrome.runtime.lastError</code> will be set to
- // 'in-progress' or 'reauth-failed'.
+ // rejected $(ref:runtime.lastError) will be set to
+ // <code>'in-progress'</code> or <code>'reauth-failed'</code>.
static void exportPasswords(VoidCallback callback);
// Requests the export progress status. This is the same as the last value
diff --git a/chromium/chrome/common/extensions/api/platform_keys.idl b/chromium/chrome/common/extensions/api/platform_keys.idl
index b184c7b474e..b0d280faecd 100644
--- a/chromium/chrome/common/extensions/api/platform_keys.idl
+++ b/chromium/chrome/common/extensions/api/platform_keys.idl
@@ -97,7 +97,7 @@ namespace platformKeys {
// $(ref:platformKeys.subtleCrypto).
// |privateKey|: Might be <code>null</code> if this extension does not have
// access to it.
- callback GetKeyPairCallback = void (object publicKey,
+ callback GetKeyPairCallback = void (object publicKey,
optional object privateKey);
callback VerificationCallback = void (VerificationResult result);
@@ -124,16 +124,40 @@ namespace platformKeys {
// accepted as by WebCrypto's <a
// href="http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-importKey">importKey</a>
// function, e.g. <code>RsaHashedImportParams</code> for a RSASSA-PKCS1-v1_5
- // key. For RSASSA-PKCS1-v1_5 keys, additionally the parameters <code>{
- // "hash": { "name": "none" } }</code> are supported. The sign function will
- // then apply PKCS#1 v1.5 padding and but not hash the given data.
- // <p>Currently, this function only supports the "RSASSA-PKCS1-v1_5"
- // algorithm with one of the hashing algorithms "none", "SHA-1", "SHA-256",
- // "SHA-384", and "SHA-512".</p>
+ // key and <code>EcKeyImportParams</code> for EC key.
+ // Additionally for RSASSA-PKCS1-v1_5 keys, hashing algorithm name parameter
+ // can be specified with one of the following values: "none", "SHA-1",
+ // "SHA-256", "SHA-384", or "SHA-512", e.g.
+ // <code>{"hash": { "name": "none" } }</code>. The sign function will then
+ // apply PKCS#1 v1.5 padding but not hash the given data.
+ // <p>Currently, this function only supports the "RSASSA-PKCS1-v1_5" and
+ // "ECDSA" algorithms.</p>
[nocompile] static void getKeyPair(ArrayBuffer certificate,
object parameters,
GetKeyPairCallback callback);
+ // Passes the key pair identified by <code>publicKeySpkiDer</code> for
+ // usage with $(ref:platformKeys.subtleCrypto) to <code>callback</code>.
+ // |publicKeySpkiDer|: A DER-encoded X.509 SubjectPublicKeyInfo, obtained
+ // e.g. by calling WebCrypto's exportKey function with format="spki".
+ // |parameters|: Provides signature and hash algorithm parameters, in
+ // addition to those fixed by the key itself. The same parameters are
+ // accepted as by WebCrypto's <a
+ // href="http://www.w3.org/TR/WebCryptoAPI/#SubtleCrypto-method-importKey">importKey</a>
+ // function, e.g. <code>RsaHashedImportParams</code> for a RSASSA-PKCS1-v1_5
+ // key. For RSASSA-PKCS1-v1_5 keys, we need to also pass a "hash" parameter
+ // <code>{ "hash": { "name": string } }</code>. The "hash" parameter
+ // represents the name of the hashing algorithm to be used in the digest
+ // operation before a sign. It is possible to pass "none" as the hash name,
+ // in which case the sign function will apply PKCS#1 v1.5 padding and but
+ // not hash the given data.
+ // <p>Currently, this function only supports the "RSASSA-PKCS1-v1_5"
+ // algorithm with one of the hashing algorithms "none", "SHA-1", "SHA-256",
+ // "SHA-384", and "SHA-512".</p>
+ [nocompile] static void getKeyPairBySpki(ArrayBuffer publicKeySpkiDer,
+ object parameters,
+ GetKeyPairCallback callback);
+
// An implementation of WebCrypto's
// <a href="http://www.w3.org/TR/WebCryptoAPI/#subtlecrypto-interface">
// SubtleCrypto</a>
diff --git a/chromium/chrome/common/extensions/api/platform_keys_internal.idl b/chromium/chrome/common/extensions/api/platform_keys_internal.idl
index 81784fb683f..3f4ae2fa40a 100644
--- a/chromium/chrome/common/extensions/api/platform_keys_internal.idl
+++ b/chromium/chrome/common/extensions/api/platform_keys_internal.idl
@@ -59,5 +59,16 @@ namespace platformKeysInternal {
static void getPublicKey(ArrayBuffer certificate,
DOMString algorithmName,
GetPublicKeyCallback callback);
+
+ // Takes as arguments a <code>publicKeySpkiDer</code> and
+ // <code>algorithmName</code>. Checks if <code>publicKeySpkiDer</code> is
+ // not empty and if the <code>algorithmName</code> specified is supported.
+ // If so, calls back <code>callback</code> with the key info and a WebCrypto
+ // <code>KeyAlgorithm</code> dictionary describing the key's algorithm. The
+ // <code>name</code> property will equal <code>algorithmName</code>.
+ // Otherwise, calls back with an error.
+ static void getPublicKeyBySpki(ArrayBuffer publicKeySpkiDer,
+ DOMString algorithmName,
+ GetPublicKeyCallback callback);
};
};
diff --git a/chromium/chrome/common/extensions/api/printing_metrics.idl b/chromium/chrome/common/extensions/api/printing_metrics.idl
index b8f09393562..e22b66982cf 100644
--- a/chromium/chrome/common/extensions/api/printing_metrics.idl
+++ b/chromium/chrome/common/extensions/api/printing_metrics.idl
@@ -133,6 +133,9 @@ namespace printingMetrics {
// The number of pages in the document.
long numberOfPages;
+
+ // The status of the printer.
+ printing.PrinterStatus printer_status;
};
callback GetPrintJobsCallback = void(PrintJobInfo[] jobs);
diff --git a/chromium/chrome/common/extensions/api/settings_private.idl b/chromium/chrome/common/extensions/api/settings_private.idl
index b4a1848df5a..1d9a244262e 100644
--- a/chromium/chrome/common/extensions/api/settings_private.idl
+++ b/chromium/chrome/common/extensions/api/settings_private.idl
@@ -60,6 +60,17 @@ namespace settingsPrivate {
// The recommended value if enforcement == RECOMMENDED.
any? recommendedValue;
+ // If enforcement == ENFORCED this optionally specifies preference values
+ // that are still available for selection by the user. If set, must contain
+ // at least 2 distinct values, as must contain |value| and
+ // |recommendedValue| (if present).
+ any[]? userSelectableValues;
+
+ // If true, user control of the preference is disabled for reasons unrelated
+ // to controlledBy (e.g. no signed-in profile is present). A false value is
+ // a no-op.
+ boolean? userControlDisabled;
+
// The extension ID if controlledBy == EXTENSION.
DOMString? extensionId;
diff --git a/chromium/chrome/common/extensions/api/tab_capture.idl b/chromium/chrome/common/extensions/api/tab_capture.idl
index 5dd0e6c25d2..d0210c064b1 100644
--- a/chromium/chrome/common/extensions/api/tab_capture.idl
+++ b/chromium/chrome/common/extensions/api/tab_capture.idl
@@ -89,7 +89,7 @@ namespace tabCapture {
// |options| : Configures the returned media stream.
// |callback| : Callback with either the tab capture MediaStream or
// <code>null</code>. <code>null</code> indicates an error has occurred
- // and the client may query chrome.runtime.lastError to access the error
+ // and the client may query $(ref:runtime.lastError) to access the error
// details.
static void capture(CaptureOptions options,
GetTabMediaCallback callback);
@@ -126,7 +126,7 @@ namespace tabCapture {
// |options| : Constraints for the capture and returned MediaStream.
// |callback| : Callback with either the tab capture MediaStream or
// <code>null</code>. <code>null</code> indicates an error has occurred
- // and the client may query chrome.runtime.lastError to access the error
+ // and the client may query $(ref:runtime.lastError) to access the error
// details.
static void captureOffscreenTab(DOMString startUrl,
CaptureOptions options,
diff --git a/chromium/chrome/common/extensions/api/tts.json b/chromium/chrome/common/extensions/api/tts.json
index e639a304892..5b43290bdd3 100644
--- a/chromium/chrome/common/extensions/api/tts.json
+++ b/chromium/chrome/common/extensions/api/tts.json
@@ -195,7 +195,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called right away, before speech finishes. Check chrome.runtime.lastError to make sure there were no errors. Use options.onEvent to get more detailed feedback.",
+ "description": "Called right away, before speech finishes. Check $(ref:runtime.lastError) to make sure there were no errors. Use options.onEvent to get more detailed feedback.",
"parameters": []
}
]
diff --git a/chromium/chrome/common/extensions/api/webstore_private.json b/chromium/chrome/common/extensions/api/webstore_private.json
index 94b82e4da12..f1418484d41 100644
--- a/chromium/chrome/common/extensions/api/webstore_private.json
+++ b/chromium/chrome/common/extensions/api/webstore_private.json
@@ -396,6 +396,11 @@
"name": "id",
"type": "string",
"description": "The id of the extension"
+ }, {
+ "name": "manifest",
+ "type": "string",
+ "optional": true,
+ "description": "The manifest of the extension"
},
{
"name": "callback",
diff --git a/chromium/chrome/common/extensions/api/webview_tag.json b/chromium/chrome/common/extensions/api/webview_tag.json
index cf62c9d6eee..dcfebced2c3 100644
--- a/chromium/chrome/common/extensions/api/webview_tag.json
+++ b/chromium/chrome/common/extensions/api/webview_tag.json
@@ -288,7 +288,7 @@
{
"name": "create",
"type": "function",
- "description": "Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in <code>chrome.runtime.lastError</code>).",
+ "description": "Creates a new context menu item. Note that if an error occurs during creation, you may not find out until the creation callback fires (the details will be in $(ref:runtime.lastError)).",
"returns": {
"choices": [
{ "type": "integer" },
@@ -307,7 +307,7 @@
"type": "function",
"name": "callback",
"optional": true,
- "description": "Called when the item has been created in the browser. If there were any problems creating the item, details will be available in <code>chrome.runtime.lastError</code>.",
+ "description": "Called when the item has been created in the browser. If there were any problems creating the item, details will be available in $(ref:runtime.lastError).",
"parameters": []
}
]
diff --git a/chromium/chrome/common/extensions/extension_constants.cc b/chromium/chrome/common/extensions/extension_constants.cc
index 1cbfd911811..7cbe3d42723 100644
--- a/chromium/chrome/common/extensions/extension_constants.cc
+++ b/chromium/chrome/common/extensions/extension_constants.cc
@@ -71,7 +71,7 @@ const char* const kBuiltInFirstPartyExtensionIds[] = {
kMediaRouterStableExtensionId,
#if defined(OS_CHROMEOS)
kAssessmentAssistantExtensionId,
- kAutoclickExtensionId,
+ kAccessibilityCommonExtensionId,
kSelectToSpeakExtensionId,
kSwitchAccessExtensionId,
kFilesManagerAppId,
@@ -87,8 +87,13 @@ const char* const kBuiltInFirstPartyExtensionIds[] = {
#if defined(OS_CHROMEOS)
const char kAssessmentAssistantExtensionId[] =
"gndmhdcefbhlchkhipcnnbkcmicncehk";
-const char kAutoclickExtensionId[] = "egfdjlfmgnehecnclamagfafdccgfndp";
-const char kAutoclickExtensionPath[] = "chromeos/accessibility/autoclick";
+const char kAccessibilityCommonExtensionId[] =
+ "egfdjlfmgnehecnclamagfafdccgfndp";
+const char kAccessibilityCommonExtensionPath[] = "chromeos/accessibility";
+const char kAccessibilityCommonManifestFilename[] =
+ "accessibility_common_manifest.json";
+const char kAccessibilityCommonGuestManifestFilename[] =
+ "accessibility_common_manifest_guest.json";
const char kChromeVoxExtensionPath[] = "chromeos/accessibility";
const char kChromeVoxManifestFilename[] = "chromevox_manifest.json";
const char kChromeVoxGuestManifestFilename[] = "chromevox_manifest_guest.json";
diff --git a/chromium/chrome/common/extensions/extension_constants.h b/chromium/chrome/common/extensions/extension_constants.h
index 9d0940a4691..1858e695dd5 100644
--- a/chromium/chrome/common/extensions/extension_constants.h
+++ b/chromium/chrome/common/extensions/extension_constants.h
@@ -188,11 +188,15 @@ enum AppLaunchBucket {
#if defined(OS_CHROMEOS)
// The extension id of the Assessment Assistant extension.
extern const char kAssessmentAssistantExtensionId[];
-// The extension id of the Automatic Clicks extension.
-extern const char kAutoclickExtensionId[];
-// Path to preinstalled Automatic Clicks extension (relative to
+// The extension id of the Accessibility Common extension.
+extern const char kAccessibilityCommonExtensionId[];
+// Path to preinstalled Accessibility Common extension (relative to
// |chrome::DIR_RESOURCES|).
-extern const char kAutoclickExtensionPath[];
+extern const char kAccessibilityCommonExtensionPath[];
+// The manifest filename of the Accessibility Common extension.
+extern const char kAccessibilityCommonManifestFilename[];
+// The guest manifest filename of the Accessibility Common extension.
+extern const char kAccessibilityCommonGuestManifestFilename[];
// Path to preinstalled ChromeVox screen reader extension (relative to
// |chrome::DIR_RESOURCES|).
extern const char kChromeVoxExtensionPath[];
diff --git a/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.cc b/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.cc
index 79a6f4e5148..effeaec82b0 100644
--- a/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.cc
+++ b/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.cc
@@ -24,19 +24,17 @@ static base::LazyInstance<LinkedAppIcons>::DestructorAtExit
} // namespace
-LinkedAppIcons::IconInfo::IconInfo() {
-}
+constexpr int LinkedAppIcons::kAnySize;
-LinkedAppIcons::IconInfo::~IconInfo() {
-}
+LinkedAppIcons::IconInfo::IconInfo() = default;
-LinkedAppIcons::LinkedAppIcons() {
-}
+LinkedAppIcons::IconInfo::~IconInfo() = default;
+
+LinkedAppIcons::LinkedAppIcons() = default;
LinkedAppIcons::LinkedAppIcons(const LinkedAppIcons& other) = default;
-LinkedAppIcons::~LinkedAppIcons() {
-}
+LinkedAppIcons::~LinkedAppIcons() = default;
// static
const LinkedAppIcons& LinkedAppIcons::GetLinkedAppIcons(
diff --git a/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.h b/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.h
index 32845384e44..82f06970332 100644
--- a/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.h
+++ b/chromium/chrome/common/extensions/manifest_handlers/linked_app_icons.h
@@ -15,6 +15,8 @@ namespace extensions {
// A structure to hold the parsed linked app icon data.
struct LinkedAppIcons : public Extension::ManifestData {
+ static constexpr int kAnySize = 0;
+
struct IconInfo {
IconInfo();
~IconInfo();
diff --git a/chromium/chrome/common/extensions/permissions/chrome_api_permissions.cc b/chromium/chrome/common/extensions/permissions/chrome_api_permissions.cc
index c6a72f2ce8e..ec06f67d656 100644
--- a/chromium/chrome/common/extensions/permissions/chrome_api_permissions.cc
+++ b/chromium/chrome/common/extensions/permissions/chrome_api_permissions.cc
@@ -77,6 +77,9 @@ constexpr APIPermissionInfo::InitInfo permissions_to_register[] = {
APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning},
{APIPermission::kEnterpriseHardwarePlatform, "enterprise.hardwarePlatform",
APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning},
+ {APIPermission::kEnterpriseNetworkingAttributes,
+ "enterprise.networkingAttributes",
+ APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning},
{APIPermission::kEnterprisePlatformKeys, "enterprise.platformKeys",
APIPermissionInfo::kFlagDoesNotRequireManagedSessionFullLoginWarning},
{APIPermission::kFileBrowserHandler, "fileBrowserHandler",
diff --git a/chromium/chrome/common/extensions/permissions/chrome_permission_message_rules.cc b/chromium/chrome/common/extensions/permissions/chrome_permission_message_rules.cc
index 26bf88f800f..8385bc2f259 100644
--- a/chromium/chrome/common/extensions/permissions/chrome_permission_message_rules.cc
+++ b/chromium/chrome/common/extensions/permissions/chrome_permission_message_rules.cc
@@ -670,6 +670,15 @@ ChromePermissionMessageRule::GetAllRules() {
{IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_HARDWARE_PLATFORM,
{APIPermission::kEnterpriseHardwarePlatform},
{}},
+ {IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_DEVICE_ATTRIBUTES,
+ {APIPermission::kEnterpriseDeviceAttributes},
+ {}},
+ {IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_NETWORKING_ATTRIBUTES,
+ {APIPermission::kEnterpriseNetworkingAttributes},
+ {}},
+ {IDS_EXTENSION_PROMPT_WARNING_ENTERPRISE_PLATFORMKEYS,
+ {APIPermission::kEnterprisePlatformKeys},
+ {}},
{IDS_EXTENSION_PROMPT_WARNING_LOGIN, {APIPermission::kLogin}, {}},
{IDS_EXTENSION_PROMPT_WARNING_LOGIN_SCREEN_UI,
{APIPermission::kLoginScreenUi},
diff --git a/chromium/chrome/common/extensions/permissions/permission_set_unittest.cc b/chromium/chrome/common/extensions/permissions/permission_set_unittest.cc
index 55ff95f2e81..1284ab87161 100644
--- a/chromium/chrome/common/extensions/permissions/permission_set_unittest.cc
+++ b/chromium/chrome/common/extensions/permissions/permission_set_unittest.cc
@@ -781,11 +781,6 @@ TEST(PermissionsTest, PermissionMessages) {
skip.insert(APIPermission::kWebView);
skip.insert(APIPermission::kWindowShape);
- // These permissions are restricted to extensions force-installed by policy
- // and don't require a prompt, i.e. they're restricted to location 'policy'.
- skip.insert(APIPermission::kEnterprisePlatformKeys);
- skip.insert(APIPermission::kEnterpriseDeviceAttributes);
-
// TODO(erikkay) add a string for this permission.
skip.insert(APIPermission::kBackground);
diff --git a/chromium/chrome/common/features.gni b/chromium/chrome/common/features.gni
index 98afaf334de..91d3c7c34e7 100644
--- a/chromium/chrome/common/features.gni
+++ b/chromium/chrome/common/features.gni
@@ -51,9 +51,6 @@ declare_args() {
enable_one_click_signin =
is_win || is_mac || (is_linux && !is_chromeos && !is_chromecast)
- # Enables password change in leaked password dialog, disabled by default.
- enable_password_change_in_leaked_dialog = false
-
enable_service_discovery = (enable_mdns && !is_android) || is_mac
# Enables use of the session service, which is enabled by default.
diff --git a/chromium/chrome/common/google_url_loader_throttle.cc b/chromium/chrome/common/google_url_loader_throttle.cc
index 5af3086ef4d..c1870b0f56e 100644
--- a/chromium/chrome/common/google_url_loader_throttle.cc
+++ b/chromium/chrome/common/google_url_loader_throttle.cc
@@ -4,9 +4,13 @@
#include "chrome/common/google_url_loader_throttle.h"
+#include "base/feature_list.h"
+#include "base/metrics/histogram_functions.h"
#include "build/build_config.h"
+#include "chrome/common/chrome_features.h"
#include "chrome/common/net/safe_search_util.h"
#include "components/google/core/common/google_util.h"
+#include "net/base/url_util.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
@@ -26,6 +30,8 @@ void GoogleURLLoaderThrottle::UpdateCorsExemptHeader(
network::mojom::NetworkContextParams* params) {
params->cors_exempt_header_list.push_back(
safe_search_util::kGoogleAppsAllowedDomains);
+ params->cors_exempt_header_list.push_back(
+ safe_search_util::kYouTubeRestrictHeaderName);
#if defined(OS_ANDROID)
params->cors_exempt_header_list.push_back(kCCTClientDataHeader);
#endif
@@ -34,11 +40,13 @@ void GoogleURLLoaderThrottle::UpdateCorsExemptHeader(
GoogleURLLoaderThrottle::GoogleURLLoaderThrottle(
#if defined(OS_ANDROID)
const std::string& client_data_header,
+ bool night_mode_enabled,
#endif
chrome::mojom::DynamicParams dynamic_params)
:
#if defined(OS_ANDROID)
client_data_header_(client_data_header),
+ night_mode_enabled_(night_mode_enabled),
#endif
dynamic_params_(std::move(dynamic_params)) {
}
@@ -64,7 +72,7 @@ void GoogleURLLoaderThrottle::WillStartRequest(
dynamic_params_.youtube_restrict <
safe_search_util::YOUTUBE_RESTRICT_COUNT) {
safe_search_util::ForceYouTubeRestrict(
- request->url, &request->headers,
+ request->url, &request->cors_exempt_headers,
static_cast<safe_search_util::YouTubeRestrictMode>(
dynamic_params_.youtube_restrict));
}
@@ -82,6 +90,20 @@ void GoogleURLLoaderThrottle::WillStartRequest(
request->cors_exempt_headers.SetHeader(kCCTClientDataHeader,
client_data_header_);
}
+
+ bool is_google_homepage_or_search =
+ google_util::IsGoogleHomePageUrl(request->url) ||
+ google_util::IsGoogleSearchUrl(request->url);
+ if (is_google_homepage_or_search) {
+ // TODO (crbug.com/1081510): Remove this experimental code once a final
+ // solution is agreed upon.
+ if (base::FeatureList::IsEnabled(features::kAndroidDarkSearch)) {
+ request->url = net::AppendOrReplaceQueryParameter(
+ request->url, "cs", night_mode_enabled_ ? "1" : "0");
+ }
+ base::UmaHistogramBoolean("Android.DarkTheme.DarkSearchRequested",
+ night_mode_enabled_);
+ }
#endif
}
@@ -105,7 +127,7 @@ void GoogleURLLoaderThrottle::WillRedirectRequest(
dynamic_params_.youtube_restrict <
safe_search_util::YOUTUBE_RESTRICT_COUNT) {
safe_search_util::ForceYouTubeRestrict(
- redirect_info->new_url, modified_headers,
+ redirect_info->new_url, modified_cors_exempt_headers,
static_cast<safe_search_util::YouTubeRestrictMode>(
dynamic_params_.youtube_restrict));
}
diff --git a/chromium/chrome/common/google_url_loader_throttle.h b/chromium/chrome/common/google_url_loader_throttle.h
index 3740358d83c..571d5f866b0 100644
--- a/chromium/chrome/common/google_url_loader_throttle.h
+++ b/chromium/chrome/common/google_url_loader_throttle.h
@@ -20,6 +20,7 @@ class GoogleURLLoaderThrottle
public:
#if defined(OS_ANDROID)
GoogleURLLoaderThrottle(const std::string& client_data_header,
+ bool night_mode_enabled,
chrome::mojom::DynamicParams dynamic_params);
#else
explicit GoogleURLLoaderThrottle(chrome::mojom::DynamicParams dynamic_params);
@@ -30,7 +31,6 @@ class GoogleURLLoaderThrottle
static void UpdateCorsExemptHeader(
network::mojom::NetworkContextParams* params);
- private:
// blink::URLLoaderThrottle:
void DetachFromCurrentSequence() override;
void WillStartRequest(network::ResourceRequest* request,
@@ -48,8 +48,10 @@ class GoogleURLLoaderThrottle
bool* defer) override;
#endif
+ private:
#if defined(OS_ANDROID)
std::string client_data_header_;
+ bool night_mode_enabled_;
#endif
const chrome::mojom::DynamicParams dynamic_params_;
};
diff --git a/chromium/chrome/common/google_url_loader_throttle_unittest.cc b/chromium/chrome/common/google_url_loader_throttle_unittest.cc
new file mode 100644
index 00000000000..a8d36b1e4ee
--- /dev/null
+++ b/chromium/chrome/common/google_url_loader_throttle_unittest.cc
@@ -0,0 +1,75 @@
+// Copyright 2020 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.
+
+#include "chrome/common/google_url_loader_throttle.h"
+
+#include "base/test/scoped_feature_list.h"
+#include "build/build_config.h"
+#include "chrome/common/chrome_features.h"
+#include "chrome/common/renderer_configuration.mojom.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+class GoogleURLLoaderThrottleTest : public testing::Test {
+ public:
+ GoogleURLLoaderThrottleTest() {
+ scoped_feature_list_.InitWithFeatureList(
+ std::make_unique<base::FeatureList>());
+ }
+
+ ~GoogleURLLoaderThrottleTest() override = default;
+
+ base::test::ScopedFeatureList& scoped_feature_list() {
+ return scoped_feature_list_;
+ }
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+};
+
+#if defined(OS_ANDROID)
+TEST_F(GoogleURLLoaderThrottleTest, DarkSearchGoogleHomepage) {
+ scoped_feature_list().Reset();
+ scoped_feature_list().InitAndEnableFeature(features::kAndroidDarkSearch);
+ GoogleURLLoaderThrottle throttle(/* client_header= */ "",
+ /* night_mode_enabled= */ true,
+ chrome::mojom::DynamicParams());
+
+ network::ResourceRequest request;
+ request.url = GURL("https://www.google.com");
+ bool defer = false;
+
+ throttle.WillStartRequest(&request, &defer);
+ EXPECT_NE(std::string::npos, request.url.spec().find("cs=1"));
+}
+
+TEST_F(GoogleURLLoaderThrottleTest, DarkSearchGoogleSearch) {
+ scoped_feature_list().Reset();
+ scoped_feature_list().InitAndEnableFeature(features::kAndroidDarkSearch);
+ GoogleURLLoaderThrottle throttle(/* client_header= */ "",
+ /* night_mode_enabled= */ true,
+ chrome::mojom::DynamicParams());
+
+ network::ResourceRequest request;
+ request.url = GURL("https://www.google.com/search?q=test");
+ bool defer = false;
+
+ throttle.WillStartRequest(&request, &defer);
+ EXPECT_NE(std::string::npos, request.url.spec().find("cs=1"));
+}
+
+TEST_F(GoogleURLLoaderThrottleTest, DarkSearchGoogleSource) {
+ scoped_feature_list().Reset();
+ scoped_feature_list().InitAndEnableFeature(features::kAndroidDarkSearch);
+ GoogleURLLoaderThrottle throttle(/* client_header= */ "",
+ /* night_mode_enabled= */ true,
+ chrome::mojom::DynamicParams());
+
+ network::ResourceRequest request;
+ request.url = GURL("https://code.google.com/");
+ bool defer = false;
+
+ throttle.WillStartRequest(&request, &defer);
+ EXPECT_EQ(std::string::npos, request.url.spec().find("cs=1"));
+}
+#endif
diff --git a/chromium/chrome/common/mac/app_shim.mojom b/chromium/chrome/common/mac/app_shim.mojom
index b270a155198..ac3822c1798 100644
--- a/chromium/chrome/common/mac/app_shim.mojom
+++ b/chromium/chrome/common/mac/app_shim.mojom
@@ -89,6 +89,10 @@ interface AppShimHost {
// clicking on the app's icon in the dock or by selecting it with Cmd+Tab.
FocusApp();
+ // Sent when the application should launch if needed (e.g, when the dock
+ // icon is clicked).
+ ReopenApp();
+
// Sent when files are opened by the app (e.g, by opening in Finder, or by
// dragging on to the app in the dock).
FilesOpened(array<mojo_base.mojom.FilePath> files);
diff --git a/chromium/chrome/common/media/cdm_host_file_path.cc b/chromium/chrome/common/media/cdm_host_file_path.cc
index e1dffd5a466..2adbad725bd 100644
--- a/chromium/chrome/common/media/cdm_host_file_path.cc
+++ b/chromium/chrome/common/media/cdm_host_file_path.cc
@@ -6,7 +6,9 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
+#include "base/check.h"
#include "base/logging.h"
+#include "base/notreached.h"
#include "base/path_service.h"
#include "base/stl_util.h"
#include "build/branding_buildflags.h"
diff --git a/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux.cc b/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux.cc
index 0fdfc56c725..44a89a2e7f6 100644
--- a/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux.cc
+++ b/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux.cc
@@ -7,10 +7,12 @@
#include <memory>
#include <string>
+#include "base/check.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/important_file_writer.h"
#include "base/json/json_string_value_serializer.h"
+#include "base/logging.h"
#include "base/path_service.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
diff --git a/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux_unittest.cc b/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux_unittest.cc
index 125bf50d21a..62508021b0e 100644
--- a/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux_unittest.cc
+++ b/chromium/chrome/common/media/component_widevine_cdm_hint_file_linux_unittest.cc
@@ -7,6 +7,7 @@
#include <stdint.h>
#include <stdlib.h>
+#include "base/check.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/important_file_writer.h"
diff --git a/chromium/chrome/common/media_router/discovery/media_sink_internal.cc b/chromium/chrome/common/media_router/discovery/media_sink_internal.cc
index e39d0ebddbb..2c5c8ed5bc5 100644
--- a/chromium/chrome/common/media_router/discovery/media_sink_internal.cc
+++ b/chromium/chrome/common/media_router/discovery/media_sink_internal.cc
@@ -7,6 +7,7 @@
#include <new>
#include "base/logging.h"
+#include "base/notreached.h"
#include "base/strings/string_util.h"
namespace media_router {
diff --git a/chromium/chrome/common/media_router/discovery/media_sink_service_base.cc b/chromium/chrome/common/media_router/discovery/media_sink_service_base.cc
index a5a34a53330..e7eba6f2bb5 100644
--- a/chromium/chrome/common/media_router/discovery/media_sink_service_base.cc
+++ b/chromium/chrome/common/media_router/discovery/media_sink_service_base.cc
@@ -4,6 +4,7 @@
#include "chrome/common/media_router/discovery/media_sink_service_base.h"
#include "base/bind.h"
+#include "base/logging.h"
#include "chrome/common/media_router/media_route.h"
#include <vector>
diff --git a/chromium/chrome/common/media_router/issue.h b/chromium/chrome/common/media_router/issue.h
index 8b790b6cf72..840c3747645 100644
--- a/chromium/chrome/common/media_router/issue.h
+++ b/chromium/chrome/common/media_router/issue.h
@@ -8,7 +8,6 @@
#include <string>
#include <vector>
-#include "base/logging.h"
#include "chrome/common/media_router/media_route.h"
#include "chrome/common/media_router/media_sink.h"
diff --git a/chromium/chrome/common/media_router/media_route.cc b/chromium/chrome/common/media_router/media_route.cc
index eac0e63063e..82ba6ac02c2 100644
--- a/chromium/chrome/common/media_router/media_route.cc
+++ b/chromium/chrome/common/media_router/media_route.cc
@@ -33,9 +33,7 @@ MediaRoute::MediaRoute(const MediaRoute::Id& media_route_id,
media_sink_id_(media_sink_id),
description_(description),
is_local_(is_local),
- for_display_(for_display),
- is_incognito_(false),
- is_local_presentation_(false) {}
+ for_display_(for_display) {}
MediaRoute::MediaRoute(const MediaRoute& other) = default;
@@ -51,7 +49,7 @@ bool MediaRoute::operator==(const MediaRoute& other) const {
description_ == other.description_ && is_local_ == other.is_local_ &&
controller_type_ == other.controller_type_ &&
for_display_ == other.for_display_ &&
- is_incognito_ == other.is_incognito_ &&
+ is_off_the_record_ == other.is_off_the_record_ &&
is_local_presentation_ == other.is_local_presentation_;
}
diff --git a/chromium/chrome/common/media_router/media_route.h b/chromium/chrome/common/media_router/media_route.h
index 1d8f946885f..16e19e7485c 100644
--- a/chromium/chrome/common/media_router/media_route.h
+++ b/chromium/chrome/common/media_router/media_route.h
@@ -8,7 +8,6 @@
#include <iosfwd>
#include <string>
-#include "base/logging.h"
#include "base/values.h"
#include "chrome/common/media_router/media_sink.h"
#include "chrome/common/media_router/media_source.h"
@@ -96,8 +95,10 @@ class MediaRoute {
void set_for_display(bool for_display) { for_display_ = for_display; }
bool for_display() const { return for_display_; }
- void set_incognito(bool is_incognito) { is_incognito_ = is_incognito; }
- bool is_incognito() const { return is_incognito_; }
+ void set_off_the_record(bool is_off_the_record) {
+ is_off_the_record_ = is_off_the_record;
+ }
+ bool is_off_the_record() const { return is_off_the_record_; }
void set_local_presentation(bool is_local_presentation) {
is_local_presentation_ = is_local_presentation;
@@ -139,8 +140,8 @@ class MediaRoute {
// |true| if the route can be displayed in the UI.
bool for_display_ = false;
- // |true| if the route was created by an incognito profile.
- bool is_incognito_ = false;
+ // |true| if the route was created by an OffTheRecord profile.
+ bool is_off_the_record_ = false;
// |true| if the presentation associated with this route is a local
// presentation.
diff --git a/chromium/chrome/common/media_router/media_route_unittest.cc b/chromium/chrome/common/media_router/media_route_unittest.cc
index 01a94be6b1e..86a3ca8c758 100644
--- a/chromium/chrome/common/media_router/media_route_unittest.cc
+++ b/chromium/chrome/common/media_router/media_route_unittest.cc
@@ -47,10 +47,10 @@ TEST(MediaRouteTest, TestEquals) {
false);
EXPECT_FALSE(route1 == route5);
- // Same as route1 with different incognito.
+ // Same as route1 with different off_the_record.
MediaRoute route6(kRouteId1, media_source, "sinkId", "Description", true,
false);
- route6.set_incognito(true);
+ route6.set_off_the_record(true);
EXPECT_FALSE(route1 == route6);
}
diff --git a/chromium/chrome/common/media_router/media_source.cc b/chromium/chrome/common/media_router/media_source.cc
index 05a71cabcbd..1f7dd3f4d2c 100644
--- a/chromium/chrome/common/media_router/media_source.cc
+++ b/chromium/chrome/common/media_router/media_source.cc
@@ -21,13 +21,12 @@ namespace {
// Prefixes used to format and detect various protocols' media source URNs.
// See: https://www.ietf.org/rfc/rfc3406.txt
+constexpr char kAnyTabMediaUrn[] = "urn:x-org.chromium.media:source:tab:*";
constexpr char kTabMediaUrnFormat[] = "urn:x-org.chromium.media:source:tab:%d";
constexpr base::StringPiece kDesktopMediaUrnPrefix =
"urn:x-org.chromium.media:source:desktop:";
constexpr base::StringPiece kUnknownDesktopMediaUrn =
"urn:x-org.chromium.media:source:desktop";
-constexpr char kTabRemotingUrnFormat[] =
- "urn:x-org.chromium.media:source:tab_content_remoting:%d";
// List of non-http(s) schemes that are allowed in a Presentation URL.
constexpr std::array<const char* const, 5> kAllowedSchemes{
@@ -70,17 +69,37 @@ MediaSource::MediaSource(const GURL& presentation_url)
MediaSource::~MediaSource() = default;
// static
-MediaSource MediaSource::ForTab(int tab_id) {
- return MediaSource(base::StringPrintf(kTabMediaUrnFormat, tab_id));
+MediaSource MediaSource::ForLocalFile() {
+ // TODO(crbug.com/1090878): Use something more sane here. Fixing this
+ // requires tracking down other places where tab ID 0 is used to indicate
+ // local file casting.
+ //
+ // This probably isn't a source of bugs in practice, because tab IDs are
+ // generated by SessionIdGenerator, which appears to only produce positive
+ // values, but that fact isn't clearly documentated, and other parts of
+ // Chromium don't seem to rely on it, using -1 as the canonical invalid tab
+ // ID.
+ return MediaSource(base::StringPrintf(kTabMediaUrnFormat, 0));
}
// static
-MediaSource MediaSource::ForTabContentRemoting(int tab_id) {
- return MediaSource(base::StringPrintf(kTabRemotingUrnFormat, tab_id));
+MediaSource MediaSource::ForAnyTab() {
+ return MediaSource(std::string(kAnyTabMediaUrn));
+}
+
+// static
+MediaSource MediaSource::ForTab(int tab_id) {
+ // Ideally we shouldn't allow -1 as a tab ID, but in unit tests, a tab ID of
+ // -1 can show up when this function is called from
+ // CastHandler::StartObservingForSinks() because SessionTabHelper::IdForTab
+ // can return -1.
+ DCHECK_GE(tab_id, -1);
+ return MediaSource(base::StringPrintf(kTabMediaUrnFormat, tab_id));
}
// static
MediaSource MediaSource::ForDesktop(const std::string& desktop_media_id) {
+ DCHECK(!desktop_media_id.empty());
return MediaSource(kDesktopMediaUrnPrefix.as_string() + desktop_media_id);
}
@@ -94,20 +113,19 @@ MediaSource MediaSource::ForPresentationUrl(const GURL& presentation_url) {
return MediaSource(presentation_url);
}
+bool MediaSource::IsTabMirroringSource() const {
+ return id() == kAnyTabMediaUrn || TabId() > 0;
+}
+
bool MediaSource::IsDesktopMirroringSource() const {
return id() == kUnknownDesktopMediaUrn ||
base::StartsWith(id(), kDesktopMediaUrnPrefix,
base::CompareCase::SENSITIVE);
}
-bool MediaSource::IsTabMirroringSource() const {
- int tab_id;
- return std::sscanf(id_.c_str(), kTabMediaUrnFormat, &tab_id) == 1 &&
- tab_id > 0;
-}
-
-bool MediaSource::IsMirroringSource() const {
- return IsDesktopMirroringSource() || IsTabMirroringSource();
+bool MediaSource::IsLocalFileSource() const {
+ // TODO(crbug.com/1090878): Keep this method is sync with ForLocalFile().
+ return TabId() == 0;
}
bool MediaSource::IsCastPresentationUrl() const {
@@ -116,13 +134,9 @@ bool MediaSource::IsCastPresentationUrl() const {
}
int MediaSource::TabId() const {
- int tab_id;
- if (sscanf(id_.c_str(), kTabMediaUrnFormat, &tab_id) == 1)
- return tab_id;
- else if (sscanf(id_.c_str(), kTabRemotingUrnFormat, &tab_id) == 1)
- return tab_id;
- else
- return -1;
+ int tab_id = -1;
+ sscanf(id_.c_str(), kTabMediaUrnFormat, &tab_id);
+ return tab_id;
}
base::Optional<std::string> MediaSource::DesktopStreamId() const {
@@ -133,11 +147,6 @@ base::Optional<std::string> MediaSource::DesktopStreamId() const {
return base::nullopt;
}
-bool MediaSource::IsValid() const {
- return TabId() > 0 || IsDesktopMirroringSource() ||
- IsValidPresentationUrl(GURL(id_));
-}
-
bool MediaSource::IsDialSource() const {
return url_.SchemeIs(kCastDialPresentationUrlScheme);
}
@@ -146,4 +155,16 @@ std::string MediaSource::AppNameFromDialSource() const {
return IsDialSource() ? url_.path() : "";
}
+std::string MediaSource::TruncateForLogging(size_t max_length) const {
+ const std::string origin = url_.GetOrigin().spec();
+ if (!origin.empty())
+ return origin.substr(0, max_length);
+ // TODO(takumif): Keep the query string by redacting PII. The query string may
+ // contain info useful for debugging such as the required capabilities.
+ const size_t query_start_index = id_.find("?");
+ const size_t length =
+ query_start_index == std::string::npos ? max_length : query_start_index;
+ return id_.substr(0, length);
+}
+
} // namespace media_router
diff --git a/chromium/chrome/common/media_router/media_source.h b/chromium/chrome/common/media_router/media_source.h
index edf2111d694..6fdbea9350d 100644
--- a/chromium/chrome/common/media_router/media_source.h
+++ b/chromium/chrome/common/media_router/media_source.h
@@ -90,8 +90,9 @@ class MediaSource {
// Protocol-specific media source object creation.
// Returns MediaSource URI depending on the type of source.
+ static MediaSource ForLocalFile();
+ static MediaSource ForAnyTab();
static MediaSource ForTab(int tab_id);
- static MediaSource ForTabContentRemoting(int tab_id);
static MediaSource ForPresentationUrl(const GURL& presentation_url);
// Creates a media source for a specific desktop.
@@ -108,16 +109,23 @@ class MediaSource {
// extension-based Cast MRP is removed.
static MediaSource ForDesktop();
- // Returns true if source outputs its content via mirroring.
- bool IsDesktopMirroringSource() const;
+ // Returns true if source outputs its content via tab mirroring and isn't a
+ // local file.
bool IsTabMirroringSource() const;
- bool IsMirroringSource() const;
+
+ // Returns true if source outputs its content via desktop mirroring.
+ bool IsDesktopMirroringSource() const;
+
+ // Returns true if the source is a local file.
+ bool IsLocalFileSource() const;
// Returns true if this is represents a Cast Presentation URL.
bool IsCastPresentationUrl() const;
// Parses the ID and returns the SessionTabHelper tab ID referencing a source
- // tab. Returns a non-positive value on error.
+ // tab. Don't rely on this method returning something useful without first
+ // calling IsTabMirroringSource(); it will return 0 for for ForLocalFile()
+ // source and -1 for non-tab sources or the ForAnyTab() source.
int TabId() const;
// When this source was created by ForDesktop(string), returns a stream ID
@@ -126,10 +134,6 @@ class MediaSource {
// returns base::nullopt.
base::Optional<std::string> DesktopStreamId() const;
- // Checks that this is a parseable URN and is of a known type.
- // Does not deeper protocol-level syntax checks.
- bool IsValid() const;
-
// Returns true this source outputs its content via DIAL.
// TODO(crbug.com/804419): Move this to in-browser DIAL/Cast MRP when we have
// one.
@@ -139,6 +143,9 @@ class MediaSource {
// valid DIAL media source.
std::string AppNameFromDialSource() const;
+ // Returns a shortened copy of the media source ID suitable for logging.
+ std::string TruncateForLogging(size_t max_length) const;
+
private:
MediaSource::Id id_;
GURL url_;
diff --git a/chromium/chrome/common/media_router/media_source_unittest.cc b/chromium/chrome/common/media_router/media_source_unittest.cc
index 11825581c17..c4609881dab 100644
--- a/chromium/chrome/common/media_router/media_source_unittest.cc
+++ b/chromium/chrome/common/media_router/media_source_unittest.cc
@@ -54,25 +54,34 @@ TEST(MediaSourceTest, ConstructorWithURLString) {
EXPECT_EQ(test_url, source1.url());
}
+TEST(MediaSourceTest, ForAnyTab) {
+ auto source = MediaSource::ForAnyTab();
+ EXPECT_EQ("urn:x-org.chromium.media:source:tab:*", source.id());
+ EXPECT_EQ(-1, source.TabId());
+ EXPECT_FALSE(source.IsDesktopMirroringSource());
+ EXPECT_TRUE(source.IsTabMirroringSource());
+ EXPECT_FALSE(source.IsLocalFileSource());
+ EXPECT_FALSE(source.IsCastPresentationUrl());
+ EXPECT_FALSE(source.IsDialSource());
+}
+
TEST(MediaSourceTest, ForTab) {
auto source = MediaSource::ForTab(123);
EXPECT_EQ("urn:x-org.chromium.media:source:tab:123", source.id());
EXPECT_EQ(123, source.TabId());
- EXPECT_TRUE(source.IsValid());
EXPECT_FALSE(source.IsDesktopMirroringSource());
EXPECT_TRUE(source.IsTabMirroringSource());
- EXPECT_TRUE(source.IsMirroringSource());
+ EXPECT_FALSE(source.IsLocalFileSource());
EXPECT_FALSE(source.IsCastPresentationUrl());
EXPECT_FALSE(source.IsDialSource());
}
-TEST(MediaSourceTest, ForTabContentRemoting) {
- auto source = MediaSource::ForTabContentRemoting(123);
- EXPECT_EQ(123, source.TabId());
- EXPECT_TRUE(source.IsValid());
+TEST(MediaSourceTest, ForLocalFile) {
+ auto source = MediaSource::ForLocalFile();
+ EXPECT_EQ("urn:x-org.chromium.media:source:tab:0", source.id());
EXPECT_FALSE(source.IsDesktopMirroringSource());
EXPECT_FALSE(source.IsTabMirroringSource());
- EXPECT_FALSE(source.IsMirroringSource());
+ EXPECT_TRUE(source.IsLocalFileSource());
EXPECT_FALSE(source.IsCastPresentationUrl());
EXPECT_FALSE(source.IsDialSource());
}
@@ -81,10 +90,9 @@ TEST(MediaSourceTest, ForDesktop) {
std::string media_id = "fakeMediaId";
auto source = MediaSource::ForDesktop(media_id);
EXPECT_EQ("urn:x-org.chromium.media:source:desktop:" + media_id, source.id());
- EXPECT_TRUE(source.IsValid());
EXPECT_TRUE(source.IsDesktopMirroringSource());
EXPECT_FALSE(source.IsTabMirroringSource());
- EXPECT_TRUE(source.IsMirroringSource());
+ EXPECT_FALSE(source.IsLocalFileSource());
EXPECT_FALSE(source.IsCastPresentationUrl());
EXPECT_FALSE(source.IsDialSource());
}
@@ -94,23 +102,13 @@ TEST(MediaSourceTest, ForPresentationUrl) {
"https://www.example.com/presentation.html";
auto source = MediaSource::ForPresentationUrl(GURL(kPresentationUrl));
EXPECT_EQ(kPresentationUrl, source.id());
- EXPECT_TRUE(source.IsValid());
EXPECT_FALSE(source.IsDesktopMirroringSource());
EXPECT_FALSE(source.IsTabMirroringSource());
- EXPECT_FALSE(source.IsMirroringSource());
+ EXPECT_FALSE(source.IsLocalFileSource());
EXPECT_FALSE(source.IsCastPresentationUrl());
EXPECT_FALSE(source.IsDialSource());
}
-TEST(MediaSourceTest, IsValid) {
- // Disallowed scheme
- EXPECT_FALSE(MediaSource::ForPresentationUrl(GURL("file:///some/local/path"))
- .IsValid());
- // Not a URL
- EXPECT_FALSE(
- MediaSource::ForPresentationUrl(GURL("totally not a url")).IsValid());
-}
-
TEST(MediaSourceTest, IsCastPresentationUrl) {
EXPECT_TRUE(MediaSource(GURL("cast:233637DE")).IsCastPresentationUrl());
EXPECT_TRUE(
diff --git a/chromium/chrome/common/media_router/mojom/BUILD.gn b/chromium/chrome/common/media_router/mojom/BUILD.gn
index 7463f0776a5..b6cb091ba85 100644
--- a/chromium/chrome/common/media_router/mojom/BUILD.gn
+++ b/chromium/chrome/common/media_router/mojom/BUILD.gn
@@ -4,6 +4,11 @@
import("//mojo/public/tools/bindings/mojom.gni")
+mojom("logger") {
+ sources = [ "logger.mojom" ]
+ public_deps = [ "//mojo/public/mojom/base" ]
+}
+
mojom("media_controller") {
sources = [
"media_controller.mojom",
@@ -21,6 +26,7 @@ mojom("media_router") {
sources = [ "media_router.mojom" ]
public_deps = [
+ ":logger",
":media_controller",
"//components/mirroring/mojom:host",
"//media/mojo/mojom:mirror_service_remoting",
diff --git a/chromium/chrome/common/media_router/mojom/logger.mojom b/chromium/chrome/common/media_router/mojom/logger.mojom
new file mode 100644
index 00000000000..340062e46ca
--- /dev/null
+++ b/chromium/chrome/common/media_router/mojom/logger.mojom
@@ -0,0 +1,53 @@
+// Copyright 2020 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.
+
+module media_router.mojom;
+
+import "mojo/public/mojom/base/time.mojom";
+
+enum LogCategory {
+ kDiscovery,
+ kRoute,
+ kMirroring,
+ kUi,
+};
+
+// Collects logs from Media Router components such as Media Route Providers.
+// The implementation lives in the browser process.
+interface Logger {
+ // Records a log entry of "info" severity. The severities are "info",
+ // "warning", and "error" in increasing order.
+ // |component|: This is usually the name of the class that is emitting the
+ // log, such as "CastSessionTracker".
+ // |message|: The log message.
+ // |sink_id|: ID of the media sink associated with this log. May be empty if
+ // the log is not associated with a sink.
+ // |media_source|: ID of the media source, which may be of the format
+ // "cast:ABCDEFGH?arg1=val1" (app ID and query params) for Cast sessions,
+ // or the receiver page URL in the case of presentations. May be empty.
+ // |session_id|: ID of the Cast or presentation session associated with this
+ // log. May be empty.
+ LogInfo(LogCategory category,
+ string component,
+ string message,
+ string sink_id,
+ string media_source,
+ string session_id);
+
+ // Records a log entry of "warning" severity.
+ LogWarning(LogCategory category,
+ string component,
+ string message,
+ string sink_id,
+ string media_source,
+ string session_id);
+
+ // Records a log entry of "error" severity.
+ LogError(LogCategory category,
+ string component,
+ string message,
+ string sink_id,
+ string media_source,
+ string session_id);
+};
diff --git a/chromium/chrome/common/media_router/mojom/media_router.mojom b/chromium/chrome/common/media_router/mojom/media_router.mojom
index 95e445dfa20..0219ea1b462 100644
--- a/chromium/chrome/common/media_router/mojom/media_router.mojom
+++ b/chromium/chrome/common/media_router/mojom/media_router.mojom
@@ -4,6 +4,7 @@
module media_router.mojom;
+import "chrome/common/media_router/mojom/logger.mojom";
import "chrome/common/media_router/mojom/media_controller.mojom";
import "chrome/common/media_router/mojom/media_status.mojom";
import "components/mirroring/mojom/mirroring_service_host.mojom";
@@ -122,8 +123,8 @@ struct MediaRoute {
RouteControllerType controller_type;
// Set to true if this route should be displayed for |media_sink_id| in UI.
bool for_display;
- // Set to true if this route was created by an incognito profile.
- bool is_incognito;
+ // Set to true if this route was created by an OffTheRecord profile.
+ bool is_off_the_record;
// Set to true if this route corresponds to a local presentation.
bool is_local_presentation;
};
@@ -208,7 +209,7 @@ enum RouteRequestResultCode {
ROUTE_NOT_FOUND,
SINK_NOT_FOUND,
INVALID_ORIGIN,
- INCOGNITO_MISMATCH,
+ OFF_THE_RECORD_MISMATCH,
NO_SUPPORTED_PROVIDER,
CANCELLED,
ROUTE_ALREADY_EXISTS,
@@ -307,7 +308,8 @@ interface MediaRouteProvider {
// If |timeout| is positive, it will be used in place of the default timeout
// defined by Media Route Provider Manager.
//
- // If |incognito| is true, the request was made by an incognito profile.
+ // If |off_the_record| is true, the request was made by an OffTheRecord
+ // profile.
//
// If the operation was successful, |route| will be defined and |error_text|
// will be null. If the operation failed, |route| will be null and
@@ -323,7 +325,7 @@ interface MediaRouteProvider {
url.mojom.Origin origin,
int32 tab_id,
mojo_base.mojom.TimeDelta timeout,
- bool incognito) =>
+ bool off_the_record) =>
(MediaRoute? route,
RoutePresentationConnection? connection,
string? error_text,
@@ -338,8 +340,8 @@ interface MediaRouteProvider {
// If |timeout| is positive, it will be used in place of the default timeout
// defined by Media Route Provider Manager.
//
- // If the route request was created by an incognito profile,
- // |incognito| must be true.
+ // If the route request was created by an OffTheRecord profile,
+ // |off_the_record| must be true.
//
// If the operation was successful, |route| will be defined and |error_text|
// will be null. If the operation failed, |route| will be null and
@@ -353,7 +355,7 @@ interface MediaRouteProvider {
url.mojom.Origin origin,
int32 tab_id,
mojo_base.mojom.TimeDelta timeout,
- bool incognito) =>
+ bool off_the_record) =>
(MediaRoute? route,
RoutePresentationConnection? connection,
string? error_text,
@@ -373,8 +375,8 @@ interface MediaRouteProvider {
// defined by Media Route Provider Manager; see CreateRoute for additional
// documentation.
//
- // If the route request was created by an incognito profile,
- // |incognito| must be true.
+ // If the route request was created by an OffTheRecord profile,
+ // |off_the_record| must be true.
//
// If the operation was successful, |route| will be defined and
// |error_text| will be null. If the operation failed, |route| will be null
@@ -391,7 +393,7 @@ interface MediaRouteProvider {
url.mojom.Origin origin,
int32 tab_id,
mojo_base.mojom.TimeDelta timeout,
- bool incognito) =>
+ bool off_the_record) =>
(MediaRoute? route,
RoutePresentationConnection? connection,
string? error_text,
@@ -597,6 +599,15 @@ interface MediaRouter {
// Returns current status of media sink service in JSON format.
GetMediaSinkServiceStatus() => (string status);
+ // The logger can be used to add entries to logs returned by GetLogs().
+ GetLogger(pending_receiver<Logger> receiver);
+
+ // Returns a JSON array of logs collected by Media Router components.
+ // Serializing the logs requires allocating extra memory, so it should only be
+ // called under limited circumstances, such as when the user is submitting a
+ // feedback report.
+ GetLogsAsString() => (string logs);
+
// Called to get a mirroring.mojom.MirroringServiceHost. These APIs are used
// by Media Router extension to start mirroring through the mirroring service.
// TODO(http://crbug.com/809249): Remove these APIs when native Cast MRP with
diff --git a/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.cc b/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.cc
index ecb173bd65c..a48bece3a32 100644
--- a/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.cc
+++ b/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.cc
@@ -216,7 +216,7 @@ bool StructTraits<media_router::mojom::MediaRouteDataView,
out->set_local(data.is_local());
out->set_for_display(data.for_display());
- out->set_incognito(data.is_incognito());
+ out->set_off_the_record(data.is_off_the_record());
out->set_local_presentation(data.is_local_presentation());
return true;
diff --git a/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.h b/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.h
index cc7c383a797..76ab7593602 100644
--- a/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.h
+++ b/chromium/chrome/common/media_router/mojom/media_router_mojom_traits.h
@@ -397,8 +397,8 @@ struct StructTraits<media_router::mojom::MediaRouteDataView,
return route.for_display();
}
- static bool is_incognito(const media_router::MediaRoute& route) {
- return route.is_incognito();
+ static bool is_off_the_record(const media_router::MediaRoute& route) {
+ return route.is_off_the_record();
}
static bool is_local_presentation(const media_router::MediaRoute& route) {
@@ -426,8 +426,9 @@ struct EnumTraits<media_router::mojom::RouteRequestResultCode,
return media_router::mojom::RouteRequestResultCode::SINK_NOT_FOUND;
case media_router::RouteRequestResult::INVALID_ORIGIN:
return media_router::mojom::RouteRequestResultCode::INVALID_ORIGIN;
- case media_router::RouteRequestResult::INCOGNITO_MISMATCH:
- return media_router::mojom::RouteRequestResultCode::INCOGNITO_MISMATCH;
+ case media_router::RouteRequestResult::OFF_THE_RECORD_MISMATCH:
+ return media_router::mojom::RouteRequestResultCode::
+ OFF_THE_RECORD_MISMATCH;
case media_router::RouteRequestResult::NO_SUPPORTED_PROVIDER:
return media_router::mojom::RouteRequestResultCode::
NO_SUPPORTED_PROVIDER;
@@ -467,8 +468,8 @@ struct EnumTraits<media_router::mojom::RouteRequestResultCode,
case media_router::mojom::RouteRequestResultCode::INVALID_ORIGIN:
*output = media_router::RouteRequestResult::INVALID_ORIGIN;
return true;
- case media_router::mojom::RouteRequestResultCode::INCOGNITO_MISMATCH:
- *output = media_router::RouteRequestResult::INCOGNITO_MISMATCH;
+ case media_router::mojom::RouteRequestResultCode::OFF_THE_RECORD_MISMATCH:
+ *output = media_router::RouteRequestResult::OFF_THE_RECORD_MISMATCH;
return true;
case media_router::mojom::RouteRequestResultCode::NO_SUPPORTED_PROVIDER:
*output = media_router::RouteRequestResult::NO_SUPPORTED_PROVIDER;
diff --git a/chromium/chrome/common/media_router/providers/cast/cast_media_source.cc b/chromium/chrome/common/media_router/providers/cast/cast_media_source.cc
index 97002d0fd2a..c7fe6bf2e93 100644
--- a/chromium/chrome/common/media_router/providers/cast/cast_media_source.cc
+++ b/chromium/chrome/common/media_router/providers/cast/cast_media_source.cc
@@ -61,6 +61,7 @@ const EnumTable<CastDeviceCapability> EnumTable<CastDeviceCapability>::instance(
template <>
const EnumTable<ReceiverAppType> EnumTable<ReceiverAppType>::instance(
{
+ {ReceiverAppType::kOther, "OTHER"},
{ReceiverAppType::kWeb, "WEB"},
{ReceiverAppType::kAndroidTv, "ANDROID_TV"},
},
@@ -70,6 +71,9 @@ const EnumTable<ReceiverAppType> EnumTable<ReceiverAppType>::instance(
namespace media_router {
+// The maximum length of presentation URL is 64KB.
+constexpr int kMaxCastPresentationUrlLength = 64 * 1024;
+
namespace {
// A nonmember version of base::Optional::value_or that works on pointers as
@@ -188,8 +192,8 @@ std::unique_ptr<CastMediaSource> CastMediaSourceForTabMirroring(
const MediaSource::Id& source_id) {
return std::make_unique<CastMediaSource>(
source_id,
- std::vector<CastAppInfo>({CastAppInfo(kCastStreamingAppId),
- CastAppInfo(kCastStreamingAudioAppId)}));
+ std::vector<CastAppInfo>({CastAppInfo::ForCastStreaming(),
+ CastAppInfo::ForCastStreamingAudio()}));
}
std::unique_ptr<CastMediaSource> CastMediaSourceForDesktopMirroring(
@@ -197,7 +201,7 @@ std::unique_ptr<CastMediaSource> CastMediaSourceForDesktopMirroring(
// TODO(https://crbug.com/849335): Add back audio-only devices for desktop
// mirroring when proper support is implemented.
return std::make_unique<CastMediaSource>(
- source_id, std::vector<CastAppInfo>({CastAppInfo(kCastStreamingAppId)}));
+ source_id, std::vector<CastAppInfo>({CastAppInfo::ForCastStreaming()}));
}
// The logic shared by ParseCastUrl() and ParseLegacyCastUrl().
@@ -210,6 +214,8 @@ std::unique_ptr<CastMediaSource> CreateFromURLParams(
const std::string& broadcast_namespace,
const std::string& encoded_broadcast_message,
const std::string& launch_timeout_str,
+ const std::string& target_playout_delay_millis_str,
+ const std::string& audio_capture_str,
const std::vector<ReceiverAppType>& supported_app_types,
const std::string& app_params) {
if (app_infos.empty())
@@ -227,13 +233,24 @@ std::unique_ptr<CastMediaSource> CreateFromURLParams(
broadcast_namespace, DecodeURLComponent(encoded_broadcast_message)));
}
- int launch_timeout_millis;
+ int launch_timeout_millis = 0;
if (base::StringToInt(launch_timeout_str, &launch_timeout_millis) &&
launch_timeout_millis > 0) {
cast_source->set_launch_timeout(
base::TimeDelta::FromMilliseconds(launch_timeout_millis));
}
+ int target_playout_delay_millis = 0;
+ if (base::StringToInt(target_playout_delay_millis_str,
+ &target_playout_delay_millis) &&
+ target_playout_delay_millis > 0) {
+ cast_source->set_target_playout_delay(
+ base::TimeDelta::FromMilliseconds(target_playout_delay_millis));
+ }
+
+ if (audio_capture_str == "0")
+ cast_source->set_allow_audio_capture(false);
+
if (!supported_app_types.empty())
cast_source->set_supported_app_types(supported_app_types);
cast_source->set_app_params(app_params);
@@ -259,6 +276,8 @@ std::unique_ptr<CastMediaSource> ParseCastUrl(const MediaSource::Id& source_id,
FindValueOr(params, "broadcastNamespace", ""),
FindValueOr(params, "broadcastMessage", ""),
FindValueOr(params, "launchTimeout", ""),
+ FindValueOr(params, "streamingTargetPlayoutDelayMillis", ""),
+ FindValueOr(params, "streamingCaptureAudio", ""),
SupportedAppTypesFromString(FindValueOr(params, "supportedAppTypes", "")),
FindValueOr(params, "appParams", ""));
}
@@ -318,6 +337,8 @@ std::unique_ptr<CastMediaSource> ParseLegacyCastUrl(
FindValueOr(params, "__castBroadcastNamespace__", ""),
FindValueOr(params, "__castBroadcastMessage__", ""),
FindValueOr(params, "__castLaunchTimeout__", ""),
+ /* target_playout_delay_millis_str */ "",
+ /* audio_capture */ "",
/* supported_app_types */ {},
/* appParams */ "");
}
@@ -339,27 +360,45 @@ bool IsAutoJoinAllowed(AutoJoinPolicy policy,
}
}
+bool IsSiteInitiatedMirroringSource(const MediaSource::Id& source_id) {
+ return base::StartsWith(source_id, kMirroringAppUri,
+ base::CompareCase::SENSITIVE);
+}
+
CastAppInfo::CastAppInfo(
const std::string& app_id,
BitwiseOr<cast_channel::CastDeviceCapability> required_capabilities)
: app_id(app_id), required_capabilities(required_capabilities) {}
+
CastAppInfo::~CastAppInfo() = default;
CastAppInfo::CastAppInfo(const CastAppInfo& other) = default;
// static
+CastAppInfo CastAppInfo::ForCastStreaming() {
+ return CastAppInfo(kCastStreamingAppId, {CastDeviceCapability::VIDEO_OUT,
+ CastDeviceCapability::AUDIO_OUT});
+}
+
+// static
+CastAppInfo CastAppInfo::ForCastStreamingAudio() {
+ return CastAppInfo(kCastStreamingAudioAppId,
+ {CastDeviceCapability::AUDIO_OUT});
+}
+
+// static
std::unique_ptr<CastMediaSource> CastMediaSource::FromMediaSource(
const MediaSource& source) {
- if (source.IsTabMirroringSource())
+ if (source.IsTabMirroringSource() || source.IsLocalFileSource())
return CastMediaSourceForTabMirroring(source.id());
if (source.IsDesktopMirroringSource())
return CastMediaSourceForDesktopMirroring(source.id());
const GURL& url = source.url();
- if (!url.is_valid())
- return nullptr;
+ if (!url.is_valid() || url.spec().length() > kMaxCastPresentationUrlLength)
+ return nullptr;
if (url.SchemeIs(kCastPresentationUrlScheme)) {
return ParseCastUrl(source.id(), url);
} else if (IsLegacyCastPresentationUrl(url)) {
diff --git a/chromium/chrome/common/media_router/providers/cast/cast_media_source.h b/chromium/chrome/common/media_router/providers/cast/cast_media_source.h
index 09c04496b2f..ce8f7b9ef98 100644
--- a/chromium/chrome/common/media_router/providers/cast/cast_media_source.h
+++ b/chromium/chrome/common/media_router/providers/cast/cast_media_source.h
@@ -11,7 +11,7 @@
#include <type_traits>
#include <vector>
-#include "base/logging.h"
+#include "base/check.h"
#include "base/optional.h"
#include "chrome/common/media_router/media_source.h"
#include "components/cast_channel/cast_message_util.h"
@@ -28,6 +28,13 @@ static constexpr char kCastStreamingAudioAppId[] = "85CDB22F";
// message.
static constexpr char kMultizoneLeaderAppId[] = "MultizoneLeader";
+static const constexpr char* const kMultizoneMemberAppIds[] = {
+ kMultizoneLeaderAppId,
+ "531A4F84", // MultizoneLeader
+ "MultizoneFollower",
+ "705D30C6" // MultizoneFollower
+};
+
static constexpr base::TimeDelta kDefaultLaunchTimeout =
base::TimeDelta::FromSeconds(60);
@@ -44,12 +51,20 @@ class BitwiseOr {
for (E e : values)
Add(e);
}
+ static constexpr BitwiseOr FromBits(T bits) { return BitwiseOr(bits); }
bool empty() const { return bits_ == 0; }
+ T bits() const { return bits_; }
void Add(E value) { bits_ |= Mask(value); }
+ bool Has(E value) const { return (bits_ & Mask(value)) != 0; }
+ bool HasAll(const BitwiseOr& other) const {
+ return (bits_ & other.bits_) == other.bits_;
+ }
bool operator==(const BitwiseOr& other) const { return bits_ == other.bits_; }
bool operator!=(const BitwiseOr& other) const { return *this != other; }
private:
+ explicit constexpr BitwiseOr(T bits) : bits_(bits) {}
+
static T Mask(E value) {
const T result = static_cast<T>(value);
DCHECK(static_cast<E>(result) == value);
@@ -60,12 +75,16 @@ class BitwiseOr {
// Represents a Cast app and its capabilitity requirements.
struct CastAppInfo {
- explicit CastAppInfo(const std::string& app_id,
- BitwiseOr<cast_channel::CastDeviceCapability> = {});
+ explicit CastAppInfo(
+ const std::string& app_id,
+ BitwiseOr<cast_channel::CastDeviceCapability> required_capabilities);
~CastAppInfo();
CastAppInfo(const CastAppInfo& other);
+ static CastAppInfo ForCastStreaming();
+ static CastAppInfo ForCastStreamingAudio();
+
std::string app_id;
// A bitset of capabilities required by the app.
@@ -114,6 +133,9 @@ bool IsAutoJoinAllowed(AutoJoinPolicy policy,
const url::Origin& origin2,
int tab_id2);
+// Returns true if |source_id| is a valid origin for site-initiated mirroring.
+bool IsSiteInitiatedMirroringSource(const MediaSource::Id& source_id);
+
// Represents a MediaSource parsed into structured, Cast specific data. The
// following MediaSources can be parsed into CastMediaSource:
// - Cast Presentation URLs
@@ -165,6 +187,17 @@ class CastMediaSource {
DefaultActionPolicy default_action_policy() const {
return default_action_policy_;
}
+ base::Optional<base::TimeDelta> target_playout_delay() const {
+ return target_playout_delay_;
+ }
+ void set_target_playout_delay(
+ const base::Optional<base::TimeDelta>& target_playout_delay) {
+ target_playout_delay_ = target_playout_delay;
+ }
+ bool allow_audio_capture() const { return allow_audio_capture_; }
+ void set_allow_audio_capture(bool allow_audio_capture) {
+ allow_audio_capture_ = allow_audio_capture;
+ }
const std::string& app_params() const { return app_params_; }
void set_app_params(const std::string& app_params) {
app_params_ = app_params;
@@ -180,9 +213,11 @@ class CastMediaSource {
AutoJoinPolicy auto_join_policy_;
DefaultActionPolicy default_action_policy_;
base::TimeDelta launch_timeout_ = kDefaultLaunchTimeout;
- // Empty if not set.
+ // Optional parameters.
std::string client_id_;
base::Optional<cast_channel::BroadcastRequest> broadcast_request_;
+ base::Optional<base::TimeDelta> target_playout_delay_;
+ bool allow_audio_capture_ = true;
std::vector<ReceiverAppType> supported_app_types_ = {ReceiverAppType::kWeb};
std::string app_params_;
};
diff --git a/chromium/chrome/common/media_router/providers/cast/cast_media_source_unittest.cc b/chromium/chrome/common/media_router/providers/cast/cast_media_source_unittest.cc
index 42c5c660f7a..03ebc375c99 100644
--- a/chromium/chrome/common/media_router/providers/cast/cast_media_source_unittest.cc
+++ b/chromium/chrome/common/media_router/providers/cast/cast_media_source_unittest.cc
@@ -30,6 +30,8 @@ TEST(CastMediaSourceTest, FromCastURLWithDefaults) {
EXPECT_EQ(DefaultActionPolicy::kCreateSession,
source->default_action_policy());
EXPECT_EQ(ReceiverAppType::kWeb, source->supported_app_types()[0]);
+ EXPECT_EQ(base::nullopt, source->target_playout_delay());
+ EXPECT_EQ(true, source->allow_audio_capture());
}
TEST(CastMediaSourceTest, FromCastURL) {
@@ -42,7 +44,9 @@ TEST(CastMediaSourceTest, FromCastURL) {
"&autoJoinPolicy=tab_and_origin_scoped"
"&defaultActionPolicy=cast_this_tab"
"&appParams=appParams"
- "&supportedAppTypes=ANDROID_TV,WEB");
+ "&supportedAppTypes=ANDROID_TV,WEB"
+ "&streamingTargetPlayoutDelayMillis=42"
+ "&streamingCaptureAudio=0");
std::unique_ptr<CastMediaSource> source =
CastMediaSource::FromMediaSourceId(source_id);
ASSERT_TRUE(source);
@@ -64,6 +68,9 @@ TEST(CastMediaSourceTest, FromCastURL) {
EXPECT_EQ(ReceiverAppType::kAndroidTv, source->supported_app_types()[0]);
EXPECT_EQ(ReceiverAppType::kWeb, source->supported_app_types()[1]);
EXPECT_EQ("appParams", source->app_params());
+ EXPECT_EQ(base::TimeDelta::FromMilliseconds(42),
+ source->target_playout_delay());
+ EXPECT_EQ(false, source->allow_audio_capture());
}
TEST(CastMediaSourceTest, FromLegacyCastURL) {
@@ -159,6 +166,10 @@ TEST(CastMediaSourceTest, FromInvalidSource) {
EXPECT_FALSE(CastMediaSource::FromMediaSourceId("cast:?param=foo"));
EXPECT_FALSE(CastMediaSource::FromMediaSourceId(
"https://google.com/cast#__castAppId__=/param=foo"));
+ // URL spec exceeds maximum size limit 64KB.
+ int length = 64 * 1024 + 1;
+ std::string invalidURL(length, 'a');
+ EXPECT_FALSE(CastMediaSource::FromMediaSourceId("cast:appid?" + invalidURL));
}
} // namespace media_router
diff --git a/chromium/chrome/common/media_router/route_request_result.h b/chromium/chrome/common/media_router/route_request_result.h
index 855dfa8e1f0..65761d726a2 100644
--- a/chromium/chrome/common/media_router/route_request_result.h
+++ b/chromium/chrome/common/media_router/route_request_result.h
@@ -42,7 +42,7 @@ class RouteRequestResult {
ROUTE_NOT_FOUND = 3,
SINK_NOT_FOUND = 4,
INVALID_ORIGIN = 5,
- INCOGNITO_MISMATCH = 6,
+ OFF_THE_RECORD_MISMATCH = 6,
NO_SUPPORTED_PROVIDER = 7,
CANCELLED = 8,
ROUTE_ALREADY_EXISTS = 9,
diff --git a/chromium/chrome/common/net/OWNERS b/chromium/chrome/common/net/OWNERS
index b77292902d2..14758211512 100644
--- a/chromium/chrome/common/net/OWNERS
+++ b/chromium/chrome/common/net/OWNERS
@@ -1,4 +1,7 @@
file://net/OWNERS
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
+
# COMPONENT: Internals>Network
# TEAM: net-dev@chromium.org
diff --git a/chromium/chrome/common/net/net_error_page_support.mojom b/chromium/chrome/common/net/net_error_page_support.mojom
new file mode 100644
index 00000000000..ae2a112b4e3
--- /dev/null
+++ b/chromium/chrome/common/net/net_error_page_support.mojom
@@ -0,0 +1,17 @@
+// Copyright 2020 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.
+
+module chrome.mojom;
+
+// A per-frame interface used to support network error pages.
+// TODO(darin): Consolidate other such interfaces into this interface.
+interface NetErrorPageSupport {
+ // Called to schedule a download of the current page at a later time.
+ [EnableIf=enable_offline_pages]
+ DownloadPageLater();
+
+ // Called to indicate if download button is being shown in the error page.
+ [EnableIf=enable_offline_pages]
+ SetIsShowingDownloadButtonInErrorPage(bool showing_download_button);
+};
diff --git a/chromium/chrome/common/performance_manager/OWNERS b/chromium/chrome/common/performance_manager/OWNERS
index 0a5168e1964..7e4c8d7e6b4 100644
--- a/chromium/chrome/common/performance_manager/OWNERS
+++ b/chromium/chrome/common/performance_manager/OWNERS
@@ -1 +1,5 @@
-file://chrome/browser/performance_manager/OWNERS
+file://components/performance_manager/OWNERS
+
+# For IPC security review
+per-file *.mojom=set noparent
+per-file *.mojom=file://ipc/SECURITY_OWNERS
diff --git a/chromium/chrome/common/performance_manager/mojom/BUILD.gn b/chromium/chrome/common/performance_manager/mojom/BUILD.gn
index 6d99bc11f20..bcaa4f5aa4b 100644
--- a/chromium/chrome/common/performance_manager/mojom/BUILD.gn
+++ b/chromium/chrome/common/performance_manager/mojom/BUILD.gn
@@ -2,4 +2,9 @@ import("//mojo/public/tools/bindings/mojom.gni")
mojom("mojom") {
sources = [ "tcmalloc.mojom" ]
+
+ cpp_only = true
+ disable_variants = true
+
+ deps = [ "//mojo/public/mojom/base" ]
}
diff --git a/chromium/chrome/common/pref_names.cc b/chromium/chrome/common/pref_names.cc
index 934e5074bd0..4f6f8d2fd1a 100644
--- a/chromium/chrome/common/pref_names.cc
+++ b/chromium/chrome/common/pref_names.cc
@@ -18,11 +18,6 @@ namespace prefs {
// *************** PROFILE PREFS ***************
// These are attached to the user profile
-// A bool pref that indicates whether interventions for abusive experiences
-// should be enforced.
-const char kAbusiveExperienceInterventionEnforce[] =
- "abusive_experience_intervention_enforce";
-
// A bool pref that keeps whether the child status for this profile was already
// successfully checked via ChildAccountService.
const char kChildAccountStatusKnown[] = "child_account_status_known";
@@ -706,7 +701,7 @@ const char kSAMLOfflineSigninTimeLimit[] = "saml.offline_signin_time_limit";
// against GAIA: If GAIA redirects to a SAML IdP, the preference is set to the
// current time. If GAIA performs the authentication itself, the preference is
// cleared. The time is expressed as the serialization obtained from
-// base::Time::ToInternalValue().
+// PrefService::SetTime().
const char kSAMLLastGAIASignInTime[] = "saml.last_gaia_sign_in_time";
// The total number of seconds that the machine has spent sitting on the
@@ -818,6 +813,10 @@ const char kPinUnlockMinimumLength[] = "pin_unlock_minimum_length";
const char kPinUnlockMaximumLength[] = "pin_unlock_maximum_length";
// Boolean pref indicating whether users are allowed to set easy pins.
const char kPinUnlockWeakPinsAllowed[] = "pin_unlock_weak_pins_allowed";
+// A boolean pref that controls whether the PIN autosubmit feature is enabled.
+// This feature, when enabled, exposes the user's PIN length by showing how many
+// digits are necessary to unlock the device. Can be recommended.
+const char kPinUnlockAutosubmitEnabled[] = "pin_unlock_autosubmit_enabled";
// Boolean pref indicating whether this device supports BLE advertising.
const char kInstantTetheringBleAdvertisingSupported[] =
@@ -1031,10 +1030,6 @@ const char kLoginExtensionApiLaunchExtensionId[] =
// String containing last RSU lookup key uploaded. Empty until first upload.
const char kLastRsuDeviceIdUploaded[] = "rsu.last_rsu_device_id_uploaded";
-// Boolean that determines whether to show a banner in OS Settings that links
-// to Browser settings.
-const char kSettingsShowBrowserBanner[] = "settings.cros.show_browser_banner";
-
// Boolean user profile pref that determines whether to show a banner in browser
// settings that links to OS settings.
const char kSettingsShowOSBanner[] = "settings.cros.show_os_banner";
@@ -1043,6 +1038,16 @@ const char kSettingsShowOSBanner[] = "settings.cros.show_os_banner";
// urls to be used via the WebUSB API on the login screen.
const char kDeviceLoginScreenWebUsbAllowDevicesForUrls[] =
"device_login_screen_webusb_allow_devices_for_urls";
+
+// Int64 pref indicating the time in microseconds since Windows epoch when the
+// timer for update required which will block user session was started. If the
+// timer is not started the pref holds the default value base::Time().
+const char kUpdateRequiredTimerStartTime[] = "update_required_timer_start_time";
+
+// Int64 pref indicating the waiting time in microseconds after which the update
+// required timer will expire and block user session. If the timer is not
+// started the pref holds the default value base::TimeDelta().
+const char kUpdateRequiredWarningPeriod[] = "update_required_warning_period";
#endif // defined(OS_CHROMEOS)
// A boolean pref set to true if a Home button to open the Home pages should be
@@ -1196,6 +1201,12 @@ const char kAccessibilityImageLabelsEnabled[] =
const char kAccessibilityImageLabelsOptInAccepted[] =
"settings.a11y.enable_accessibility_image_labels_opt_in_accepted";
+#if !defined(OS_CHROMEOS)
+// A boolean pref which determines whether focus highlighting is enabled.
+const char kAccessibilityFocusHighlightEnabled[] =
+ "settings.a11y.focus_highlight";
+#endif
+
#if !defined(OS_ANDROID)
// Whether the Live Caption feature is enabled.
const char kLiveCaptionEnabled[] =
@@ -1424,6 +1435,11 @@ const char kPrintJobHistoryExpirationPeriod[] =
// they use the chrome.printing.submitJob() function.
const char kPrintingAPIExtensionsWhitelist[] =
"printing.printing_api_extensions_whitelist";
+
+// Boolean flag which represents whether the user's print job history can be
+// deleted.
+const char kDeletePrintJobHistoryAllowed[] =
+ "printing.delete_print_job_history_allowed";
#endif // OS_CHROMEOS
// An integer pref specifying the fallback behavior for sites outside of content
@@ -1541,6 +1557,12 @@ const char kNaviOnboardGroup[] = "browser.navi_onboard_group";
const char kEnableQuietNotificationPermissionUi[] =
"profile.content_settings.enable_quiet_permission_ui.notifications";
+// Boolean indicating whether, as part of the adaptive activation quiet UI dry
+// run experiment, the user has accumulated three notification permission
+// request denies in a row.
+const char kHadThreeConsecutiveNotificationPermissionDenies[] =
+ "profile.content_settings.had_three_consecutive_denies.notifications";
+
// Boolean indicating whether to show a promo for the quiet notification
// permission UI.
const char kQuietNotificationPermissionShouldShowPromo[] =
@@ -1661,6 +1683,10 @@ const char kOpenPdfDownloadInSystemReader[] =
// ask the user where they want to download the file (only for Android).
const char kPromptForDownloadAndroid[] = "download.prompt_for_download_android";
+// The prompt status for the download later dialog.
+const char kDownloadLaterPromptStatus[] =
+ "download.download_later_prompt_status";
+
// Boolean which specifies whether we should display the missing SD card error.
// This is only applicable for Android.
const char kShowMissingSdCardErrorAndroid[] =
@@ -2092,6 +2118,10 @@ const char kAutoEnrollmentPowerLimit[] = "AutoEnrollmentPowerLimit";
// them to the policy server.
const char kDeviceActivityTimes[] = "device_status.activity_times";
+// A pref that stores user app activity times before reporting them to the
+// policy server.
+const char kAppActivityTimes[] = "device_status.app_activity_times";
+
// A pref that stores user activity times before reporting them to the policy
// server.
const char kUserActivityTimes[] = "consumer_device_status.activity_times";
@@ -2238,13 +2268,15 @@ const char kReportingUsers[] = "reporting_users";
const char kArcAppInstallEventLoggingEnabled[] =
"arc.app_install_event_logging_enabled";
+// Boolean pref indicating if event logging is enabled for policy based
+// extension.
+const char kExtensionInstallEventLoggingEnabled[] =
+ "extensions.install.event_logging_enabled";
+
// Whether we received the remove users remote command, and hence should proceed
// with removing the users while at the login screen.
const char kRemoveUsersRemoteCommand[] = "remove_users_remote_command";
-// Whether camera-produced media files have been consolidated to one place.
-const char kCameraMediaConsolidated[] = "camera_media_consolidated";
-
// Integer pref used by the metrics::DailyEvent owned by
// chromeos::power::auto_screen_brightness::MetricsReporter.
const char kAutoScreenBrightnessMetricsDailySample[] =
@@ -2282,6 +2314,20 @@ const char kSamlInSessionPasswordChangeEnabled[] =
const char kSamlPasswordExpirationAdvanceWarningDays[] =
"saml.password_expiration_advance_warning_days";
+// Enable online signin on the lock screen.
+const char kSamlLockScreenReauthenticationEnabled[] =
+ "saml.lock_screen_reauthentication_enabled";
+
+// Integer pref used by the metrics::DailyEvent owned by
+// local_search_service::MetricsReporter.
+const char kLocalSearchServiceMetricsDailySample[] =
+ "local_search_service.metrics.daily_sample";
+
+// Integer prefs used to back event counts reported by
+// local_search_service::MetricsReporter.
+const char kLocalSearchServiceMetricsCrosSettingsCount[] =
+ "local_search_service.metrics.cros_settings_count";
+
#endif // defined(OS_CHROMEOS)
// Whether there is a Flash version installed that supports clearing LSO data.
@@ -2857,12 +2903,6 @@ const char kIsolateOrigins[] = "site_isolation.isolate_origins";
// Boolean that specifies opting into --site-per-process (full Site Isolation).
const char kSitePerProcess[] = "site_isolation.site_per_process";
-// A list of origins that were heuristically determined to need process
-// isolation. For example, an origin may be placed on this list in response to
-// the user typing a password on it.
-const char kUserTriggeredIsolatedOrigins[] =
- "site_isolation.user_triggered_isolated_origins";
-
#if !defined(OS_ANDROID)
// Boolean that specifies whether media (audio/video) autoplay is allowed.
const char kAutoplayAllowed[] = "media.autoplay_allowed";
@@ -2953,15 +2993,13 @@ const char kCorsLegacyModeEnabled[] = "cors.legacy_mode.enabled";
const char kExternalProtocolDialogShowAlwaysOpenCheckbox[] =
"external_protocol_dialog.show_always_open_checkbox";
-// This pref allows the Web Components v0 APIs to be re-enabled temporarily
-// from M80 through M84.
-// TODO(937746): Remove this after M84.
-const char kWebComponentsV0Enabled[] = "web_components_v0_enabled";
-
-// This pref allows the FormControlsRefresh feature to be disabled temporarily
-// from M81 through M84.
-// TODO(1034611): Remove this after M84.
-const char kUseLegacyFormControls[] = "use_legacy_form_controls";
+// List of dictionaries. For each dictionary, key "protocol" is a protocol
+// (as a string) that is permitted by policy to launch an external application
+// without prompting the user. Key "allowed_origins" is a nested list of origin
+// patterns that defines the scope of applicability of that protocol. If the
+// "allow" list is empty, that protocol rule will never apply.
+const char kAutoLaunchProtocolsFromOrigins[] =
+ "protocol_handler.policy.auto_launch_protocols_from_origins";
// This pref enables the ScrollToTextFragment feature.
const char kScrollToTextFragmentEnabled[] = "scroll_to_text_fragment_enabled";
@@ -2985,6 +3023,10 @@ extern const char kCertificateProvisioningStateForDevice[] =
"cert_provisioning_device_state";
#endif
+// This pref enables periodically fetching new Media Feed items for top feeds.
+const char kMediaFeedsBackgroundFetching[] =
+ "media_feeds_background_fetching_enabled";
+
// This pref enables checking of Media Feed items against the Safe Search API.
const char kMediaFeedsSafeSearchEnabled[] = "media_feeds_safe_search_enabled";
diff --git a/chromium/chrome/common/pref_names.h b/chromium/chrome/common/pref_names.h
index 493b14f3631..2f54b8588eb 100644
--- a/chromium/chrome/common/pref_names.h
+++ b/chromium/chrome/common/pref_names.h
@@ -22,7 +22,6 @@
namespace prefs {
// Profile prefs. Please add Local State prefs below instead.
-extern const char kAbusiveExperienceInterventionEnforce[];
extern const char kChildAccountStatusKnown[];
extern const char kDefaultApps[];
extern const char kSafeBrowsingForTrustedSourcesEnabled[];
@@ -177,6 +176,9 @@ extern const char kContextualSearchEnabledValue[];
extern const char kShowInternalAccessibilityTree[];
extern const char kAccessibilityImageLabelsEnabled[];
extern const char kAccessibilityImageLabelsOptInAccepted[];
+#if !defined(OS_CHROMEOS)
+extern const char kAccessibilityFocusHighlightEnabled[];
+#endif
extern const char kAccessibilityCaptionsTextSize[];
extern const char kAccessibilityCaptionsTextFont[];
extern const char kAccessibilityCaptionsTextColor[];
@@ -286,6 +288,7 @@ extern const char kQuickUnlockTimeout[];
extern const char kPinUnlockMinimumLength[];
extern const char kPinUnlockMaximumLength[];
extern const char kPinUnlockWeakPinsAllowed[];
+extern const char kPinUnlockAutosubmitEnabled[];
extern const char kInstantTetheringBleAdvertisingSupported[];
extern const char kCastReceiverEnabled[];
extern const char kMinimumAllowedChromeVersion[];
@@ -332,9 +335,10 @@ extern const char kAppReinstallRecommendationEnabled[];
extern const char kStartupBrowserWindowLaunchSuppressed[];
extern const char kLoginExtensionApiDataForNextLoginAttempt[];
extern const char kLoginExtensionApiLaunchExtensionId[];
-extern const char kSettingsShowBrowserBanner[];
extern const char kSettingsShowOSBanner[];
extern const char kDeviceLoginScreenWebUsbAllowDevicesForUrls[];
+extern const char kUpdateRequiredTimerStartTime[];
+extern const char kUpdateRequiredWarningPeriod[];
#endif // defined(OS_CHROMEOS)
extern const char kShowHomeButton[];
extern const char kSpeechRecognitionFilterProfanities[];
@@ -456,6 +460,7 @@ extern const char kPrintingSendUsernameAndFilenameEnabled[];
extern const char kPrintingMaxSheetsAllowed[];
extern const char kPrintJobHistoryExpirationPeriod[];
extern const char kPrintingAPIExtensionsWhitelist[];
+extern const char kDeletePrintJobHistoryAllowed[];
#endif // OS_CHROMEOS
extern const char kDefaultSupervisedUserFilteringBehavior[];
@@ -514,6 +519,7 @@ extern const char kEnableQuietNotificationPermissionUi[];
extern const char kQuietNotificationPermissionShouldShowPromo[];
extern const char kQuietNotificationPermissionPromoWasShown[];
extern const char kNotificationPermissionActions[];
+extern const char kHadThreeConsecutiveNotificationPermissionDenies[];
extern const char kProfileLastUsed[];
extern const char kProfilesLastActive[];
@@ -555,6 +561,7 @@ extern const char kOpenPdfDownloadInSystemReader[];
#endif
#if defined(OS_ANDROID)
extern const char kPromptForDownloadAndroid[];
+extern const char kDownloadLaterPromptStatus[];
extern const char kShowMissingSdCardErrorAndroid[];
#endif
@@ -681,6 +688,7 @@ extern const char kHardwareKeyboardLayout[];
extern const char kShouldAutoEnroll[];
extern const char kAutoEnrollmentPowerLimit[];
extern const char kDeviceActivityTimes[];
+extern const char kAppActivityTimes[];
extern const char kUserActivityTimes[];
extern const char kExternalStorageDisabled[];
extern const char kExternalStorageReadOnly[];
@@ -721,8 +729,8 @@ extern const char kPowerMetricsIdleSuspendCount[];
extern const char kPowerMetricsLidClosedSuspendCount[];
extern const char kReportingUsers[];
extern const char kArcAppInstallEventLoggingEnabled[];
+extern const char kExtensionInstallEventLoggingEnabled[];
extern const char kRemoveUsersRemoteCommand[];
-extern const char kCameraMediaConsolidated[];
extern const char kAutoScreenBrightnessMetricsDailySample[];
extern const char kAutoScreenBrightnessMetricsAtlasUserAdjustmentCount[];
extern const char kAutoScreenBrightnessMetricsEveUserAdjustmentCount[];
@@ -735,7 +743,11 @@ extern const char
extern const char kKnownUserParentAccessCodeConfig[];
extern const char kSamlInSessionPasswordChangeEnabled[];
extern const char kSamlPasswordExpirationAdvanceWarningDays[];
+extern const char kSamlLockScreenReauthenticationEnabled[];
extern const char kLastRsuDeviceIdUploaded[];
+extern const char kLocalSearchServiceMetricsDailySample[];
+extern const char kLocalSearchServiceMetricsCrosSettingsCount[];
+
#endif // defined(OS_CHROMEOS)
extern const char kClearPluginLSODataEnabled[];
@@ -991,7 +1003,6 @@ extern const char kUnsafelyTreatInsecureOriginAsSecure[];
extern const char kIsolateOrigins[];
extern const char kSitePerProcess[];
-extern const char kUserTriggeredIsolatedOrigins[];
#if !defined(OS_ANDROID)
extern const char kAutoplayAllowed[];
@@ -1042,9 +1053,7 @@ extern const char kCorsLegacyModeEnabled[];
extern const char kExternalProtocolDialogShowAlwaysOpenCheckbox[];
-extern const char kWebComponentsV0Enabled[];
-
-extern const char kUseLegacyFormControls[];
+extern const char kAutoLaunchProtocolsFromOrigins[];
extern const char kScrollToTextFragmentEnabled[];
@@ -1059,6 +1068,7 @@ extern const char kCertificateProvisioningStateForUser[];
extern const char kCertificateProvisioningStateForDevice[];
#endif
+extern const char kMediaFeedsBackgroundFetching[];
extern const char kMediaFeedsSafeSearchEnabled[];
extern const char kAppCacheForceEnabled[];
diff --git a/chromium/chrome/common/prerender_canceler.mojom b/chromium/chrome/common/prerender_canceler.mojom
deleted file mode 100644
index 58d0ee027fa..00000000000
--- a/chromium/chrome/common/prerender_canceler.mojom
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2017 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.
-
-module chrome.mojom;
-
-import "url/mojom/url.mojom";
-
-// This interface is provided to a renderer that is used for prerendering. It
-// enables the renderer to detect and respond to cases that should cause the
-// prerendering to be cancelled.
-interface PrerenderCanceler {
- // Cancels prerendering because of an unsupported scheme.
- CancelPrerenderForUnsupportedScheme(url.mojom.Url url);
-};
diff --git a/chromium/chrome/common/prerender_messages.h b/chromium/chrome/common/prerender_messages.h
deleted file mode 100644
index a6e900009c1..00000000000
--- a/chromium/chrome/common/prerender_messages.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2012 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.
-
-#ifndef CHROME_COMMON_PRERENDER_MESSAGES_H_
-#define CHROME_COMMON_PRERENDER_MESSAGES_H_
-
-#include "chrome/common/prerender_types.h"
-#include "ipc/ipc_message.h"
-#include "ipc/ipc_message_macros.h"
-#include "ipc/ipc_param_traits.h"
-
-#define IPC_MESSAGE_START PrerenderMsgStart
-
-IPC_ENUM_TRAITS_MAX_VALUE(prerender::PrerenderMode,
- prerender::PRERENDER_MODE_COUNT - 1)
-
-// PrerenderLinkManager Messages
-
-// Sent by the renderer process to notify that the resource prefetcher has
-// discovered all possible subresources and issued requests for them.
-IPC_MESSAGE_CONTROL0(PrerenderHostMsg_PrefetchFinished)
-
-// PrerenderDispatcher Messages
-// These are messages sent from the browser to the renderer in relation to
-// running prerenders.
-
-// Tells a renderer if it's currently being prerendered. Must only be set
-// before any navigation occurs, and only set to NO_PRERENDER at most once after
-// that.
-IPC_MESSAGE_ROUTED2(PrerenderMsg_SetIsPrerendering,
- prerender::PrerenderMode,
- std::string /* histogram_prefix */)
-
-#endif // CHROME_COMMON_PRERENDER_MESSAGES_H_
diff --git a/chromium/chrome/common/prerender_types.h b/chromium/chrome/common/prerender_types.h
deleted file mode 100644
index e6c98dc86e4..00000000000
--- a/chromium/chrome/common/prerender_types.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright 2014 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.
-
-#ifndef CHROME_COMMON_PRERENDER_TYPES_H_
-#define CHROME_COMMON_PRERENDER_TYPES_H_
-
-namespace prerender {
-
-enum PrerenderMode {
- // Neither prefetch nor prerender.
- NO_PRERENDER = 0,
-
- // Only used in tests. Can be removed after http://crbug.com/898955 is fixed.
- DEPRECATED_FULL_PRERENDER = 1,
-
- // Prefetch some network resources to warm up the cache.
- PREFETCH_ONLY = 2,
-
- PRERENDER_MODE_COUNT = 3,
-};
-
-} // namespace prerender
-
-#endif // CHROME_COMMON_PRERENDER_TYPES_H_
diff --git a/chromium/chrome/common/prerender_url_loader_throttle.cc b/chromium/chrome/common/prerender_url_loader_throttle.cc
index 96c33d2bbc6..8c010275e14 100644
--- a/chromium/chrome/common/prerender_url_loader_throttle.cc
+++ b/chromium/chrome/common/prerender_url_loader_throttle.cc
@@ -24,9 +24,9 @@ const char kPurposeHeaderName[] = "Purpose";
const char kPurposeHeaderValue[] = "prefetch";
void CallCancelPrerenderForUnsupportedScheme(
- mojo::PendingRemote<chrome::mojom::PrerenderCanceler> canceler,
+ mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler,
const GURL& url) {
- mojo::Remote<chrome::mojom::PrerenderCanceler>(std::move(canceler))
+ mojo::Remote<prerender::mojom::PrerenderCanceler>(std::move(canceler))
->CancelPrerenderForUnsupportedScheme(url);
}
@@ -39,9 +39,9 @@ bool IsNoStoreResponse(const network::mojom::URLResponseHead& response_head) {
} // namespace
PrerenderURLLoaderThrottle::PrerenderURLLoaderThrottle(
- PrerenderMode mode,
+ prerender::mojom::PrerenderMode mode,
const std::string& histogram_prefix,
- mojo::PendingRemote<chrome::mojom::PrerenderCanceler> canceler)
+ mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler)
: mode_(mode),
histogram_prefix_(histogram_prefix),
canceler_(std::move(canceler)) {
@@ -69,7 +69,7 @@ void PrerenderURLLoaderThrottle::DetachFromCurrentSequence() {
void PrerenderURLLoaderThrottle::WillStartRequest(
network::ResourceRequest* request,
bool* defer) {
- if (mode_ == PREFETCH_ONLY) {
+ if (mode_ == prerender::mojom::PrerenderMode::kPrefetchOnly) {
request->load_flags |= net::LOAD_PREFETCH;
request->cors_exempt_headers.SetHeader(kPurposeHeaderName,
kPurposeHeaderValue);
@@ -123,7 +123,7 @@ void PrerenderURLLoaderThrottle::WillStartRequest(
}
#endif // OS_ANDROID
- if (mode_ == PREFETCH_ONLY) {
+ if (mode_ == prerender::mojom::PrerenderMode::kPrefetchOnly) {
detached_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(
content::kDefaultDetachableCancelDelayMs),
@@ -139,7 +139,7 @@ void PrerenderURLLoaderThrottle::WillRedirectRequest(
net::HttpRequestHeaders* /* modified_headers */,
net::HttpRequestHeaders* /* modified_cors_exempt_headers */) {
redirect_count_++;
- if (mode_ == PREFETCH_ONLY) {
+ if (mode_ == prerender::mojom::PrerenderMode::kPrefetchOnly) {
RecordPrefetchResponseReceived(
histogram_prefix_, blink::IsResourceTypeFrame(resource_type_),
true /* is_redirect */, IsNoStoreResponse(response_head));
@@ -169,8 +169,9 @@ void PrerenderURLLoaderThrottle::WillProcessResponse(
const GURL& response_url,
network::mojom::URLResponseHead* response_head,
bool* defer) {
- if (mode_ != PREFETCH_ONLY)
+ if (mode_ != prerender::mojom::PrerenderMode::kPrefetchOnly) {
return;
+ }
bool is_main_resource = blink::IsResourceTypeFrame(resource_type_);
RecordPrefetchResponseReceived(histogram_prefix_, is_main_resource,
diff --git a/chromium/chrome/common/prerender_url_loader_throttle.h b/chromium/chrome/common/prerender_url_loader_throttle.h
index c76ad1264d7..f7b35f5d172 100644
--- a/chromium/chrome/common/prerender_url_loader_throttle.h
+++ b/chromium/chrome/common/prerender_url_loader_throttle.h
@@ -10,8 +10,8 @@
#include "base/optional.h"
#include "base/sequenced_task_runner.h"
#include "base/timer/timer.h"
-#include "chrome/common/prerender_canceler.mojom.h"
-#include "chrome/common/prerender_types.h"
+#include "components/prerender/common/prerender_canceler.mojom.h"
+#include "components/prerender/common/prerender_types.mojom.h"
#include "net/base/request_priority.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h"
@@ -23,9 +23,9 @@ class PrerenderURLLoaderThrottle
public base::SupportsWeakPtr<PrerenderURLLoaderThrottle> {
public:
PrerenderURLLoaderThrottle(
- PrerenderMode mode,
+ prerender::mojom::PrerenderMode mode,
const std::string& histogram_prefix,
- mojo::PendingRemote<chrome::mojom::PrerenderCanceler> canceler);
+ mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler);
~PrerenderURLLoaderThrottle() override;
// Called when the prerender is used. This will unpaused requests and set the
@@ -54,14 +54,14 @@ class PrerenderURLLoaderThrottle
void OnTimedOut();
- PrerenderMode mode_;
+ prerender::mojom::PrerenderMode mode_;
std::string histogram_prefix_;
bool deferred_ = false;
int redirect_count_ = 0;
blink::mojom::ResourceType resource_type_;
- mojo::PendingRemote<chrome::mojom::PrerenderCanceler> canceler_;
+ mojo::PendingRemote<prerender::mojom::PrerenderCanceler> canceler_;
// The throttle changes most request priorities to IDLE during prerendering.
// The priority is reset back to the original priority when prerendering is
diff --git a/chromium/chrome/common/prerender_util.cc b/chromium/chrome/common/prerender_util.cc
index 70282cf5107..a08bb92f369 100644
--- a/chromium/chrome/common/prerender_util.cc
+++ b/chromium/chrome/common/prerender_util.cc
@@ -57,9 +57,9 @@ bool DoesSubresourceURLHaveValidScheme(const GURL& url) {
return DoesURLHaveValidScheme(url) || url == url::kAboutBlankURL;
}
-bool IsValidHttpMethod(PrerenderMode prerender_mode,
+bool IsValidHttpMethod(prerender::mojom::PrerenderMode prerender_mode,
const std::string& method) {
- DCHECK_NE(prerender_mode, NO_PRERENDER);
+ DCHECK_NE(prerender_mode, prerender::mojom::PrerenderMode::kNoPrerender);
// |method| has been canonicalized to upper case at this point so we can just
// compare them.
DCHECK_EQ(method, base::ToUpperASCII(method));
@@ -68,7 +68,7 @@ bool IsValidHttpMethod(PrerenderMode prerender_mode,
return true;
}
- if (prerender_mode == PREFETCH_ONLY)
+ if (prerender_mode == prerender::mojom::PrerenderMode::kPrefetchOnly)
return false;
for (auto* valid_method : kValidHttpMethodsForPrerendering) {
diff --git a/chromium/chrome/common/prerender_util.h b/chromium/chrome/common/prerender_util.h
index 4fa1436ccb6..39d2aa7f698 100644
--- a/chromium/chrome/common/prerender_util.h
+++ b/chromium/chrome/common/prerender_util.h
@@ -7,7 +7,7 @@
#include <string>
-#include "chrome/common/prerender_types.h"
+#include "components/prerender/common/prerender_types.mojom.h"
class GURL;
@@ -22,7 +22,8 @@ bool DoesURLHaveValidScheme(const GURL& url);
bool DoesSubresourceURLHaveValidScheme(const GURL& url);
// Returns true iff the method given is valid for prerendering.
-bool IsValidHttpMethod(PrerenderMode prerender_mode, const std::string& method);
+bool IsValidHttpMethod(prerender::mojom::PrerenderMode prerender_mode,
+ const std::string& method);
std::string ComposeHistogramName(const std::string& prefix_type,
const std::string& name);
diff --git a/chromium/chrome/common/privacy_budget/BUILD.gn b/chromium/chrome/common/privacy_budget/BUILD.gn
new file mode 100644
index 00000000000..8190119f51a
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/BUILD.gn
@@ -0,0 +1,50 @@
+# Copyright 2020 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.
+
+source_set("privacy_budget") {
+ sources = [
+ "container_ops.h",
+ "field_trial_param_conversions.cc",
+ "field_trial_param_conversions.h",
+ "privacy_budget_features.cc",
+ "privacy_budget_features.h",
+ "privacy_budget_settings_provider.cc",
+ "privacy_budget_settings_provider.h",
+ ]
+
+ public_deps = [
+ "//base",
+ "//third_party/blink/public/common",
+ ]
+}
+
+source_set("unit_tests") {
+ testonly = true
+
+ sources = [
+ "container_ops_unittest.cc",
+ "field_trial_param_conversions_unittest.cc",
+ ]
+
+ deps = [
+ ":privacy_budget",
+ "//base",
+ "//testing/gtest",
+ ]
+}
+
+source_set("test_support") {
+ testonly = true
+
+ sources = [
+ "scoped_privacy_budget_config.cc",
+ "scoped_privacy_budget_config.h",
+ ]
+
+ deps = [
+ ":privacy_budget",
+ "//base/test:test_support",
+ "//third_party/blink/public/common/privacy_budget",
+ ]
+}
diff --git a/chromium/chrome/common/privacy_budget/DEPS b/chromium/chrome/common/privacy_budget/DEPS
new file mode 100644
index 00000000000..487aca2a220
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/DEPS
@@ -0,0 +1,3 @@
+include_rules = [
+ "+third_party/blink/public/common/privacy_budget"
+]
diff --git a/chromium/chrome/common/privacy_budget/OWNERS b/chromium/chrome/common/privacy_budget/OWNERS
new file mode 100644
index 00000000000..cfc756a1170
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/OWNERS
@@ -0,0 +1,4 @@
+file://third_party/blink/public/common/privacy_budget/OWNERS
+
+# TEAM: privacy-sandbox-dev@chromium.org
+# COMPONENT: Privacy>Fingerprinting
diff --git a/chromium/chrome/common/privacy_budget/README.md b/chromium/chrome/common/privacy_budget/README.md
new file mode 100644
index 00000000000..f58322ed4c9
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/README.md
@@ -0,0 +1,6 @@
+# Privacy Budget: Static Study Settings
+
+See [Privacy Budget: Code
+Locations](../../../docs/privacy_budget_code_locations.md) for
+details.
+
diff --git a/chromium/chrome/common/privacy_budget/container_ops.h b/chromium/chrome/common/privacy_budget/container_ops.h
new file mode 100644
index 00000000000..c7665401e23
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/container_ops.h
@@ -0,0 +1,83 @@
+// Copyright 2020 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.
+
+#ifndef CHROME_COMMON_PRIVACY_BUDGET_CONTAINER_OPS_H_
+#define CHROME_COMMON_PRIVACY_BUDGET_CONTAINER_OPS_H_
+
+#include <algorithm>
+#include <cstddef>
+#include <vector>
+
+#include "base/rand_util.h"
+#include "base/stl_util.h"
+#include "base/strings/string_piece.h"
+
+namespace internal {
+// Note that these implementations aren't meant for to be used outside of the
+// narrow usage within this directory.
+
+// Moves a random subset of |num| elements from |from| to |to|. The type |T|
+// must satisfy |UnorderedAssociativeContainer|.
+//
+// Returns true if any elements were moved.
+template <typename T, typename V = typename T::value_type>
+bool ExtractRandomSubset(T* from, T* to, size_t num) {
+ if (num == 0 || from->empty())
+ return false;
+ std::vector<V> copy(from->begin(), from->end());
+ if (num < copy.size())
+ base::RandomShuffle(copy.begin(), copy.end());
+ for (auto to_remove_it = copy.begin(); num > 0 && to_remove_it != copy.end();
+ ++to_remove_it, --num) {
+ from->erase(*to_remove_it);
+ to->insert(*to_remove_it);
+ }
+ return true;
+}
+
+// Extracts elements from |from| that matches predicate |pred| and places them
+// in |to|.
+//
+// Returns true if any elements were moved.
+template <typename T, typename Predicate, typename V = typename T::value_type>
+bool ExtractIf(T* from, T* to, Predicate predicate) {
+ std::vector<V> to_be_moved;
+ to_be_moved.reserve(from->size());
+ std::copy_if(from->begin(), from->end(),
+ std::inserter(to_be_moved, to_be_moved.end()), predicate);
+ for (const auto& v : to_be_moved)
+ from->erase(v);
+ to->insert(to_be_moved.begin(), to_be_moved.end());
+ return !to_be_moved.empty();
+}
+
+// Removes elements from |right| that also exist in |left|.
+//
+// Returns true if |right| was modified.
+//
+// Different from std::set_difference in that it does not assume any ordering of
+// elements.
+template <typename T, typename V = typename T::value_type>
+bool SubtractLeftFromRight(const T& left, T* right) {
+ const auto previous_size = right->size();
+ base::EraseIf(*right, [&](const V& v) { return base::Contains(left, v); });
+ return previous_size != right->size();
+}
+
+// Determine if the intersection of |left| and |right| is non-empty. Notably
+// unlike std::set_intersection<> does not assume any ordering of elements.
+template <typename T, typename V = typename T::value_type>
+bool Intersects(const T& left, const T& right) {
+ if (left.size() <= right.size()) {
+ return std::any_of(left.begin(), left.end(), [&](const V& candidate) {
+ return base::Contains(right, candidate);
+ });
+ } else {
+ return Intersects(right, left);
+ }
+}
+
+} // namespace internal
+
+#endif // CHROME_COMMON_PRIVACY_BUDGET_CONTAINER_OPS_H_
diff --git a/chromium/chrome/common/privacy_budget/container_ops_unittest.cc b/chromium/chrome/common/privacy_budget/container_ops_unittest.cc
new file mode 100644
index 00000000000..5721ae091c2
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/container_ops_unittest.cc
@@ -0,0 +1,166 @@
+// Copyright 2020 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.
+
+#include <set>
+
+#include "chrome/common/privacy_budget/container_ops.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace internal {
+
+namespace {
+
+typedef ::testing::Types<std::unordered_set<int>, std::set<int>> ContainerTypes;
+
+} // namespace
+
+template <typename T>
+class ContainerOpsTest : public ::testing::Test {};
+
+TYPED_TEST_SUITE_P(ContainerOpsTest);
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractRandomSubset) {
+ TypeParam from = {1, 2, 3, 4};
+ TypeParam to = {5};
+
+ EXPECT_TRUE(ExtractRandomSubset(&from, &to, 1));
+ EXPECT_EQ(3u, from.size());
+ EXPECT_EQ(2u, to.size());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractRandomSubset_Zero) {
+ TypeParam from = {1, 2, 3, 4};
+ TypeParam to = {5};
+
+ EXPECT_FALSE(ExtractRandomSubset(&from, &to, 0));
+ EXPECT_EQ(from, (TypeParam{1, 2, 3, 4}));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractRandomSubset_Empty) {
+ TypeParam to = {5};
+
+ // Moving from an empty set.
+ TypeParam from_two;
+ EXPECT_FALSE(ExtractRandomSubset(&from_two, &to, 1));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractRandomSubset_Overflow) {
+ TypeParam from = {1, 2, 3, 4};
+ TypeParam to = {5};
+ // Overflow.
+ EXPECT_TRUE(ExtractRandomSubset(&from, &to, 100));
+ EXPECT_EQ(0u, from.size());
+ EXPECT_EQ(5u, to.size());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractRandomSubset_Merge) {
+ TypeParam from = {1, 2, 3, 4};
+ TypeParam to = {1, 2, 3, 4, 5};
+ // Moved element disappears because |from| is a subset of |to|. Assuming the
+ // underlying set implementation is correct (we'd be in pretty bad shape if
+ // that were not true) verifies that the element being moved is one we expect.
+ EXPECT_TRUE(ExtractRandomSubset(&from, &to, 1));
+ EXPECT_EQ(3u, from.size());
+ EXPECT_EQ(5u, to.size());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestIntersects) {
+ TypeParam a = {1, 2, 3, 4};
+ TypeParam b = {4, 5, 6, 7};
+ TypeParam c = {10, 11};
+ TypeParam d;
+
+ EXPECT_TRUE(Intersects(a, b));
+ EXPECT_FALSE(Intersects(b, c));
+ EXPECT_FALSE(Intersects(b, d));
+ EXPECT_FALSE(Intersects(d, d));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractIf_Basic) {
+ TypeParam from = {1, 2, 3, 4, 5, 6};
+ TypeParam to;
+
+ // Extracts only when predicate is true.
+ EXPECT_TRUE(ExtractIf(&from, &to, [](const auto& v) { return v % 2 == 0; }));
+ EXPECT_EQ(from, (TypeParam{1, 3, 5}));
+ EXPECT_EQ(to, (TypeParam{2, 4, 6}));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractIf_AlwaysFalse) {
+ TypeParam from = {1, 3, 5};
+ TypeParam to;
+
+ // Noop if predicate is always false.
+ EXPECT_FALSE(ExtractIf(&from, &to, [](const auto& v) { return false; }));
+ EXPECT_EQ(from, (TypeParam{1, 3, 5}));
+ EXPECT_TRUE(to.empty());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractIf_AlwaysTrue) {
+ TypeParam from = {1, 2, 3, 4, 5, 6};
+ TypeParam to;
+
+ // Just because. Isn't testing anything new.
+ EXPECT_TRUE(ExtractIf(&from, &to, [](const auto& v) { return true; }));
+ EXPECT_EQ(6u, to.size());
+ EXPECT_TRUE(from.empty());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestExtractIf_EmptySource) {
+ TypeParam from;
+ TypeParam to = {1, 2, 3, 4, 5, 6};
+
+ // Noop if |from| is empty.
+ EXPECT_FALSE(ExtractIf(&from, &to, [](const auto& v) { return true; }));
+ EXPECT_EQ(6u, to.size());
+ EXPECT_TRUE(from.empty());
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestSubtractLeftFromRight_WithIntersection) {
+ TypeParam a = {1, 2, 3, 4, 5, 6, 7};
+ TypeParam b = {2, 3, 4};
+
+ EXPECT_TRUE(SubtractLeftFromRight(b, &a));
+ EXPECT_EQ(a, (TypeParam{1, 5, 6, 7}));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestSubtractLeftFromRight_NoIntersection) {
+ TypeParam a = {1, 5, 6, 7};
+ TypeParam c = {10};
+
+ // Nothing happens if there's no intersection.
+ EXPECT_FALSE(SubtractLeftFromRight(c, &a));
+ EXPECT_EQ(a, (TypeParam{1, 5, 6, 7}));
+}
+
+TYPED_TEST_P(ContainerOpsTest, TestSubtractLeftFromRight_LeftEmpty) {
+ TypeParam a = {1, 5, 6, 7};
+ TypeParam d;
+
+ // Nothing happens when the left side is empty.
+ EXPECT_FALSE(SubtractLeftFromRight(d, &a));
+ EXPECT_EQ(a, (TypeParam{1, 5, 6, 7}));
+}
+
+REGISTER_TYPED_TEST_SUITE_P(ContainerOpsTest,
+ TestIntersects,
+ TestExtractIf_Basic,
+ TestExtractIf_AlwaysFalse,
+ TestExtractIf_AlwaysTrue,
+ TestExtractIf_EmptySource,
+ TestExtractRandomSubset,
+ TestExtractRandomSubset_Zero,
+ TestExtractRandomSubset_Empty,
+ TestExtractRandomSubset_Overflow,
+ TestExtractRandomSubset_Merge,
+ TestSubtractLeftFromRight_WithIntersection,
+ TestSubtractLeftFromRight_NoIntersection,
+ TestSubtractLeftFromRight_LeftEmpty);
+
+INSTANTIATE_TYPED_TEST_SUITE_P(UnorderedAndOrderedSets,
+ ContainerOpsTest,
+ ContainerTypes);
+
+} // namespace internal
diff --git a/chromium/chrome/common/privacy_budget/field_trial_param_conversions.cc b/chromium/chrome/common/privacy_budget/field_trial_param_conversions.cc
new file mode 100644
index 00000000000..80859cbe1a4
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/field_trial_param_conversions.cc
@@ -0,0 +1,48 @@
+// Copyright 2020 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.
+
+#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
+
+#include <utility>
+
+bool DecodeIdentifiabilityType(const base::StringPiece s,
+ blink::IdentifiableSurface* out) {
+ uint64_t hash = 0;
+ if (!base::StringToUint64(s, &hash))
+ return false;
+ *out = blink::IdentifiableSurface::FromMetricHash(hash);
+ return true;
+}
+
+bool DecodeIdentifiabilityType(const base::StringPiece s,
+ blink::IdentifiableSurface::Type* out) {
+ uint64_t hash = 0;
+ if (!base::StringToUint64(s, &hash))
+ return false;
+ if ((hash & blink::IdentifiableSurface::kTypeMask) != hash)
+ return false;
+ *out = static_cast<blink::IdentifiableSurface::Type>(hash);
+ return true;
+}
+
+std::string EncodeIdentifiabilityType(const blink::IdentifiableSurface& s) {
+ return base::NumberToString(s.ToUkmMetricHash());
+}
+
+std::string EncodeIdentifiabilityType(
+ const blink::IdentifiableSurface::Type& t) {
+ return base::NumberToString(static_cast<uint64_t>(t));
+}
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<const blink::IdentifiableSurface, int>& v) {
+ return EncodeIdentifiabilityType(v.first) + ";" +
+ base::NumberToString(v.second);
+}
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<const blink::IdentifiableSurface::Type, int>& v) {
+ return EncodeIdentifiabilityType(v.first) + ";" +
+ base::NumberToString(v.second);
+}
diff --git a/chromium/chrome/common/privacy_budget/field_trial_param_conversions.h b/chromium/chrome/common/privacy_budget/field_trial_param_conversions.h
new file mode 100644
index 00000000000..3c99297a790
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/field_trial_param_conversions.h
@@ -0,0 +1,121 @@
+// Copyright 2020 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.
+
+#ifndef CHROME_COMMON_PRIVACY_BUDGET_FIELD_TRIAL_PARAM_CONVERSIONS_H_
+#define CHROME_COMMON_PRIVACY_BUDGET_FIELD_TRIAL_PARAM_CONVERSIONS_H_
+
+#include <type_traits>
+
+#include "base/notreached.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_piece.h"
+#include "base/strings/string_split.h"
+#include "base/strings/string_util.h"
+#include "chrome/common/privacy_budget/privacy_budget_features.h"
+#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
+
+// The Encode/Decode families of functions are meant to be used to encode
+// various types so that they can be specified via field trial configurations
+// and Prefs.
+
+bool DecodeIdentifiabilityType(const base::StringPiece,
+ blink::IdentifiableSurface*);
+
+bool DecodeIdentifiabilityType(const base::StringPiece,
+ blink::IdentifiableSurface::Type*);
+
+// This explosion of DecodeIdentifiabilityTypePair specializations is a great
+// example of why you don't want to go down the path of templates if you could
+// ever avoid it.
+//
+// The variability here is that unordered_map uses pair<K,V> as its value_type
+// while map uses pair<const K, V>. Per spec, unordered_map should also use the
+// latter, but alas, that is not the case.
+//
+// Adding to the confusion, pair<const K, V> is non-movable and non-copyable. So
+// it can't be returned via a trivial *out parameter. Amazing.
+template <typename U,
+ typename V = typename U::value_type,
+ typename P = typename std::remove_const<typename V::first_type>::type>
+std::pair<V, bool> DecodeIdentifiabilityTypePair(base::StringPiece s) {
+ auto pieces =
+ base::SplitStringPiece(s, ";", base::WhitespaceHandling::TRIM_WHITESPACE,
+ base::SplitResult::SPLIT_WANT_NONEMPTY);
+ if (pieces.size() != 2)
+ return {V(), false};
+ P type_id;
+ int rate;
+ if (!DecodeIdentifiabilityType(pieces[0], &type_id) ||
+ !base::StringToInt(pieces[1], &rate))
+ return {V(), false};
+ if (rate < 0 || rate > features::kMaxIdentifiabilityStudySurfaceSelectionRate)
+ return {V(), false};
+ return {V(type_id, rate), true};
+}
+
+template <
+ typename U,
+ typename S = std::enable_if_t<
+ std::is_same<typename U::key_type, typename U::value_type>::value>>
+std::pair<typename U::value_type, bool> DecodeIdentifiabilityTypePair(
+ base::StringPiece s) {
+ using P = typename U::value_type;
+ P value;
+ if (!DecodeIdentifiabilityType(s, &value))
+ return {P(), false};
+ return {value, true};
+}
+
+std::string EncodeIdentifiabilityType(const blink::IdentifiableSurface&);
+
+std::string EncodeIdentifiabilityType(const blink::IdentifiableSurface::Type&);
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<const blink::IdentifiableSurface, int>&);
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<const blink::IdentifiableSurface::Type, int>&);
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<blink::IdentifiableSurface, int>&);
+
+std::string EncodeIdentifiabilityType(
+ const std::pair<blink::IdentifiableSurface::Type, int>&);
+
+// Decodes a field trial parameter containing a list of values. The result is
+// returned in the form of a container type that must be specified at
+// instantiation. There should be a valid DecodeIdentifiabilityType
+// specialization for the container's value type.
+template <typename T,
+ std::pair<typename T::value_type, bool> Decoder(
+ const base::StringPiece) = DecodeIdentifiabilityTypePair<T>>
+T DecodeIdentifiabilityFieldTrialParam(base::StringPiece encoded_value) {
+ T result;
+ auto hashes = base::SplitStringPiece(
+ encoded_value, ",", base::WhitespaceHandling::TRIM_WHITESPACE,
+ base::SplitResult::SPLIT_WANT_NONEMPTY);
+ for (const auto& hash : hashes) {
+ auto decoded = Decoder(hash);
+ if (!decoded.second)
+ continue;
+ result.insert(decoded.first);
+ }
+ return result;
+}
+
+// Encodes a field trial parameter that will contain a list of values taken from
+// a container. The container must satisfy the named requirement Container. Its
+// value_type must have a corresponding EncodeIdentifiabilityType
+// specialization.
+template <typename T,
+ std::string Encoder(const typename T::value_type&) =
+ EncodeIdentifiabilityType>
+std::string EncodeIdentifiabilityFieldTrialParam(const T& source) {
+ std::vector<std::string> result;
+ std::transform(source.begin(), source.end(), std::back_inserter(result),
+ [](auto& v) { return Encoder(v); });
+ return base::JoinString(result, ",");
+}
+
+#endif // CHROME_COMMON_PRIVACY_BUDGET_FIELD_TRIAL_PARAM_CONVERSIONS_H_
diff --git a/chromium/chrome/common/privacy_budget/field_trial_param_conversions_unittest.cc b/chromium/chrome/common/privacy_budget/field_trial_param_conversions_unittest.cc
new file mode 100644
index 00000000000..46a68e44e76
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/field_trial_param_conversions_unittest.cc
@@ -0,0 +1,73 @@
+// Copyright 2020 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.
+
+#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+TEST(FieldTrialParamConversionsTest, Surface) {
+ auto original_surface = blink::IdentifiableSurface::FromMetricHash(100);
+ EXPECT_EQ(std::string("100"), EncodeIdentifiabilityType(original_surface));
+
+ original_surface = blink::IdentifiableSurface::FromTypeAndInput(
+ blink::IdentifiableSurface::Type::kWebFeature, 1);
+ std::string encoded = EncodeIdentifiabilityType(original_surface);
+ EXPECT_EQ(std::string("257"), encoded);
+
+ auto decoded_surface = blink::IdentifiableSurface();
+ EXPECT_TRUE(DecodeIdentifiabilityType(encoded, &decoded_surface));
+ EXPECT_EQ(original_surface, decoded_surface);
+}
+
+TEST(FieldTrialParamConversionsTest, Type) {
+ auto original_type = blink::IdentifiableSurface::Type::kWebFeature;
+ std::string encoded = EncodeIdentifiabilityType(original_type);
+ EXPECT_EQ(std::string("1"), encoded);
+
+ auto foo = blink::IdentifiableSurface::Type::kReservedInternal;
+ EXPECT_TRUE(DecodeIdentifiabilityType(encoded, &foo));
+ EXPECT_EQ(original_type, foo);
+}
+
+TEST(FieldTrialParamConversionsTest, FieldTrialParam_Surface) {
+ std::map<blink::IdentifiableSurface, int> original_map;
+ original_map[blink::IdentifiableSurface::FromMetricHash(100)] = 5;
+ original_map[blink::IdentifiableSurface::FromMetricHash(UINT64_C(1) << 55)] =
+ 5;
+
+ auto encoded = EncodeIdentifiabilityFieldTrialParam(original_map);
+ EXPECT_EQ(std::string("100;5,36028797018963968;5"), encoded);
+
+ auto decoded_map = DecodeIdentifiabilityFieldTrialParam<
+ std::map<blink::IdentifiableSurface, int>>(encoded);
+ EXPECT_EQ(original_map, decoded_map);
+}
+
+TEST(FieldTrialParamConversionsTest, FieldTrialParam_Type) {
+ std::map<blink::IdentifiableSurface::Type, int> original_map;
+ original_map[blink::IdentifiableSurface::Type::kReservedInternal] = 6;
+ original_map[blink::IdentifiableSurface::Type::kWebFeature] = 5;
+
+ auto encoded = EncodeIdentifiabilityFieldTrialParam(original_map);
+ EXPECT_EQ(std::string("0;6,1;5"), encoded);
+
+ auto decoded_map = DecodeIdentifiabilityFieldTrialParam<
+ std::map<blink::IdentifiableSurface::Type, int>>(encoded);
+ EXPECT_EQ(original_map, decoded_map);
+}
+
+TEST(FieldTrialParamConversionsTest, DecodeBadSurface) {
+ auto decoded_surface = blink::IdentifiableSurface();
+ EXPECT_FALSE(DecodeIdentifiabilityType("foo", &decoded_surface));
+ EXPECT_FALSE(DecodeIdentifiabilityType("-100", &decoded_surface));
+ EXPECT_FALSE(DecodeIdentifiabilityType("100000000000000000000000000",
+ &decoded_surface));
+}
+
+TEST(FieldTrialParamConversionsTest, DecodeBadType) {
+ auto decoded_type = blink::IdentifiableSurface::Type::kReservedInternal;
+ EXPECT_FALSE(DecodeIdentifiabilityType("foo", &decoded_type));
+ EXPECT_FALSE(DecodeIdentifiabilityType("-100", &decoded_type));
+ EXPECT_FALSE(DecodeIdentifiabilityType("256", &decoded_type));
+}
diff --git a/chromium/chrome/common/privacy_budget/privacy_budget_features.cc b/chromium/chrome/common/privacy_budget/privacy_budget_features.cc
new file mode 100644
index 00000000000..9571caa6fc8
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/privacy_budget_features.cc
@@ -0,0 +1,33 @@
+// Copyright 2020 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.
+
+#include "chrome/common/privacy_budget/privacy_budget_features.h"
+
+namespace features {
+
+const base::Feature kIdentifiabilityStudy = {"IdentifiabilityStudy",
+ base::FEATURE_DISABLED_BY_DEFAULT};
+
+const base::FeatureParam<int> kIdentifiabilityStudyGeneration = {
+ &kIdentifiabilityStudy, "Gen", 0};
+
+const base::FeatureParam<std::string> kIdentifiabilityStudyBlockedMetrics = {
+ &kIdentifiabilityStudy, "BlockedHashes", ""};
+
+const base::FeatureParam<std::string> kIdentifiabilityStudyBlockedTypes = {
+ &kIdentifiabilityStudy, "BlockedTypes", ""};
+
+const base::FeatureParam<int> kIdentifiabilityStudySurfaceSelectionRate = {
+ &kIdentifiabilityStudy, "Rho", 0};
+
+const base::FeatureParam<int> kIdentifiabilityStudyMaxSurfaces = {
+ &kIdentifiabilityStudy, "Max", kMaxIdentifiabilityStudyMaxSurfaces};
+
+const base::FeatureParam<std::string> kIdentifiabilityStudyPerSurfaceSettings =
+ {&kIdentifiabilityStudy, "HashRate", ""};
+
+const base::FeatureParam<std::string> kIdentifiabilityStudyPerTypeSettings = {
+ &kIdentifiabilityStudy, "TypeRate", ""};
+
+} // namespace features
diff --git a/chromium/chrome/common/privacy_budget/privacy_budget_features.h b/chromium/chrome/common/privacy_budget/privacy_budget_features.h
new file mode 100644
index 00000000000..ec540c323ec
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/privacy_budget_features.h
@@ -0,0 +1,114 @@
+// Copyright 2020 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.
+
+#ifndef CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_FEATURES_H_
+#define CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_FEATURES_H_
+
+#include <string>
+
+#include "base/feature_list.h"
+#include "base/metrics/field_trial_params.h"
+
+namespace features {
+
+// # Encoding of IdentifiableSurfaces:
+//
+// An IdentifiableSurface is encoded as the decimal representation of it's
+// ToUkmMetricHash() result.
+
+// Parent feature for all identifiability study logic.
+//
+// If the feature is disabled, then this browser instance will not be
+// participating in the identifiability study. I.e. no identifiability metrics
+// will be recorded or reported.
+//
+// Enabling the feature doesn't automatically make this client part of the study
+// either. See documentation for IdentifiabilityStudySettings for a full list of
+// the criteria that contributes to that decision.
+extern const base::Feature kIdentifiabilityStudy;
+
+// Each time the key study parameters change, the study generation also
+// increments. Reporting the study generation alongside metrics allows the data
+// from different study generations to be grouped independently.
+//
+// Changes to the study generation resets all persisted state for the
+// identifiability study.
+//
+// Parameter name: "Gen"
+// Parameter type: int
+extern const base::FeatureParam<int> kIdentifiabilityStudyGeneration;
+
+// Surfaces that should be excluded from reports.
+//
+// Parameter name: "BlockedHashes"
+// Parameter type: Comma separated list of decimal integers, each of which
+// represents an IdentifiableSurface.
+//
+// E.g.:
+// * "258, 257" : Matches IdentifiableSurface::FromTypeAndInput(kWebFeature, 1)
+// and IdentifiableSurface::FromTypeAndInput(kWebFeature, 2)
+extern const base::FeatureParam<std::string>
+ kIdentifiabilityStudyBlockedMetrics;
+
+// Surface types that should be excluded from reports.
+//
+// Parameter name: "BlockedTypes"
+// Parameter type: Comma separated list of decimal integers, each of which
+// represents an IdentifiableSurface::Type.
+//
+// E.g.:
+// * "1, 2" : Matches all surfaces with types kWebFeature and kCanvasReadback.
+extern const base::FeatureParam<std::string> kIdentifiabilityStudyBlockedTypes;
+
+// Base selection rate for surfaces that don't have a per-surface selection
+// rate. Rates are always represented as the denominator of a 1-in-N selection.
+//
+// Parameter name: "Rho"
+// Parameter type: int
+extern const base::FeatureParam<int> kIdentifiabilityStudySurfaceSelectionRate;
+
+// Largest meaningful sampling denominator. Picked out of hat.
+constexpr int kMaxIdentifiabilityStudySurfaceSelectionRate = 1000000;
+
+// The maximum number of surfaces that can be included in the identifiability
+// study.
+//
+// Parameter name: "Max"
+// Parameter type: int
+extern const base::FeatureParam<int> kIdentifiabilityStudyMaxSurfaces;
+
+// This is a hardcoded maximum for the number of identifiable surfaces that
+// can be reported for a user. The actual ceiling for active surfaces cannot
+// exceed this value even if it's sent via a server-side configuration.
+//
+// In other words this is the maximum value that can be configured via
+// `kIdentifiabilityStudyMaxSurfaces`. Hence it's the
+// `kMaxIdentifiabilityStudyMaxSurfaces`.
+constexpr int kMaxIdentifiabilityStudyMaxSurfaces = 10;
+
+// Selection rate for clusters of related surfaces.
+//
+// Parameter name: "HashRate"
+// Parameter type: Comma separated list of <filter-string>;<rate> pairs.
+//
+// E.g.:
+// * "257;800" : Sets the selection rate to 1-in-800 for
+// IdentifiableSurface::FromTypeAndInput(kWebFeature, 1).
+extern const base::FeatureParam<std::string>
+ kIdentifiabilityStudyPerSurfaceSettings;
+
+// Selection rate for clusters of related surfaces.
+//
+// Parameter name: "TypeRate"
+// Parameter type: Comma separated list of <filter-string>;<rate> pairs.
+//
+// E.g.:
+// * "2;1000" : Sets the selection rate to 1-in-1000 for *all* surfaces with
+// type kCanvasReadback.
+extern const base::FeatureParam<std::string>
+ kIdentifiabilityStudyPerTypeSettings;
+
+} // namespace features
+
+#endif // CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_FEATURES_H_
diff --git a/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.cc b/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.cc
new file mode 100644
index 00000000000..fea8329a502
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.cc
@@ -0,0 +1,55 @@
+// Copyright 2020 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.
+
+#include "chrome/common/privacy_budget/privacy_budget_settings_provider.h"
+
+#include <memory>
+
+#include "base/stl_util.h"
+#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
+#include "chrome/common/privacy_budget/privacy_budget_features.h"
+#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
+
+PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider()
+ : blocked_surfaces_(
+ DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceSet>(
+ features::kIdentifiabilityStudyBlockedMetrics.Get())),
+ blocked_types_(
+ DecodeIdentifiabilityFieldTrialParam<IdentifiableSurfaceTypeSet>(
+ features::kIdentifiabilityStudyBlockedTypes.Get())),
+
+ // In practice there's really no point in enabling the feature with a max
+ // active surface count of 0.
+ enabled_(base::FeatureList::IsEnabled(features::kIdentifiabilityStudy) &&
+ features::kIdentifiabilityStudySurfaceSelectionRate.Get() > 0) {}
+
+PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider(
+ const PrivacyBudgetSettingsProvider&) = default;
+PrivacyBudgetSettingsProvider::PrivacyBudgetSettingsProvider(
+ PrivacyBudgetSettingsProvider&&) = default;
+PrivacyBudgetSettingsProvider::~PrivacyBudgetSettingsProvider() = default;
+
+bool PrivacyBudgetSettingsProvider::IsActive() const {
+ return enabled_;
+}
+
+bool PrivacyBudgetSettingsProvider::IsAnyTypeOrSurfaceBlocked() const {
+ return !blocked_surfaces_.empty() || !blocked_types_.empty();
+}
+
+bool PrivacyBudgetSettingsProvider::IsSurfaceAllowed(
+ blink::IdentifiableSurface surface) const {
+ return !base::Contains(blocked_surfaces_, surface) &&
+ IsTypeAllowed(surface.GetType());
+}
+
+bool PrivacyBudgetSettingsProvider::IsTypeAllowed(
+ blink::IdentifiableSurface::Type type) const {
+ return !base::Contains(blocked_types_, type);
+}
+
+std::unique_ptr<PrivacyBudgetSettingsProvider>
+PrivacyBudgetSettingsProvider::Clone() const {
+ return std::make_unique<PrivacyBudgetSettingsProvider>(*this);
+}
diff --git a/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.h b/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.h
new file mode 100644
index 00000000000..94b05f29a9e
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/privacy_budget_settings_provider.h
@@ -0,0 +1,80 @@
+// Copyright 2020 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.
+
+#ifndef CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_SETTINGS_PROVIDER_H_
+#define CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_SETTINGS_PROVIDER_H_
+
+#include <memory>
+#include <unordered_set>
+
+#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings_provider.h"
+#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
+
+// A IdentifiabilityStudySettingsProvider that's based on the identifiability
+// study feature flags and field trial configuration.
+//
+// These features and field trial parameters are found in
+// privacy_budget_features.h.
+//
+// In the browser process these settings are used to filter out metrics that
+// should be excluded from the study. In the renderer they are used to prevent
+// certain surfaces from being sampled at all.
+//
+// Note: The ONLY parameters that should be exposed to the renderer are those
+// that are shared across a large number of clients since it is possible to
+// indirectly observe the set of surfaces that are sampled. Thus the set of
+// sampled surfaces itself could become an identifier.
+//
+// Renderer-exposed controls are meant to act as a granular kill switches in
+// cases where the act of sampling itself has unforeseen adverse side-effects.
+// Filtering done in the browser are privacy controls and cannot address
+// issues arising at the point of sampling.
+class PrivacyBudgetSettingsProvider final
+ : public blink::IdentifiabilityStudySettingsProvider {
+ public:
+ using IdentifiableSurfaceSet =
+ std::unordered_set<blink::IdentifiableSurface,
+ blink::IdentifiableSurfaceHash>;
+ using IdentifiableSurfaceTypeSet =
+ std::unordered_set<blink::IdentifiableSurface::Type>;
+
+ PrivacyBudgetSettingsProvider();
+ PrivacyBudgetSettingsProvider(const PrivacyBudgetSettingsProvider&);
+ PrivacyBudgetSettingsProvider(PrivacyBudgetSettingsProvider&&);
+ ~PrivacyBudgetSettingsProvider() override;
+
+ bool operator=(const PrivacyBudgetSettingsProvider&) const = delete;
+ bool operator=(const PrivacyBudgetSettingsProvider&&) const = delete;
+
+ // blink::IdentifiabilityStudySettingsProvider
+ bool IsActive() const override;
+ bool IsAnyTypeOrSurfaceBlocked() const override;
+ bool IsSurfaceAllowed(blink::IdentifiableSurface surface) const override;
+ bool IsTypeAllowed(blink::IdentifiableSurface::Type type) const override;
+
+ const IdentifiableSurfaceSet& blocked_surfaces() const {
+ return blocked_surfaces_;
+ }
+ const IdentifiableSurfaceTypeSet& blocked_types() const {
+ return blocked_types_;
+ }
+
+ // Useful for passing these around.
+ std::unique_ptr<PrivacyBudgetSettingsProvider> Clone() const;
+
+ private:
+ // Set of identifiable surfaces for which we will NOT collect metrics. This
+ // list is server controlled.
+ const IdentifiableSurfaceSet blocked_surfaces_;
+
+ // Set of identifiable surface types for which we will NOT collect metrics.
+ // This list is server controlled.
+ const IdentifiableSurfaceTypeSet blocked_types_;
+
+ // True if identifiability study is enabled. If this field is false, then none
+ // of the other values are applicable.
+ const bool enabled_ = false;
+};
+
+#endif // CHROME_COMMON_PRIVACY_BUDGET_PRIVACY_BUDGET_SETTINGS_PROVIDER_H_
diff --git a/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.cc b/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.cc
new file mode 100644
index 00000000000..3d92b507d28
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.cc
@@ -0,0 +1,90 @@
+// Copyright 2020 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.
+
+#include "chrome/common/privacy_budget/scoped_privacy_budget_config.h"
+
+#include "chrome/common/privacy_budget/field_trial_param_conversions.h"
+#include "chrome/common/privacy_budget/privacy_budget_features.h"
+#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
+#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
+
+namespace test {
+
+ScopedPrivacyBudgetConfig::Parameters::Parameters() = default;
+ScopedPrivacyBudgetConfig::Parameters::Parameters(const Parameters&) = default;
+ScopedPrivacyBudgetConfig::Parameters::Parameters(Parameters&&) = default;
+ScopedPrivacyBudgetConfig::Parameters::~Parameters() = default;
+
+ScopedPrivacyBudgetConfig::~ScopedPrivacyBudgetConfig() = default;
+ScopedPrivacyBudgetConfig::ScopedPrivacyBudgetConfig() = default;
+
+ScopedPrivacyBudgetConfig::ScopedPrivacyBudgetConfig(
+ const Parameters& parameters) {
+ Apply(parameters);
+}
+
+ScopedPrivacyBudgetConfig::ScopedPrivacyBudgetConfig(Presets presets) {
+ switch (presets) {
+ case kEnable:
+ Apply(Parameters());
+ break;
+
+ case kDisable: {
+ Parameters parameters;
+ parameters.enabled = false;
+ Apply(parameters);
+ break;
+ }
+ }
+}
+
+void ScopedPrivacyBudgetConfig::Apply(const Parameters& parameters) {
+ blink::IdentifiabilityStudySettings::ResetStateForTesting();
+
+ if (!parameters.enabled) {
+ scoped_feature_list_.InitAndDisableFeature(features::kIdentifiabilityStudy);
+ return;
+ }
+
+ Parameters defaults;
+
+ base::FieldTrialParams ftp;
+
+ ftp.insert({features::kIdentifiabilityStudyGeneration.name,
+ base::NumberToString(parameters.generation)});
+
+ if (!parameters.blocked_surfaces.empty()) {
+ ftp.insert(
+ {features::kIdentifiabilityStudyBlockedMetrics.name,
+ EncodeIdentifiabilityFieldTrialParam(parameters.blocked_surfaces)});
+ }
+ if (!parameters.blocked_types.empty()) {
+ ftp.insert(
+ {features::kIdentifiabilityStudyBlockedTypes.name,
+ EncodeIdentifiabilityFieldTrialParam(parameters.blocked_types)});
+ }
+
+ ftp.insert({features::kIdentifiabilityStudySurfaceSelectionRate.name,
+ base::NumberToString(parameters.surface_selection_rate)});
+
+ if (parameters.max_surfaces != defaults.max_surfaces) {
+ ftp.insert({features::kIdentifiabilityStudyMaxSurfaces.name,
+ base::NumberToString(parameters.max_surfaces)});
+ }
+ if (!parameters.per_surface_sampling_rate.empty()) {
+ ftp.insert({features::kIdentifiabilityStudyPerSurfaceSettings.name,
+ EncodeIdentifiabilityFieldTrialParam(
+ parameters.per_surface_sampling_rate)});
+ }
+ if (!parameters.per_type_sampling_rate.empty()) {
+ ftp.insert({features::kIdentifiabilityStudyPerTypeSettings.name,
+ EncodeIdentifiabilityFieldTrialParam(
+ parameters.per_type_sampling_rate)});
+ }
+
+ scoped_feature_list_.InitAndEnableFeatureWithParameters(
+ features::kIdentifiabilityStudy, ftp);
+}
+
+} // namespace test
diff --git a/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.h b/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.h
new file mode 100644
index 00000000000..d84fd647599
--- /dev/null
+++ b/chromium/chrome/common/privacy_budget/scoped_privacy_budget_config.h
@@ -0,0 +1,94 @@
+// Copyright 2020 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.
+
+#ifndef CHROME_COMMON_PRIVACY_BUDGET_SCOPED_PRIVACY_BUDGET_CONFIG_H_
+#define CHROME_COMMON_PRIVACY_BUDGET_SCOPED_PRIVACY_BUDGET_CONFIG_H_
+
+#include <limits>
+#include <map>
+#include <vector>
+
+#include "base/macros.h"
+#include "base/test/scoped_feature_list.h"
+#include "third_party/blink/public/common/privacy_budget/identifiable_surface.h"
+
+namespace test {
+
+// Configures the privacy budget feature settings for testing. One can also
+// configure the service manually by setting the global feature lists
+// directly. This class is merely a convenience.
+//
+// For testing only.
+//
+// Note 1: Since we are changing feature lists, the same caveats as
+// base::test::ScopedFeatureList apply. E.g. The Apply() method should be
+// called prior to starting the threads in multi threaded environments.
+//
+// Note 2: The configuration applied by this class is *scoped*. The destructor
+// reverts the configuration changes.
+class ScopedPrivacyBudgetConfig {
+ public:
+ // These fields correspond to the equivalent features described in
+ // privacy_budget_features.h
+ //
+ // The default values enable the identifiability study with a sampling rate of
+ // 1, which means every surface is included in UKM reports.
+ struct Parameters {
+ Parameters();
+ Parameters(const Parameters&);
+ Parameters(Parameters&&);
+ ~Parameters();
+
+ bool enabled = true;
+ int generation = 1;
+
+ std::vector<blink::IdentifiableSurface> blocked_surfaces;
+ std::vector<blink::IdentifiableSurface::Type> blocked_types;
+ int surface_selection_rate = 1;
+ int max_surfaces = std::numeric_limits<int>::max();
+ std::map<blink::IdentifiableSurface, int> per_surface_sampling_rate;
+ std::map<blink::IdentifiableSurface::Type, int> per_type_sampling_rate;
+ };
+
+ enum Presets {
+ // Represents the default state of `Parameters` which enables the study with
+ // the following settings:
+ //
+ // * `generation` = 1
+ // * `surface_selection_rate`= 1 (i.e. includes every surface)
+ // * `max_surfaces` = <very large number> (i.e. unlimited)
+ kEnable,
+
+ // Disables the study. The other parameters are undefined and should not be
+ // relied upon.
+ kDisable
+ };
+
+ // Doesn't do anything until Apply() is called.
+ ScopedPrivacyBudgetConfig();
+
+ // Applies the configuration indicated by `preset`.
+ explicit ScopedPrivacyBudgetConfig(Presets preset);
+
+ // Constructs and applies the configuration described in `parameters`. No need
+ // to call Apply()
+ explicit ScopedPrivacyBudgetConfig(const Parameters& parameters);
+
+ ~ScopedPrivacyBudgetConfig();
+
+ // Apply the configuration as described in `parameters`. Should only be called
+ // once.
+ void Apply(const Parameters& parameters);
+
+ ScopedPrivacyBudgetConfig(const ScopedPrivacyBudgetConfig&) = delete;
+ ScopedPrivacyBudgetConfig& operator=(const ScopedPrivacyBudgetConfig&) =
+ delete;
+
+ private:
+ base::test::ScopedFeatureList scoped_feature_list_;
+};
+
+} // namespace test
+
+#endif // CHROME_COMMON_PRIVACY_BUDGET_SCOPED_PRIVACY_BUDGET_CONFIG_H_
diff --git a/chromium/chrome/common/profiler/stack_sampling_browsertest.cc b/chromium/chrome/common/profiler/stack_sampling_browsertest.cc
index 00726f62072..4aed0137388 100644
--- a/chromium/chrome/common/profiler/stack_sampling_browsertest.cc
+++ b/chromium/chrome/common/profiler/stack_sampling_browsertest.cc
@@ -161,3 +161,10 @@ IN_PROC_BROWSER_TEST_F(StackSamplingBrowserTest,
metrics::RENDERER_PROCESS,
metrics::COMPOSITOR_THREAD));
}
+
+IN_PROC_BROWSER_TEST_F(StackSamplingBrowserTest,
+ NetworkServiceProcessIOThread) {
+ EXPECT_TRUE(WaitForProfile(metrics::SampledProfile::PROCESS_STARTUP,
+ metrics::NETWORK_SERVICE_PROCESS,
+ metrics::IO_THREAD));
+}
diff --git a/chromium/chrome/common/profiler/stack_sampling_configuration.cc b/chromium/chrome/common/profiler/stack_sampling_configuration.cc
index 17f60142b77..647dbf08ec9 100644
--- a/chromium/chrome/common/profiler/stack_sampling_configuration.cc
+++ b/chromium/chrome/common/profiler/stack_sampling_configuration.cc
@@ -14,6 +14,7 @@
#include "components/version_info/version_info.h"
#include "content/public/common/content_switches.h"
#include "extensions/buildflags/buildflags.h"
+#include "services/service_manager/sandbox/sandbox.h"
#if defined(OS_ANDROID)
#include "chrome/android/modules/stack_unwinder/public/module.h"
@@ -107,7 +108,6 @@ StackSamplingConfiguration::GetSamplingParams() const {
base::TimeDelta::FromSeconds(IsBrowserTestModeEnabled() ? 1 : 30);
params.sampling_interval = base::TimeDelta::FromMilliseconds(100);
params.samples_per_profile = duration / params.sampling_interval;
- params.keep_consistent_sampling_interval = true;
return params;
}
@@ -171,6 +171,11 @@ void StackSamplingConfiguration::AppendCommandLineSwitchForChildProcess(
if (!enable)
return;
if (process_type == switches::kGpuProcess ||
+ (process_type == switches::kUtilityProcess &&
+ // The network service is the only utility process that is profiled for
+ // now.
+ service_manager::SandboxTypeFromCommandLine(*command_line) ==
+ service_manager::SandboxType::kNetwork) ||
(process_type == switches::kRendererProcess &&
// Do not start the profiler for extension processes since profiling the
// compositor thread in them is not useful.
@@ -222,6 +227,14 @@ StackSamplingConfiguration::GenerateConfiguration() {
if (!IsProfilerSupportedForPlatformAndChannel())
return PROFILE_DISABLED;
+#if defined(OS_MACOSX)
+ // TODO(https://crbug.com/1098119): Fix unwinding on OS X 10.16. The OS has
+ // moved all system libraries into the dyld shared cache and this seems to
+ // break the sampling profiler.
+ if (base::mac::IsOSLaterThan10_15_DontCallThis())
+ return PROFILE_DISABLED;
+#endif
+
#if defined(OS_ANDROID)
// Allow profiling if the Android Java/native unwinder module is available at
// initialization time. Otherwise request that it be installed for use on the
diff --git a/chromium/chrome/common/profiler/thread_profiler.cc b/chromium/chrome/common/profiler/thread_profiler.cc
index f32a9ef3a1d..7a4d3ce9483 100644
--- a/chromium/chrome/common/profiler/thread_profiler.cc
+++ b/chromium/chrome/common/profiler/thread_profiler.cc
@@ -6,6 +6,7 @@
#include <string>
#include <utility>
+#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
@@ -25,6 +26,21 @@
#include "content/public/common/content_switches.h"
#include "content/public/common/service_names.mojom.h"
#include "services/service_manager/embedder/switches.h"
+#include "services/service_manager/sandbox/sandbox.h"
+
+#if defined(OS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)
+#include "base/android/apk_assets.h"
+#include "base/files/memory_mapped_file.h"
+#include "base/profiler/arm_cfi_table.h"
+#include "base/profiler/chrome_unwinder_android.h"
+#include "chrome/android/modules/stack_unwinder/public/module.h"
+
+extern "C" {
+// The address of |__executable_start| is the base address of the executable or
+// shared library.
+extern char __executable_start;
+}
+#endif // defined(OS_ANDROID)
using CallStackProfileBuilder = metrics::CallStackProfileBuilder;
using CallStackProfileParams = metrics::CallStackProfileParams;
@@ -51,8 +67,13 @@ CallStackProfileParams::Process GetProcess() {
return CallStackProfileParams::RENDERER_PROCESS;
if (process_type == switches::kGpuProcess)
return CallStackProfileParams::GPU_PROCESS;
- if (process_type == switches::kUtilityProcess)
+ if (process_type == switches::kUtilityProcess) {
+ auto sandbox_type =
+ service_manager::SandboxTypeFromCommandLine(*command_line);
+ if (sandbox_type == service_manager::SandboxType::kNetwork)
+ return CallStackProfileParams::NETWORK_SERVICE_PROCESS;
return CallStackProfileParams::UTILITY_PROCESS;
+ }
if (process_type == service_manager::switches::kZygoteProcess)
return CallStackProfileParams::ZYGOTE_PROCESS;
if (process_type == switches::kPpapiPluginProcess)
@@ -62,6 +83,69 @@ CallStackProfileParams::Process GetProcess() {
return CallStackProfileParams::UNKNOWN_PROCESS;
}
+const base::RepeatingCallback<std::vector<std::unique_ptr<base::Unwinder>>()>&
+GetCoreUnwindersFactory() {
+ const auto create_unwinders_factory = []() {
+#if defined(OS_ANDROID) && BUILDFLAG(ENABLE_ARM_CFI_TABLE)
+ static constexpr char kCfiFileName[] = "assets/unwind_cfi_32";
+
+ // The module is loadable if the profiler is enabled for the current
+ // process.
+ CHECK(StackSamplingConfiguration::Get()
+ ->IsProfilerEnabledForCurrentProcess());
+
+ class UnwindersFactory {
+ public:
+ UnwindersFactory()
+ : module_(stack_unwinder::Module::Load()),
+ memory_regions_map_(module_->CreateMemoryRegionsMap()) {
+ base::MemoryMappedFile::Region cfi_region;
+ int fd = base::android::OpenApkAsset(kCfiFileName, &cfi_region);
+ DCHECK(fd >= 0);
+ bool mapped_file_ok =
+ chrome_cfi_file_.Initialize(base::File(fd), cfi_region);
+ DCHECK(mapped_file_ok);
+ chrome_cfi_table_ = base::ArmCFITable::Parse(
+ {chrome_cfi_file_.data(), chrome_cfi_file_.length()});
+ DCHECK(chrome_cfi_table_);
+ }
+ UnwindersFactory(const UnwindersFactory&) = delete;
+ UnwindersFactory& operator=(const UnwindersFactory&) = delete;
+
+ std::vector<std::unique_ptr<base::Unwinder>> Run() {
+ std::vector<std::unique_ptr<base::Unwinder>> unwinders;
+ unwinders.push_back(module_->CreateNativeUnwinder(
+ memory_regions_map_.get(),
+ reinterpret_cast<uintptr_t>(&__executable_start)));
+ unwinders.push_back(std::make_unique<base::ChromeUnwinderAndroid>(
+ chrome_cfi_table_.get(),
+ reinterpret_cast<uintptr_t>(&__executable_start)));
+ return unwinders;
+ }
+
+ private:
+ const std::unique_ptr<stack_unwinder::Module> module_;
+ const std::unique_ptr<stack_unwinder::MemoryRegionsMap>
+ memory_regions_map_;
+ base::MemoryMappedFile chrome_cfi_file_;
+ std::unique_ptr<base::ArmCFITable> chrome_cfi_table_;
+ };
+
+ return base::BindRepeating(&UnwindersFactory::Run,
+ std::make_unique<UnwindersFactory>());
+#else
+ return base::BindRepeating(
+ []() -> std::vector<std::unique_ptr<base::Unwinder>> { return {}; });
+#endif
+ };
+
+ static base::NoDestructor<
+ base::RepeatingCallback<std::vector<std::unique_ptr<base::Unwinder>>()>>
+ native_unwinder_factory(create_unwinders_factory());
+
+ return *native_unwinder_factory;
+}
+
} // namespace
// The scheduler works by splitting execution time into repeated periods such
@@ -234,12 +318,14 @@ ThreadProfiler::ThreadProfiler(
const base::StackSamplingProfiler::SamplingParams sampling_params =
StackSamplingConfiguration::Get()->GetSamplingParams();
+
startup_profiler_ = std::make_unique<StackSamplingProfiler>(
base::GetSamplingProfilerCurrentThreadToken(), sampling_params,
std::make_unique<CallStackProfileBuilder>(
CallStackProfileParams(GetProcess(), thread,
CallStackProfileParams::PROCESS_STARTUP),
- work_id_recorder_.get()));
+ work_id_recorder_.get()),
+ GetCoreUnwindersFactory().Run());
startup_profiler_->Start();
@@ -303,7 +389,8 @@ void ThreadProfiler::StartPeriodicSamplingCollection() {
work_id_recorder_.get(),
base::BindOnce(&ThreadProfiler::OnPeriodicCollectionCompleted,
owning_thread_task_runner_,
- weak_factory_.GetWeakPtr())));
+ weak_factory_.GetWeakPtr())),
+ GetCoreUnwindersFactory().Run());
if (aux_unwinder_factory_)
periodic_profiler_->AddAuxUnwinder(aux_unwinder_factory_.Run());
diff --git a/chromium/chrome/common/profiler/thread_profiler.h b/chromium/chrome/common/profiler/thread_profiler.h
index 6302c75fa2d..6c2b4f8b463 100644
--- a/chromium/chrome/common/profiler/thread_profiler.h
+++ b/chromium/chrome/common/profiler/thread_profiler.h
@@ -7,6 +7,7 @@
#include <memory>
+#include "base/callback.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/profiler/stack_sampling_profiler.h"
diff --git a/chromium/chrome/common/qr_code_generator/qr_code_generator.cc b/chromium/chrome/common/qr_code_generator/qr_code_generator.cc
index 7053c76ec2f..5c57f5fcc3f 100644
--- a/chromium/chrome/common/qr_code_generator/qr_code_generator.cc
+++ b/chromium/chrome/common/qr_code_generator/qr_code_generator.cc
@@ -6,29 +6,151 @@
#include <string.h>
+#include <ostream>
+
#include "base/check_op.h"
+#include "base/notreached.h"
+
+using GeneratedCode = QRCodeGenerator::GeneratedCode;
+using QRVersionInfo = QRCodeGenerator::QRVersionInfo;
+
+namespace {
+// Default version five QR Code.
+constexpr int kVersionDefault = 5;
+// Extended-length QR code version used by service.
+constexpr int kVersionExtended = 7;
+// Threshold for switching between the two supported versions.
+constexpr int kLargeVersionThresholdLength = 84;
+} // namespace
+
+// TODO(skare): tracking some items to resolve before submit in this block.
+// - In the QRVersionInfo comment, "Error correction group" may not be a formal
+// term in the spec. OK?
+// if so, change naming: Group 0/1 -> Group 1/2 (1-based indexing).
+constexpr QRCodeGenerator::QRVersionInfo version_infos[] = {
+ // Version data is specified as:
+ // version, size, total_bytes.
+ // Error correction Group 0 [see Table 9]
+ // group_bytes, num_segments, segment_data_bytes
+ // Error correction Group 1
+ // [may not apply for all versions, in which case num_segments is 0]
+ // group_bytes, num_segments, segment_data_bytes
+ // total_bytes for the overall code, and {num_segments, segment_data_bytes}
+ // or each group are available on table 9, page 38 of the spec.
+ // group_bytes may be calculated as num_segments*c from the table.
+
+ // 5-M
+ // 134 bytes, as 2 segments of 67.
+ {5, 37, 134, 134, 2, 43, 0, 0, 0},
+
+ // 7-M
+ // 196 bytes, as 4 segments of 49.
+ {7, 45, 196, 196, 4, 31, 0, 0, 0},
+};
-static_assert(QRCodeGenerator::kNumSegments != 0 &&
- QRCodeGenerator::kTotalBytes %
- QRCodeGenerator::kNumSegments ==
- 0,
- "invalid configuration");
+// static
+const QRVersionInfo* QRCodeGenerator::GetVersionInfo(int version) {
+ for (unsigned int i = 0; i < base::size(version_infos); i++) {
+ if (version_infos[i].version == version)
+ return &version_infos[i];
+ }
+ NOTREACHED() << "No version info found for v" << version;
+ return nullptr;
+}
-base::span<uint8_t, QRCodeGenerator::kTotalSize> QRCodeGenerator::Generate(
+// Static assertions for constraints for commonly-used versions.
+static_assert(version_infos[0].num_segments != 0 &&
+ version_infos[0].total_bytes %
+ version_infos[0].num_segments ==
+ 0,
+ "Invalid configuration, version_infos[0]");
+
+static_assert(
+ version_infos[1].total_bytes ==
+ version_infos[1].group_bytes + version_infos[1].group_bytes_1,
+ "Invalid configuration, version_infos[1]. Groups don't sum to total.");
+static_assert(version_infos[1].group_bytes == version_infos[1].segment_bytes() *
+ version_infos[1].num_segments,
+ "Invalid configuration, version_infos[1], group 0.");
+static_assert(version_infos[1].group_bytes_1 ==
+ version_infos[1].segment_bytes_1() *
+ version_infos[1].num_segments_1,
+ "Invalid configuration, version_infos[1], group 1.");
+
+QRCodeGenerator::QRCodeGenerator() = default;
+
+QRCodeGenerator::~QRCodeGenerator() = default;
+
+QRCodeGenerator::GeneratedCode::GeneratedCode() = default;
+QRCodeGenerator::GeneratedCode::GeneratedCode(
+ QRCodeGenerator::GeneratedCode&&) = default;
+QRCodeGenerator::GeneratedCode::~GeneratedCode() = default;
+
+base::Optional<GeneratedCode> QRCodeGenerator::Generate(
base::span<const uint8_t> in) {
- // Can't pass a constexpr to CHECK_LE.
- if (in.size() > kInputBytes) {
- CHECK(false) << "input too long";
+ // We're currently using a minimal set of versions to shrink test surface.
+ // When expanding, take care to validate across different platforms and
+ // a selection of QR Scanner apps.
+ const QRVersionInfo* version_info =
+ (in.size() <= kLargeVersionThresholdLength)
+ ? GetVersionInfo(kVersionDefault)
+ : GetVersionInfo(kVersionExtended);
+ if (version_info != version_info_) {
+ version_info_ = version_info;
+ d_ = std::make_unique<uint8_t[]>(version_info_->total_size());
+ }
+ // Previous data and "set" bits must be cleared.
+ memset(d_.get(), 0, version_info_->total_size());
+
+ // Input data is too long for any supported code.
+ if (in.size() > version_info->input_bytes()) {
+ return base::nullopt;
}
- memset(d_, 0, sizeof(d_));
PutVerticalTiming(6);
PutHorizontalTiming(6);
PutFinder(3, 3);
- PutFinder(3, kSize - 4);
- PutFinder(kSize - 4, 3);
+ PutFinder(3, version_info_->size - 4);
+ PutFinder(version_info_->size - 4, 3);
+
// See table E.1 for the location of alignment symbols.
- PutAlignment(30, 30);
+ if (version_info_->version == kVersionDefault) {
+ PutAlignment(30, 30);
+ } else if (version_info_->version == kVersionExtended) {
+ constexpr int kLocatorIndicesV7[] = {6, 22, 38};
+ constexpr int kLocatorIndicesV13[] = {6, 34, 62};
+ // Constant for now; may differ in higher versions.
+ constexpr int num_locator_coefficients = 3;
+ const int* locator_indices = nullptr;
+ switch (version_info_->version) {
+ case 7:
+ locator_indices = kLocatorIndicesV7;
+ break;
+ case 13:
+ locator_indices = kLocatorIndicesV13;
+ break;
+ default:
+ NOTREACHED() << "No Locator Indices found for v"
+ << version_info_->version;
+ break;
+ }
+
+ int first_index = locator_indices[0];
+ int last_index = locator_indices[num_locator_coefficients - 1];
+
+ for (int i = 0; i < num_locator_coefficients; i++) {
+ for (int j = 0; j < num_locator_coefficients; j++) {
+ int row = locator_indices[i];
+ int col = locator_indices[j];
+ // Aligntment symbols must not overwrite locators.
+ if ((row == first_index && (col == first_index || col == last_index)) ||
+ (row == last_index && col == first_index)) {
+ continue;
+ }
+ PutAlignment(row, col);
+ }
+ }
+ }
// kFormatInformation is the encoded formatting word for the QR code that
// this code generates. See tables 10 and 12.
@@ -41,43 +163,104 @@ base::span<uint8_t, QRCodeGenerator::kTotalSize> QRCodeGenerator::Generate(
constexpr uint16_t kFormatInformation = 0x5b4b;
PutFormatBits(kFormatInformation);
- // QR codes require some framing of the data which requires 12 bits of
- // overhead. Since 12 is not a multiple of eight, a frame-shift of all
+ // Add the mode and character count.
+
+ // QR codes require some framing of the data. This requires:
+ // Version 1-9: 4 bits for mode + 8 bits for char count = 12 bits
+ // Version 10-26: 4 bits for mode + 16 bits for char count = 20 bits
+ // Details are in Table 3.
+ // Since 12 and 20 are not a multiple of eight, a frame-shift of all
// subsequent bytes is required.
- uint8_t prefixed_data[kDataBytes];
- static_assert(kInputBytes < 256, "in too large for 8-bit length");
- const uint8_t len8 = static_cast<uint8_t>(in.size());
- prefixed_data[0] = 0x40 | (len8 >> 4);
- prefixed_data[1] = (len8 << 4);
- if (!in.empty()) {
- prefixed_data[1] |= (in[0] >> 4);
+ size_t data_bytes = version_info_->data_bytes();
+ uint8_t prefixed_data[data_bytes];
+ int framing_offset_bytes = 0;
+ if (version_info->version <= 9) {
+ DCHECK_LT(in.size(), 256u) << "in.size() too large for 8-bit length";
+ const uint8_t len8 = static_cast<uint8_t>(in.size());
+ prefixed_data[0] = 0x40 | (len8 >> 4);
+ prefixed_data[1] = (len8 << 4);
+ if (!in.empty()) {
+ prefixed_data[1] |= (in[0] >> 4);
+ }
+ framing_offset_bytes = 2;
+ } else if (version_info->version <= 26) {
+ DCHECK_LT(in.size(), 0x10000u) << "in.size() too large for 16-bit length";
+ const uint16_t len16 = static_cast<uint16_t>(in.size());
+ prefixed_data[0] = 0x40 | (len16 >> 12);
+ prefixed_data[1] = (len16 >> 4);
+ prefixed_data[2] = (len16 << 4);
+ if (!in.empty()) {
+ prefixed_data[2] |= (in[0] >> 4);
+ }
+ framing_offset_bytes = 3;
+ } else {
+ NOTREACHED() << "Unsupported version in Generate(): "
+ << version_info->version;
}
+
for (size_t i = 0; i < in.size() - 1; i++) {
- prefixed_data[i + 2] = (in[i] << 4) | (in[i + 1] >> 4);
+ prefixed_data[i + framing_offset_bytes] = (in[i] << 4) | (in[i + 1] >> 4);
}
if (!in.empty()) {
- prefixed_data[in.size() + 1] = in[in.size() - 1] << 4;
+ prefixed_data[in.size() + 1] = in[in.size() + 1 - framing_offset_bytes]
+ << 4;
}
// The QR code looks a little odd with fixed padding. Thus replicate the
// message to fill the input.
- for (size_t i = in.size() + 2; i < kInputBytes; i++) {
- prefixed_data[i] = prefixed_data[i % (in.size() + 2)];
+ for (size_t i = in.size() + framing_offset_bytes;
+ i < version_info_->input_bytes(); i++) {
+ prefixed_data[i] = prefixed_data[i % (in.size() + framing_offset_bytes)];
}
// Each segment of input data is expanded with error correcting
// information and then interleaved.
- uint8_t expanded_segments[kNumSegments][kSegmentBytes];
- for (size_t i = 0; i < kNumSegments; i++) {
+
+ // Error Correction for Group 0, present for all versions.
+ size_t num_segments = version_info_->num_segments;
+ size_t segment_bytes = version_info_->segment_bytes();
+ size_t segment_ec_bytes = version_info_->segment_ec_bytes();
+ uint8_t expanded_segments[num_segments][segment_bytes];
+ for (size_t i = 0; i < num_segments; i++) {
AddErrorCorrection(&expanded_segments[i][0],
- &prefixed_data[kSegmentDataBytes * i]);
+ &prefixed_data[version_info_->segment_data_bytes * i],
+ segment_bytes, segment_ec_bytes);
+ }
+
+ // Error Correction for Group 1, present for some versions.
+ // Factor out the number of bytes written by the prior group.
+ size_t num_segments_1 = version_info_->num_segments_1;
+ size_t segment_bytes_1 = version_info_->segment_bytes_1();
+ // TODO(skare): Reenable when extendiong to v13.
+ // Additionally do not use a zero-length array; nonstandard.
+ /*
+ int group_data_offset = version_info_->segment_data_bytes * num_segments;
+ size_t segment_ec_bytes_1 = version_info_->segment_ec_bytes_1();
+ uint8_t expanded_segments_1[num_segments_1][segment_bytes_1];
+ if (version_info_->num_segments_1 > 0) {
+ for (size_t i = 0; i < num_segments_1; i++) {
+ AddErrorCorrection(
+ &expanded_segments_1[i][0],
+ &prefixed_data[group_data_offset +
+ version_info_->segment_data_bytes_1 * i],
+ segment_bytes_1, segment_ec_bytes_1);
+ }
}
+ */
+
+ size_t total_bytes = version_info_->total_bytes;
+ uint8_t interleaved_data[total_bytes];
+ CHECK(total_bytes ==
+ segment_bytes * num_segments + segment_bytes_1 * num_segments_1)
+ << "internal error";
- uint8_t interleaved_data[kTotalBytes];
- static_assert(kTotalBytes == kSegmentBytes * kNumSegments, "internal error");
size_t k = 0;
- for (size_t j = 0; j < kSegmentBytes; j++) {
- for (size_t i = 0; i < kNumSegments; i++) {
+ // Interleave data from all segments.
+ // If we have multiple groups, the later groups may have more bytes in their
+ // segments after we exhaust data in the first group.
+ // TODO(skare): Extend when enabling v13.
+ for (size_t j = 0; j < segment_bytes; j++) {
+ for (size_t i = 0; i < num_segments; i++) {
interleaved_data[k++] = expanded_segments[i][j];
}
}
@@ -89,7 +272,10 @@ base::span<uint8_t, QRCodeGenerator::kTotalSize> QRCodeGenerator::Generate(
// transient.
PutBits(interleaved_data, sizeof(interleaved_data), MaskFunction3);
- return d_;
+ GeneratedCode code;
+ code.data = base::span<uint8_t>(d_.get(), version_info_->total_size());
+ code.qr_size = version_info_->size;
+ return code;
}
// MaskFunction3 implements one of the data-masking functions. See figure 21.
@@ -141,14 +327,14 @@ void QRCodeGenerator::PutAlignment(int x, int y) {
// PutVerticalTiming paints the vertical timing signal.
void QRCodeGenerator::PutVerticalTiming(int x) {
- for (int y = 0; y < kSize; y++) {
+ for (int y = 0; y < version_info_->size; y++) {
at(x, y) = 0b10 | (1 ^ (y & 1));
}
}
// PutVerticalTiming paints the horizontal timing signal.
void QRCodeGenerator::PutHorizontalTiming(int y) {
- for (int x = 0; x < kSize; x++) {
+ for (int x = 0; x < version_info_->size; x++) {
at(x, y) = 0b10 | (1 ^ (x & 1));
}
}
@@ -171,16 +357,49 @@ void QRCodeGenerator::PutFormatBits(const uint16_t format) {
}
v = format;
- for (int x = kSize - 1; x >= kSize - 1 - 7; x--) {
+ for (int x = version_info_->size - 1; x >= version_info_->size - 1 - 7; x--) {
at(x, 8) = 0b10 | (v & 1);
v >>= 1;
}
- at(8, kSize - 1 - 7) = 0b11;
- for (int y = kSize - 1 - 6; y <= kSize - 1; y++) {
+ at(8, version_info_->size - 1 - 7) = 0b11;
+ for (int y = version_info_->size - 1 - 6; y <= version_info_->size - 1; y++) {
at(8, y) = 0b10 | (v & 1);
v >>= 1;
}
+
+ // Version 7 and larger require 18-bit version information taking the form
+ // of 6x3 rectangles above the bottom-left locator and to the left of the
+ // top-right locator.
+ int size = version_info_->size;
+ int version = version_info_->version;
+ int vi_string = 0;
+ switch (version) {
+ case 5:
+ break;
+ case 7:
+ vi_string = 0b000111110010010100;
+ break;
+ case 13:
+ vi_string = 0b001101100001000111;
+ break;
+ default:
+ NOTREACHED() << "No version information string provided for QR v"
+ << version;
+ break;
+ }
+ if (vi_string) {
+ for (int i = 0; i < 6; i++) {
+ for (int j = 0; j < 3; j++) {
+ // Bottom-left rectangle is top-to-bottom, left-to-right
+ at(i, size - 8 - 3 + j) = 0b10 | (vi_string & 1);
+ // Top-right rectangle is left-to-right, top-to-bottom
+ at(size - 8 - 3 + j, i) = 0b10 | (vi_string & 1);
+ // Shift to consider the next bit.
+ vi_string >>= 1;
+ }
+ }
+ }
}
// PutBits writes the given data into the QR code in correct order, avoiding
@@ -223,8 +442,8 @@ void QRCodeGenerator::PutBits(const uint8_t* data,
BitStream stream(data, data_len);
bool going_up = true;
- int x = kSize - 1;
- int y = kSize - 1;
+ int x = version_info_->size - 1;
+ int y = version_info_->size - 1;
for (;;) {
uint8_t& right = at(x, y);
@@ -239,7 +458,7 @@ void QRCodeGenerator::PutBits(const uint8_t* data,
left = stream.Next() ^ mask_func(x - 1, y);
}
- if ((going_up && y == 0) || (!going_up && y == kSize - 1)) {
+ if ((going_up && y == 0) || (!going_up && y == version_info_->size - 1)) {
if (x == 1) {
break;
}
@@ -262,35 +481,35 @@ void QRCodeGenerator::PutBits(const uint8_t* data,
// at returns a reference to the given element of |d_|.
uint8_t& QRCodeGenerator::at(int x, int y) {
DCHECK_LE(0, x);
- DCHECK_LT(x, kSize);
+ DCHECK_LT(x, version_info_->size);
DCHECK_LE(0, y);
- DCHECK_LT(y, kSize);
- return d_[kSize * y + x];
+ DCHECK_LT(y, version_info_->size);
+ return d_[version_info_->size * y + x];
}
// fillAt sets the |len| elements at (x, y) to |value|.
void QRCodeGenerator::fillAt(int x, int y, size_t len, uint8_t value) {
DCHECK_LE(0, x);
- DCHECK_LE(static_cast<int>(x + len), kSize);
+ DCHECK_LE(static_cast<int>(x + len), version_info_->size);
DCHECK_LE(0, y);
- DCHECK_LT(y, kSize);
- memset(&d_[kSize * y + x], value, len);
+ DCHECK_LT(y, version_info_->size);
+ memset(&d_[version_info_->size * y + x], value, len);
}
// copyTo copies |len| elements from |data| to the elements at (x, y).
void QRCodeGenerator::copyTo(int x, int y, const uint8_t* data, size_t len) {
DCHECK_LE(0, x);
- DCHECK_LE(static_cast<int>(x + len), kSize);
+ DCHECK_LE(static_cast<int>(x + len), version_info_->size);
DCHECK_LE(0, y);
- DCHECK_LT(y, kSize);
- memcpy(&d_[kSize * y + x], data, len);
+ DCHECK_LT(y, version_info_->size);
+ memcpy(&d_[version_info_->size * y + x], data, len);
}
// clipped returns a reference to the given element of |d_|, or to
// |clip_dump_| if the coordinates are out of bounds.
uint8_t& QRCodeGenerator::clipped(int x, int y) {
- if (0 <= x && x < kSize && 0 <= y && y < kSize) {
- return d_[kSize * y + x];
+ if (0 <= x && x < version_info_->size && 0 <= y && y < version_info_->size) {
+ return d_[version_info_->size * y + x];
}
return clip_dump_;
}
@@ -324,10 +543,13 @@ uint8_t QRCodeGenerator::GF28Mul(uint16_t a, uint16_t b) {
// AddErrorCorrection writes the Reed-Solomon expanded version of |in| to
// |out|.
-// static
-void QRCodeGenerator::AddErrorCorrection(uint8_t out[kSegmentBytes],
- const uint8_t in[kSegmentDataBytes]) {
- // kGenerator is the product of (z - x^i) for 0 <= i < |kSegmentECBytes|,
+// |out| should have length segment_bytes for the code's version.
+// |in| should have length segment_data_bytes for the code's version.
+void QRCodeGenerator::AddErrorCorrection(uint8_t out[],
+ const uint8_t in[],
+ size_t segment_bytes,
+ size_t segment_ec_bytes) {
+ // kGenerator is the product of (z - x^i) for 0 <= i < |segment_ec_bytes|,
// where x is the term of GF(2^8) and z is the term of a polynomial ring
// over GF(2^8). It's generated with the following Sage script:
//
@@ -348,40 +570,73 @@ void QRCodeGenerator::AddErrorCorrection(uint8_t out[kSegmentBytes],
// coeffs = list(gen)
// gen = [toByte(x) for x in coeffs]
// print 'uint8_t kGenerator[' + str(len(gen)) + '] = {' + str(gen) + '}'
- static constexpr uint8_t kGenerator[kSegmentECBytes + 1] = {
+
+ // Used for 7-M: 18 error correction codewords per block.
+ static std::vector<uint8_t> kGenerator18 = {
+ 146, 217, 67, 32, 75, 173, 82, 73, 220, 240,
+ 215, 199, 175, 149, 113, 183, 251, 239, 1,
+ };
+
+ // Used for 13-M; 22 error correction codewords per block.
+ static std::vector<uint8_t> kGenerator22 = {
+ 245, 145, 26, 230, 218, 86, 253, 67, 123, 29, 137, 28,
+ 40, 69, 189, 19, 244, 182, 176, 131, 179, 89, 1,
+ };
+
+ // Used for 5-M, 24 error correction codewords per block.
+ static std::vector<uint8_t> kGenerator24 = {
117, 144, 217, 127, 247, 237, 1, 206, 43, 61, 72, 130, 73,
229, 150, 115, 102, 216, 237, 178, 70, 169, 118, 122, 1,
};
+ const std::vector<uint8_t>* generator = nullptr;
+ switch (segment_ec_bytes) {
+ case 18:
+ generator = &kGenerator18;
+ break;
+ case 22:
+ generator = &kGenerator22;
+ break;
+ case 24:
+ generator = &kGenerator24;
+ break;
+ default: {
+ NOTREACHED() << "Unsupported Generator Polynomial for segment_ec_bytes: "
+ << segment_ec_bytes;
+ return;
+ }
+ }
+
// The error-correction bytes are the remainder of dividing |in| * x^k by
// |kGenerator|, where |k| is the number of EC codewords. Polynomials here
// are represented in little-endian order, i.e. the value at index |i| is
// the coefficient of z^i.
// Multiplication of |in| by x^k thus just involves moving it up.
- uint8_t remainder[kSegmentBytes];
- memset(remainder, 0, kSegmentECBytes);
+ std::unique_ptr<uint8_t[]> remainder(new uint8_t[segment_bytes]);
+ memset(remainder.get(), 0, segment_ec_bytes);
+ size_t segment_data_bytes = segment_bytes - segment_ec_bytes;
// Reed-Solomon input is backwards. See section 7.5.2.
- for (size_t i = 0; i < kSegmentDataBytes; i++) {
- remainder[kSegmentECBytes + i] = in[kSegmentDataBytes - 1 - i];
+ for (size_t i = 0; i < segment_data_bytes; i++) {
+ remainder[segment_ec_bytes + i] = in[segment_data_bytes - 1 - i];
}
// Progressively eliminate the leading coefficient by subtracting some
- // multiple of |kGenerator| until we have a value smaller than |kGenerator|.
- for (size_t i = kSegmentBytes - 1; i >= kSegmentECBytes; i--) {
- // The leading coefficient of |kGenerator| is 1, so the multiple to
+ // multiple of |generator| until we have a value smaller than |generator|.
+ for (size_t i = segment_bytes - 1; i >= segment_ec_bytes; i--) {
+ // The leading coefficient of |generator| is 1, so the multiple to
// subtract to eliminate the leading term of |remainder| is the value of
// that leading term. The polynomial ring is characteristic two, so
// subtraction is the same as addition, which is XOR.
- for (size_t j = 0; j < sizeof(kGenerator) - 1; j++) {
- remainder[i - kSegmentECBytes + j] ^=
- GF28Mul(kGenerator[j], remainder[i]);
+ for (size_t j = 0; j < generator->size() - 1; j++) {
+ remainder[i - segment_ec_bytes + j] ^=
+ GF28Mul(generator->at(j), remainder[i]);
}
}
- memmove(out, in, kSegmentDataBytes);
+ memmove(out, in, segment_data_bytes);
// Remove the Reed-Solomon remainder again to match QR's convention.
- for (size_t i = 0; i < kSegmentECBytes; i++) {
- out[kSegmentDataBytes + i] = remainder[kSegmentECBytes - 1 - i];
+ for (size_t i = 0; i < segment_ec_bytes; i++) {
+ out[segment_data_bytes + i] = remainder[segment_ec_bytes - 1 - i];
}
}
diff --git a/chromium/chrome/common/qr_code_generator/qr_code_generator.h b/chromium/chrome/common/qr_code_generator/qr_code_generator.h
index e0a9365411e..46a33cc37c1 100644
--- a/chromium/chrome/common/qr_code_generator/qr_code_generator.h
+++ b/chromium/chrome/common/qr_code_generator/qr_code_generator.h
@@ -9,38 +9,134 @@
#include <stdint.h>
#include "base/containers/span.h"
+#include "base/optional.h"
-// QRCodeGenerator generates version five, class M QR codes that carry 84
-// bytes of raw data. References in the following comments refer to ISO 18004
-// (3rd edition).
+// QRCodeGenerator generates class M QR codes of various versions.
+// References in the following comments refer to ISO 18004 (3rd edition).
+// Supports versions up to 26 by adding constants.
class QRCodeGenerator {
public:
- // kSize is the number of "tiles" in each dimension for a v5 QR code. See
- // table 1. (The colored squares in in QR codes are called tiles in the
- // spec.)
- static constexpr int kSize = 37;
- // kTotalSize is the total number of tiles for a v5 QR code, in both
- // directions.
- static constexpr int kTotalSize = kSize * kSize;
- // These values are taken from table 9 (page 38) for a version five, class M
- // QR code. (That table is very badly formatted for version five, the rows in
- // the last column don't line up correctly. The correct value for 5M is
- // (67,43,12).)
- static constexpr size_t kTotalBytes = 134;
- static constexpr size_t kNumSegments = 2;
- static constexpr size_t kSegmentDataBytes = 43;
-
- static constexpr size_t kSegmentBytes = kTotalBytes / kNumSegments;
- static constexpr size_t kSegmentECBytes = kSegmentBytes - kSegmentDataBytes;
- static constexpr size_t kDataBytes = kSegmentDataBytes * kNumSegments;
- // Two bytes of overhead are needed for QR framing.
- static constexpr size_t kInputBytes = kDataBytes - 2;
-
- // Generate generates a QR code containing the given data and returns a
- // pointer to an array of kTotalSize bytes where the least-significant bit of
- // each byte is set if that tile should be "black". The length of |in| must be
- // less than, or equal to, |kInputBytes|.
- base::span<uint8_t, kTotalSize> Generate(base::span<const uint8_t> in);
+ // A structure containing QR version-specific constants and data.
+ // All versions currently use error correction at level M.
+ struct QRVersionInfo {
+ constexpr QRVersionInfo(const int version,
+ const int size,
+ const size_t total_bytes,
+ const size_t group_bytes,
+ const size_t num_segments,
+ const size_t segment_data_bytes,
+ const size_t group_bytes_1,
+ const size_t num_segments_1,
+ const size_t segment_data_bytes_1)
+ : version(version),
+ size(size),
+ total_bytes(total_bytes),
+ group_bytes(group_bytes),
+ num_segments(num_segments),
+ segment_data_bytes(segment_data_bytes),
+ group_bytes_1(group_bytes_1),
+ num_segments_1(num_segments_1),
+ segment_data_bytes_1(segment_data_bytes_1) {}
+
+ // The version of the QR code.
+ const int version;
+
+ // The number of "tiles" in each dimension for a QR code of |version|. See
+ // table 1. (The colored squares in in QR codes are called tiles in the
+ // spec.)
+ const int size;
+
+ // Values taken from Table 9, page 38, for a QR code of version |version|.
+ const size_t total_bytes; // Sum of group_bytes for each group.
+ const size_t group_bytes;
+ const size_t num_segments;
+ const size_t segment_data_bytes;
+ const size_t group_bytes_1;
+ const size_t num_segments_1;
+ const size_t segment_data_bytes_1;
+
+ // Total number of tiles for the QR code, size*size.
+ constexpr int total_size() const { return size * size; }
+
+ constexpr size_t segment_bytes() const {
+ return group_bytes / num_segments;
+ }
+
+ constexpr size_t segment_ec_bytes() const {
+ return segment_bytes() - segment_data_bytes;
+ }
+
+ constexpr size_t data_bytes() const {
+ return segment_data_bytes * num_segments;
+ }
+
+ constexpr size_t segment_bytes_1() const {
+ if (num_segments_1 == 0)
+ return 0;
+ return group_bytes_1 / num_segments_1;
+ }
+
+ constexpr size_t segment_ec_bytes_1() const {
+ return segment_bytes_1() - segment_data_bytes_1;
+ }
+
+ constexpr size_t data_bytes_1() const {
+ return segment_data_bytes_1 * num_segments_1;
+ }
+
+ // Two bytes of overhead are needed for QR framing.
+ // If extending beyond version 26, framing would need to be updated.
+ size_t input_bytes() const {
+ int framing_bytes = version <= 9 ? 2 : 3;
+ return data_bytes() + data_bytes_1() - framing_bytes;
+ }
+
+ DISALLOW_COPY_AND_ASSIGN(QRVersionInfo);
+ };
+
+ // Contains output data for Generate().
+ // The default state contains no data.
+ struct GeneratedCode {
+ public:
+ GeneratedCode();
+ GeneratedCode(GeneratedCode&&);
+ ~GeneratedCode();
+
+ // Pixel data; pointer to an array of bytes, where the least-significant
+ // bit of each byte is set if that tile should be "black".
+ // Clients should ensure four modules of padding when rendering the code.
+ // On error, will not be populated, and will evaluate to false.
+ base::span<uint8_t> data;
+
+ // Width and height (which are equal) of the generated data, in tiles.
+ int qr_size = 0;
+
+ DISALLOW_COPY_AND_ASSIGN(GeneratedCode);
+ };
+
+ // Static parameters for V5 QR codes.
+ // These exist while migrating clients to dynamic sizes.
+ struct V5 {
+ static constexpr int kSize = 37;
+ static constexpr int kTotalSize = kSize * kSize;
+ static constexpr size_t kNumSegments = 2;
+ static constexpr size_t kSegmentDataBytes = 43;
+ static constexpr size_t kDataBytes = kSegmentDataBytes * kNumSegments;
+ static constexpr size_t kInputBytes = kDataBytes - 2;
+ };
+
+ QRCodeGenerator();
+ ~QRCodeGenerator();
+
+ // Returns parameters for different QR code versions, or nullptr if the
+ // version is not supported (you may provide support in the cc file).
+ static const QRVersionInfo* GetVersionInfo(int version);
+
+ // Generates a QR code containing the given data.
+ // The generator will attempt to choose a version that fits the data. The
+ // returned span's length is input-dependent and not known at compile-time in
+ // this case.
+ base::Optional<GeneratedCode> Generate(base::span<const uint8_t> in);
private:
// MaskFunction3 implements one of the data-masking functions. See figure 21.
@@ -88,14 +184,27 @@ class QRCodeGenerator {
// AddErrorCorrection writes the Reed-Solomon expanded version of |in| to
// |out|.
- static void AddErrorCorrection(uint8_t out[kSegmentBytes],
- const uint8_t in[kSegmentDataBytes]);
+ // |out| should have length segment_bytes for the code's version.
+ // |in| should have length segment_data_bytes for the code's version.
+ // |segment_bytes| and |segment_ec_bytes| must be provided for the current
+ // version/level/group.
+ void AddErrorCorrection(uint8_t out[],
+ const uint8_t in[],
+ size_t segment_bytes,
+ size_t segment_ec_bytes);
+
+ // Parameters for the currently-selected version of the QR code.
+ // Generate() will pick a version that can contain enough data.
+ // Unowned; nullptr until initialized in Generate().
+ const QRVersionInfo* version_info_ = nullptr;
// d_ represents a QR code with one byte per pixel. Each byte is one pixel.
// The LSB is set if the pixel is "black". The second bit is set if the pixel
// is part of the structure of the QR code, i.e. finder or alignment symbols,
// timing patterns, or format data.
- uint8_t d_[kSize * kSize];
+ // Initialized and possibly reinitialized in Generate().
+ std::unique_ptr<uint8_t[]> d_;
+
// clip_dump_ is the target of paints that would otherwise fall outside of the
// QR code.
uint8_t clip_dump_;
diff --git a/chromium/chrome/common/qr_code_generator/qr_code_generator_unittest.cc b/chromium/chrome/common/qr_code_generator/qr_code_generator_unittest.cc
index 686a967ea98..20d49e016e3 100644
--- a/chromium/chrome/common/qr_code_generator/qr_code_generator_unittest.cc
+++ b/chromium/chrome/common/qr_code_generator/qr_code_generator_unittest.cc
@@ -13,14 +13,43 @@ TEST(QRCodeGenerator, Generate) {
// run under ASan, this will also check that every byte of the output has been
// written to.
QRCodeGenerator qr;
- uint8_t input[QRCodeGenerator::kInputBytes];
+ uint8_t input[QRCodeGenerator::V5::kInputBytes];
memset(input, 'a', sizeof(input));
- auto qr_data = qr.Generate(input);
+ base::Optional<QRCodeGenerator::GeneratedCode> qr_code = qr.Generate(input);
+ ASSERT_NE(qr_code, base::nullopt);
+ auto& qr_data = qr_code->data;
int index = 0;
- for (int y = 0; y < QRCodeGenerator::kSize; y++) {
- for (int x = 0; x < QRCodeGenerator::kSize; x++) {
+ ASSERT_EQ(qr_data.size(),
+ static_cast<size_t>(QRCodeGenerator::V5::kTotalSize));
+ for (int y = 0; y < QRCodeGenerator::V5::kSize; y++) {
+ for (int x = 0; x < QRCodeGenerator::V5::kSize; x++) {
ASSERT_EQ(0, qr_data[index++] & 0b11111100);
}
}
}
+
+TEST(QRCodeGenerator, GenerateVersionSelection) {
+ // Ensure that dynamic version selection works,
+ // even when reusing the same QR Generator object.
+ // Longer inputs produce longer codes.
+ QRCodeGenerator qr;
+
+ uint8_t input_small[10];
+ memset(input_small, 'a', sizeof(input_small));
+ base::Optional<QRCodeGenerator::GeneratedCode> qr_code_small(
+ qr.Generate(input_small));
+ ASSERT_NE(qr_code_small, base::nullopt);
+ int size_small = qr_code_small->data.size();
+
+ uint8_t input_large[100];
+ memset(input_large, 'a', sizeof(input_large));
+ base::Optional<QRCodeGenerator::GeneratedCode> qr_code_large(
+ qr.Generate(input_large));
+ ASSERT_NE(qr_code_large, base::nullopt);
+ int size_large = qr_code_large->data.size();
+
+ ASSERT_GT(size_small, 0);
+ ASSERT_GT(size_large, 0);
+ ASSERT_GT(size_large, size_small);
+}
diff --git a/chromium/chrome/common/render_messages.h b/chromium/chrome/common/render_messages.h
index ab85c179be4..971aaaa8873 100644
--- a/chromium/chrome/common/render_messages.h
+++ b/chromium/chrome/common/render_messages.h
@@ -45,19 +45,6 @@
IPC_MESSAGE_ROUTED1(ChromeViewMsg_LoadBlockedPlugins,
std::string /* identifier */)
-// JavaScript related messages -----------------------------------------------
-
-#if BUILDFLAG(ENABLE_OFFLINE_PAGES)
-// Message sent from the renderer to the browser to schedule to download the
-// page at a later time.
-IPC_MESSAGE_ROUTED0(ChromeViewHostMsg_DownloadPageLater)
-
-// Message sent from the renderer to the browser to indicate if download button
-// is being shown in error page.
-IPC_MESSAGE_ROUTED1(ChromeViewHostMsg_SetIsShowingDownloadButtonInErrorPage,
- bool /* showing download button */)
-#endif
-
//-----------------------------------------------------------------------------
// Misc messages
// These are messages sent from the renderer to the browser process.
diff --git a/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac.h b/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac.h
index 5f93e6285fb..4d00114f5ad 100644
--- a/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac.h
+++ b/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac.h
@@ -12,7 +12,6 @@
#include <memory>
#include <vector>
-#include "base/logging.h"
#include "base/macros.h"
namespace safe_browsing {
diff --git a/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac_unittest.cc b/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac_unittest.cc
index 5d6d270dbfa..0b95761b30c 100644
--- a/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac_unittest.cc
+++ b/chromium/chrome/common/safe_browsing/mach_o_image_reader_mac_unittest.cc
@@ -8,6 +8,7 @@
#include <libkern/OSByteOrder.h>
#include <mach-o/fat.h>
#include <mach-o/loader.h>
+#include <mach/vm_param.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
diff --git a/chromium/chrome/common/search/ntp_logging_events.h b/chromium/chrome/common/search/ntp_logging_events.h
index c15685d496e..a776c381e34 100644
--- a/chromium/chrome/common/search/ntp_logging_events.h
+++ b/chromium/chrome/common/search/ntp_logging_events.h
@@ -28,8 +28,9 @@ enum NTPLoggingEventType {
// by the single-iframe version of the NTP.
NTP_ALL_TILES_LOADED = 11,
- // Activated by clicking on the fakebox icon. Logged by Voice Search.
- NTP_VOICE_ACTION_ACTIVATE_FAKEBOX = 13,
+ // Activated by clicking on the fakebox or realbox icon. Logged by Voice
+ // Search.
+ NTP_VOICE_ACTION_ACTIVATE_SEARCH_BOX = 13,
// Activated by keyboard shortcut.
NTP_VOICE_ACTION_ACTIVATE_KEYBOARD = 14,
// Close the voice overlay by a user's explicit action.
diff --git a/chromium/chrome/common/secure_origin_whitelist.cc b/chromium/chrome/common/secure_origin_allowlist.cc
index e6a2a3ba1e0..f54ab17ad46 100644
--- a/chromium/chrome/common/secure_origin_whitelist.cc
+++ b/chromium/chrome/common/secure_origin_allowlist.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include "chrome/common/secure_origin_whitelist.h"
+#include "chrome/common/secure_origin_allowlist.h"
#include <set>
#include <string>
@@ -11,7 +11,7 @@
#include "components/prefs/pref_registry_simple.h"
#include "extensions/common/constants.h"
-namespace secure_origin_whitelist {
+namespace secure_origin_allowlist {
std::set<std::string> GetSchemesBypassingSecureContextCheck() {
std::set<std::string> schemes;
@@ -24,4 +24,4 @@ void RegisterPrefs(PrefRegistrySimple* local_state) {
/* default_value */ "");
}
-} // namespace secure_origin_whitelist
+} // namespace secure_origin_allowlist
diff --git a/chromium/chrome/common/secure_origin_whitelist.h b/chromium/chrome/common/secure_origin_allowlist.h
index e55ca47d2fd..9f41c82186d 100644
--- a/chromium/chrome/common/secure_origin_whitelist.h
+++ b/chromium/chrome/common/secure_origin_allowlist.h
@@ -2,23 +2,23 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#ifndef CHROME_COMMON_SECURE_ORIGIN_WHITELIST_H_
-#define CHROME_COMMON_SECURE_ORIGIN_WHITELIST_H_
+#ifndef CHROME_COMMON_SECURE_ORIGIN_ALLOWLIST_H_
+#define CHROME_COMMON_SECURE_ORIGIN_ALLOWLIST_H_
#include <set>
#include <string>
class PrefRegistrySimple;
-namespace secure_origin_whitelist {
+namespace secure_origin_allowlist {
-// Returns a whitelist of schemes that should bypass the Is Privileged Context
+// Returns a allowlist of schemes that should bypass the Is Privileged Context
// check. See http://www.w3.org/TR/powerful-features/#settings-privileged.
std::set<std::string> GetSchemesBypassingSecureContextCheck();
-// Register preferences for Secure Origin Whitelists.
+// Register preferences for Secure Origin Allowlists.
void RegisterPrefs(PrefRegistrySimple* local_state);
-} // namespace secure_origin_whitelist
+} // namespace secure_origin_allowlist
-#endif // CHROME_COMMON_SECURE_ORIGIN_WHITELIST_H_
+#endif // CHROME_COMMON_SECURE_ORIGIN_ALLOWLIST_H_
diff --git a/chromium/chrome/common/service_process_util.cc b/chromium/chrome/common/service_process_util.cc
index 7e9b588fec6..58a0b0fc058 100644
--- a/chromium/chrome/common/service_process_util.cc
+++ b/chromium/chrome/common/service_process_util.cc
@@ -153,7 +153,7 @@ std::unique_ptr<base::CommandLine> CreateServiceProcessCommandLine() {
return command_line;
}
-ServiceProcessState::ServiceProcessState() : state_(NULL) {
+ServiceProcessState::ServiceProcessState() : state_(nullptr) {
autorun_command_line_ = CreateServiceProcessCommandLine();
CreateState();
}
diff --git a/chromium/chrome/common/service_process_util_posix.cc b/chromium/chrome/common/service_process_util_posix.cc
index 848ef552503..b4913b0d678 100644
--- a/chromium/chrome/common/service_process_util_posix.cc
+++ b/chromium/chrome/common/service_process_util_posix.cc
@@ -12,6 +12,7 @@
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/location.h"
+#include "base/logging.h"
#include "base/message_loop/message_loop_current.h"
#include "base/posix/eintr_wrapper.h"
#include "base/synchronization/waitable_event.h"
diff --git a/chromium/chrome/common/service_process_util_win.cc b/chromium/chrome/common/service_process_util_win.cc
index 5cb5c55e617..8c6f8f9ff13 100644
--- a/chromium/chrome/common/service_process_util_win.cc
+++ b/chromium/chrome/common/service_process_util_win.cc
@@ -64,7 +64,7 @@ class ServiceProcessTerminateMonitor
void Start() {
base::string16 event_name = GetServiceProcessTerminateEventName();
DCHECK(event_name.length() <= MAX_PATH);
- terminate_event_.Set(CreateEvent(NULL, TRUE, FALSE, event_name.c_str()));
+ terminate_event_.Set(CreateEvent(nullptr, TRUE, FALSE, event_name.c_str()));
watcher_.StartWatchingOnce(terminate_event_.Get(), this);
}
@@ -211,7 +211,7 @@ bool ServiceProcessState::TakeSingletonLock() {
DCHECK(event_name.length() <= MAX_PATH);
base::win::ScopedHandle service_process_ready_event;
service_process_ready_event.Set(
- CreateEvent(NULL, TRUE, FALSE, event_name.c_str()));
+ CreateEvent(nullptr, TRUE, FALSE, event_name.c_str()));
DWORD error = GetLastError();
if ((error == ERROR_ALREADY_EXISTS) || (error == ERROR_ACCESS_DENIED))
return false;
@@ -262,5 +262,5 @@ bool ServiceProcessState::RemoveFromAutoRun() {
void ServiceProcessState::TearDownState() {
delete state_;
- state_ = NULL;
+ state_ = nullptr;
}
diff --git a/chromium/chrome/common/string_matching/BUILD.gn b/chromium/chrome/common/string_matching/BUILD.gn
deleted file mode 100644
index 183a9ede09b..00000000000
--- a/chromium/chrome/common/string_matching/BUILD.gn
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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("//build/config/ui.gni")
-import("//chrome/common/features.gni")
-
-source_set("string_matching") {
- sources = [
- "fuzzy_tokenized_string_match.cc",
- "fuzzy_tokenized_string_match.h",
- "sequence_matcher.cc",
- "sequence_matcher.h",
- "term_break_iterator.cc",
- "term_break_iterator.h",
- "tokenized_string.cc",
- "tokenized_string.h",
- "tokenized_string_char_iterator.cc",
- "tokenized_string_char_iterator.h",
- "tokenized_string_match.cc",
- "tokenized_string_match.h",
- ]
-
- deps = [
- "//base",
- "//base:i18n",
- "//cc",
- ]
-
- public_deps = [
- "//base",
- "//ui/gfx",
- ]
-}
diff --git a/chromium/chrome/common/string_matching/OWNERS b/chromium/chrome/common/string_matching/OWNERS
deleted file mode 100644
index cc83b874e21..00000000000
--- a/chromium/chrome/common/string_matching/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-jiameng@chromium.org
-thanhdng@chromium.org
diff --git a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.cc b/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.cc
deleted file mode 100644
index f26a37650cf..00000000000
--- a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.cc
+++ /dev/null
@@ -1,331 +0,0 @@
-// Copyright (c) 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.
-
-#include "chrome/common/string_matching/fuzzy_tokenized_string_match.h"
-
-#include <algorithm>
-#include <cmath>
-#include <iterator>
-
-#include "base/i18n/case_conversion.h"
-#include "base/metrics/field_trial_params.h"
-#include "base/strings/strcat.h"
-#include "base/strings/string_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "chrome/common/string_matching/sequence_matcher.h"
-
-namespace {
-constexpr double kMinScore = 0.0;
-constexpr double kMaxScore = 1.0;
-constexpr double kFirstCharacterMatchPenalty = 0.2;
-constexpr double kPrefixMatchPenalty = 0.1;
-
-// Returns sorted tokens from a TokenizedString.
-std::vector<base::string16> ProcessAndSort(const TokenizedString& text) {
- std::vector<base::string16> result;
- for (const auto& token : text.tokens()) {
- result.emplace_back(token);
- }
- std::sort(result.begin(), result.end());
- return result;
-}
-} // namespace
-
-FuzzyTokenizedStringMatch::~FuzzyTokenizedStringMatch() {}
-FuzzyTokenizedStringMatch::FuzzyTokenizedStringMatch() {}
-
-double FuzzyTokenizedStringMatch::FirstCharacterMatch(
- const TokenizedString& query,
- const TokenizedString& text) {
- const base::string16 query_lower = base::i18n::ToLower(query.text());
- size_t query_index = 0;
- for (size_t text_index = 0; text_index < text.tokens().size(); text_index++) {
- if (query_index < query_lower.size() &&
- text.tokens()[text_index][0] == query_lower[query_index]) {
- query_index++;
- if (query_index == query_lower.size()) {
- // Penalizes the score using the number of text's tokens that are
- // needed.
- return std::max(kMinScore,
- kMaxScore - kFirstCharacterMatchPenalty *
- (text_index + 1 - query_lower.size()));
- }
- }
- }
- return kMinScore;
-}
-
-double FuzzyTokenizedStringMatch::PrefixMatch(const TokenizedString& query,
- const TokenizedString& text) {
- const std::vector<base::string16> query_tokens(query.tokens());
- const std::vector<base::string16> text_tokens(text.tokens());
- double match_score = kMaxScore;
- int previous_matched_index = -1;
- // For every query token, check if it is a prefix of a text token. The newly
- // matching text token must have higher index than the previous matched token.
- for (const auto& query_token : query_tokens) {
- bool matched = false;
- for (size_t text_index = previous_matched_index + 1;
- text_index < text_tokens.size(); text_index++) {
- if (query_token.size() <= text_tokens[text_index].size() &&
- query_token ==
- text_tokens[text_index].substr(0, query_token.size())) {
- matched = true;
- // Penalizes the score based on the number of skipped tokens.
- match_score -=
- kPrefixMatchPenalty * (text_index - previous_matched_index - 1);
- previous_matched_index = text_index;
- break;
- }
- }
- if (!matched) {
- return kMinScore;
- }
- }
- return std::max(kMinScore, match_score);
-}
-
-double FuzzyTokenizedStringMatch::TokenSetRatio(
- const TokenizedString& query,
- const TokenizedString& text,
- bool partial,
- double partial_match_penalty_rate,
- bool use_edit_distance) {
- std::set<base::string16> query_token(query.tokens().begin(),
- query.tokens().end());
- std::set<base::string16> text_token(text.tokens().begin(),
- text.tokens().end());
-
- std::vector<base::string16> intersection;
- std::vector<base::string16> query_diff_text;
- std::vector<base::string16> text_diff_query;
-
- // Find the intersection and the differences between two set of tokens.
- std::set_intersection(query_token.begin(), query_token.end(),
- text_token.begin(), text_token.end(),
- std::back_inserter(intersection));
- std::set_difference(query_token.begin(), query_token.end(),
- text_token.begin(), text_token.end(),
- std::back_inserter(query_diff_text));
- std::set_difference(text_token.begin(), text_token.end(), query_token.begin(),
- query_token.end(), std::back_inserter(text_diff_query));
-
- const base::string16 intersection_string =
- base::JoinString(intersection, base::UTF8ToUTF16(" "));
- const base::string16 query_rewritten =
- intersection.empty()
- ? base::JoinString(query_diff_text, base::UTF8ToUTF16(" "))
- : base::StrCat(
- {intersection_string, base::UTF8ToUTF16(" "),
- base::JoinString(query_diff_text, base::UTF8ToUTF16(" "))});
- const base::string16 text_rewritten =
- intersection.empty()
- ? base::JoinString(text_diff_query, base::UTF8ToUTF16(" "))
- : base::StrCat(
- {intersection_string, base::UTF8ToUTF16(" "),
- base::JoinString(text_diff_query, base::UTF8ToUTF16(" "))});
-
- if (partial) {
- return std::max(
- {PartialRatio(intersection_string, query_rewritten,
- partial_match_penalty_rate, use_edit_distance),
- PartialRatio(intersection_string, text_rewritten,
- partial_match_penalty_rate, use_edit_distance),
- PartialRatio(query_rewritten, text_rewritten,
- partial_match_penalty_rate, use_edit_distance)});
- }
-
- return std::max(
- {SequenceMatcher(intersection_string, query_rewritten, use_edit_distance)
- .Ratio(),
- SequenceMatcher(intersection_string, text_rewritten, use_edit_distance)
- .Ratio(),
- SequenceMatcher(query_rewritten, text_rewritten, use_edit_distance)
- .Ratio()});
-}
-
-double FuzzyTokenizedStringMatch::TokenSortRatio(
- const TokenizedString& query,
- const TokenizedString& text,
- bool partial,
- double partial_match_penalty_rate,
- bool use_edit_distance) {
- const base::string16 query_sorted =
- base::JoinString(ProcessAndSort(query), base::UTF8ToUTF16(" "));
- const base::string16 text_sorted =
- base::JoinString(ProcessAndSort(text), base::UTF8ToUTF16(" "));
-
- if (partial) {
- return PartialRatio(query_sorted, text_sorted, partial_match_penalty_rate,
- use_edit_distance);
- }
- return SequenceMatcher(query_sorted, text_sorted, use_edit_distance).Ratio();
-}
-
-double FuzzyTokenizedStringMatch::PartialRatio(
- const base::string16& query,
- const base::string16& text,
- double partial_match_penalty_rate,
- bool use_edit_distance) {
- if (query.empty() || text.empty()) {
- return kMinScore;
- }
- base::string16 shorter = query;
- base::string16 longer = text;
-
- if (shorter.size() > longer.size()) {
- shorter = text;
- longer = query;
- }
-
- const auto matching_blocks =
- SequenceMatcher(shorter, longer, use_edit_distance).GetMatchingBlocks();
- double partial_ratio = 0;
-
- for (const auto& block : matching_blocks) {
- const int long_start =
- block.pos_second_string > block.pos_first_string
- ? block.pos_second_string - block.pos_first_string
- : 0;
-
- // Penalizes the match if it is not close to the beginning of a token.
- int current = long_start - 1;
- while (current >= 0 &&
- !base::EqualsCaseInsensitiveASCII(longer.substr(current, 1),
- base::UTF8ToUTF16(" "))) {
- current--;
- }
- const double penalty =
- std::pow(partial_match_penalty_rate, long_start - current - 1);
- // TODO(crbug/990684): currently this part re-calculate the ratio for every
- // pair. Improve this to reduce latency.
- partial_ratio = std::max(
- partial_ratio,
- SequenceMatcher(shorter, longer.substr(long_start, shorter.size()),
- use_edit_distance)
- .Ratio() *
- penalty);
-
- if (partial_ratio > 0.995) {
- return kMaxScore;
- }
- }
- return partial_ratio;
-}
-
-double FuzzyTokenizedStringMatch::WeightedRatio(
- const TokenizedString& query,
- const TokenizedString& text,
- double partial_match_penalty_rate,
- bool use_edit_distance) {
- const double unbase_scale = 0.95;
- // Since query.text() and text.text() is not normalized, we use query.tokens()
- // and text.tokens() instead.
- const base::string16 query_normalized(
- base::JoinString(query.tokens(), base::UTF8ToUTF16(" ")));
- const base::string16 text_normalized(
- base::JoinString(text.tokens(), base::UTF8ToUTF16(" ")));
- double weighted_ratio =
- SequenceMatcher(query_normalized, text_normalized, use_edit_distance)
- .Ratio();
- const double length_ratio =
- static_cast<double>(
- std::max(query_normalized.size(), text_normalized.size())) /
- std::min(query_normalized.size(), text_normalized.size());
-
- // Use partial if two strings are quite different in sizes.
- const bool use_partial = length_ratio >= 1.5;
- double partial_scale = 1;
-
- if (use_partial) {
- // If one string is much much shorter than the other, set |partial_scale| to
- // be 0.6, otherwise set it to be 0.9.
- partial_scale = length_ratio > 8 ? 0.6 : 0.9;
- weighted_ratio =
- std::max(weighted_ratio,
- PartialRatio(query_normalized, text_normalized,
- partial_match_penalty_rate, use_edit_distance) *
- partial_scale);
- }
- weighted_ratio =
- std::max(weighted_ratio,
- TokenSortRatio(query, text, use_partial /*partial*/,
- partial_match_penalty_rate, use_edit_distance) *
- unbase_scale * partial_scale);
- weighted_ratio =
- std::max(weighted_ratio,
- TokenSetRatio(query, text, use_partial /*partial*/,
- partial_match_penalty_rate, use_edit_distance) *
- unbase_scale * partial_scale);
- return weighted_ratio;
-}
-
-double FuzzyTokenizedStringMatch::PrefixMatcher(const TokenizedString& query,
- const TokenizedString& text) {
- return std::max(PrefixMatch(query, text), FirstCharacterMatch(query, text));
-}
-
-bool FuzzyTokenizedStringMatch::IsRelevant(const TokenizedString& query,
- const TokenizedString& text,
- double relevance_threshold,
- bool use_prefix_only,
- bool use_weighted_ratio,
- bool use_edit_distance,
- double partial_match_penalty_rate) {
- // If there is an exact match, relevance will be 1.0 and there is only 1 hit
- // that is the entire text/query.
- const auto& query_text = query.text();
- const auto& text_text = text.text();
- const auto query_size = query_text.size();
- const auto text_size = text_text.size();
- if (query_size > 0 && query_size == text_size &&
- base::EqualsCaseInsensitiveASCII(query_text, text_text)) {
- hits_.push_back(gfx::Range(0, query_size));
- relevance_ = 1.0;
- return true;
- }
-
- // Find |hits_| using SequenceMatcher on original query and text.
- for (const auto& match :
- SequenceMatcher(query_text, text_text, use_edit_distance)
- .GetMatchingBlocks()) {
- if (match.length > 0) {
- hits_.push_back(gfx::Range(match.pos_second_string,
- match.pos_second_string + match.length));
- }
- }
-
- // If the query is much longer than the text then it's often not a match.
- if (query_size >= text_size * 2) {
- return false;
- }
-
- const double prefix_score = PrefixMatcher(query, text);
-
- if (use_prefix_only && prefix_score >= relevance_threshold) {
- // If the prefix score is already higher than |relevance_threshold|, use
- // prefix score as final score.
- relevance_ = prefix_score;
- return true;
- }
-
- if (use_weighted_ratio) {
- // If WeightedRatio is used, |relevance_| is the average of WeightedRatio
- // and PrefixMatcher scores.
- relevance_ = (WeightedRatio(query, text, partial_match_penalty_rate,
- use_edit_distance) +
- prefix_score) /
- 2;
- } else {
- // Use simple algorithm to calculate match ratio.
- relevance_ =
- (SequenceMatcher(base::i18n::ToLower(query_text),
- base::i18n::ToLower(text_text), use_edit_distance)
- .Ratio() +
- prefix_score) /
- 2;
- }
-
- return relevance_ >= relevance_threshold;
-}
diff --git a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.h b/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.h
deleted file mode 100644
index 01bfbde6078..00000000000
--- a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match.h
+++ /dev/null
@@ -1,100 +0,0 @@
-// Copyright (c) 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_FUZZY_TOKENIZED_STRING_MATCH_H_
-#define CHROME_COMMON_STRING_MATCHING_FUZZY_TOKENIZED_STRING_MATCH_H_
-
-#include "base/gtest_prod_util.h"
-#include "base/macros.h"
-#include "chrome/common/string_matching/tokenized_string.h"
-#include "ui/gfx/range/range.h"
-
-// FuzzyTokenizedStringMatch takes two tokenized strings: one as the text and
-// the other one as the query. It matches the query against the text,
-// calculates a relevance score between [0, 1] and marks the matched portions
-// of text. A relevance of zero means the two are completely different to each
-// other. The higher the relevance score, the better the two strings are
-// matched. Matched portions of text are stored as index ranges.
-// TODO(crbug.com/1018613): each of these functions have too many input params,
-// we should revise the structure and remove unnecessary ones.
-class FuzzyTokenizedStringMatch {
- public:
- typedef std::vector<gfx::Range> Hits;
-
- FuzzyTokenizedStringMatch();
- ~FuzzyTokenizedStringMatch();
-
- // Check if the query only contains first characters of the text,
- // e.g. "coc" is a match of "Clash of Clan". Range of the score is [0, 1].
- static double FirstCharacterMatch(const TokenizedString& query,
- const TokenizedString& text);
-
- // Check if tokens of query are prefixes of text's tokens. Range of score is
- // [0, 1].
- static double PrefixMatch(const TokenizedString& query,
- const TokenizedString& text);
-
- // TokenSetRatio takes two sets of tokens, finds their intersection and
- // differences. From the intersection and differences, it rewrites the |query|
- // and |text| and find the similarity ratio between them. This function
- // assumes that TokenizedString is already normalized (converted to lower
- // case). Duplicates tokens will be removed for ratio computation.
- static double TokenSetRatio(const TokenizedString& query,
- const TokenizedString& text,
- bool partial,
- double partial_match_penalty_rate,
- bool use_edit_distance);
-
- // TokenSortRatio takes two set of tokens, sorts them and find the similarity
- // between two sorted strings. This function assumes that TokenizedString is
- // already normalized (converted to lower case)
- static double TokenSortRatio(const TokenizedString& query,
- const TokenizedString& text,
- bool partial,
- double partial_match_penalty_rate,
- bool use_edit_distance);
-
- // Finds the best ratio of shorter text with a part of longer text.
- // This function assumes that TokenizedString is already normalized (converted
- // to lower case). The return score is in range of [0, 1].
- static double PartialRatio(const base::string16& query,
- const base::string16& text,
- double partial_match_penalty_rate,
- bool use_edit_distance);
-
- // Combines scores from different ratio functions. This function assumes that
- // TokenizedString is already normalized (converted to lower cases).
- // The return score is in range of [0, 1].
- static double WeightedRatio(const TokenizedString& query,
- const TokenizedString& text,
- double partial_match_penalty_rate,
- bool use_edit_distance);
- // Since prefix match should always be favored over other matches, this
- // function is dedicated to calculate a prefix match score in range of [0, 1].
- // This score has two components: first character match and whole prefix
- // match.
- static double PrefixMatcher(const TokenizedString& query,
- const TokenizedString& text);
-
- // Calculates the relevance of two strings. Returns true if two strings are
- // somewhat matched, i.e. relevance score is greater than a threshold.
- bool IsRelevant(const TokenizedString& query,
- const TokenizedString& text,
- double relevance_threshold,
- bool use_prefix_only,
- bool use_weighted_ratio,
- bool use_edit_distance,
- double partial_match_penalty_rate);
- double relevance() const { return relevance_; }
- const Hits& hits() const { return hits_; }
-
- private:
- // Score in range of [0,1] representing how well the query matches the text.
- double relevance_ = 0;
- Hits hits_;
-
- DISALLOW_COPY_AND_ASSIGN(FuzzyTokenizedStringMatch);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_FUZZY_TOKENIZED_STRING_MATCH_H_
diff --git a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match_unittest.cc b/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match_unittest.cc
deleted file mode 100644
index 9413a36cb9c..00000000000
--- a/chromium/chrome/common/string_matching/fuzzy_tokenized_string_match_unittest.cc
+++ /dev/null
@@ -1,296 +0,0 @@
-// Copyright (c) 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.
-
-#include "chrome/common/string_matching/fuzzy_tokenized_string_match.h"
-
-#include "base/macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "chrome/common/string_matching/sequence_matcher.h"
-#include "chrome/common/string_matching/tokenized_string.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-constexpr double kPartialMatchPenaltyRate = 0.9;
-
-class FuzzyTokenizedStringMatchTest : public testing::Test {};
-
-// TODO(crbug.com/1018613): update the tests once params are consolidated.
-TEST_F(FuzzyTokenizedStringMatchTest, PartialRatioTest) {
- FuzzyTokenizedStringMatch match;
- EXPECT_NEAR(match.PartialRatio(base::UTF8ToUTF16("abcde"),
- base::UTF8ToUTF16("ababcXXXbcdeY"),
- kPartialMatchPenaltyRate, false),
- 0.6, 0.01);
- EXPECT_NEAR(match.PartialRatio(base::UTF8ToUTF16("big string"),
- base::UTF8ToUTF16("strength"),
- kPartialMatchPenaltyRate, false),
- 0.71, 0.01);
- EXPECT_EQ(match.PartialRatio(base::UTF8ToUTF16("abc"), base::UTF8ToUTF16(""),
- kPartialMatchPenaltyRate, false),
- 0);
- EXPECT_NEAR(match.PartialRatio(base::UTF8ToUTF16("different in order"),
- base::UTF8ToUTF16("order text"),
- kPartialMatchPenaltyRate, false),
- 0.67, 0.01);
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, TokenSetRatioTest) {
- FuzzyTokenizedStringMatch match;
- {
- base::string16 query(base::UTF8ToUTF16("order different in"));
- base::string16 text(base::UTF8ToUTF16("text order"));
- EXPECT_EQ(match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 1);
- EXPECT_NEAR(
- match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.67, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("short text"));
- base::string16 text(
- base::UTF8ToUTF16("this text is really really really long"));
- EXPECT_EQ(match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 1);
- EXPECT_NEAR(
- match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.57, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("common string"));
- base::string16 text(base::UTF8ToUTF16("nothing is shared"));
- EXPECT_NEAR(
- match.TokenSetRatio(TokenizedString(query), TokenizedString(text), true,
- kPartialMatchPenaltyRate, false),
- 0.38, 0.01);
- EXPECT_NEAR(
- match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.33, 0.01);
- }
- {
- base::string16 query(
- base::UTF8ToUTF16("token shared token same shared same"));
- base::string16 text(base::UTF8ToUTF16("token shared token text text long"));
- EXPECT_EQ(match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 1);
- EXPECT_NEAR(
- match.TokenSetRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.83, 0.01);
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, TokenSortRatioTest) {
- FuzzyTokenizedStringMatch match;
- {
- base::string16 query(base::UTF8ToUTF16("order different in"));
- base::string16 text(base::UTF8ToUTF16("text order"));
- EXPECT_NEAR(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 0.67, 0.01);
- EXPECT_NEAR(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.36, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("short text"));
- base::string16 text(
- base::UTF8ToUTF16("this text is really really really long"));
- EXPECT_EQ(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 0.5 * std::pow(0.9, 1));
- EXPECT_NEAR(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.33, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("common string"));
- base::string16 text(base::UTF8ToUTF16("nothing is shared"));
- EXPECT_NEAR(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- true, kPartialMatchPenaltyRate, false),
- 0.38, 0.01);
- EXPECT_NEAR(
- match.TokenSortRatio(TokenizedString(query), TokenizedString(text),
- false, kPartialMatchPenaltyRate, false),
- 0.33, 0.01);
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, WeightedRatio) {
- FuzzyTokenizedStringMatch match;
- {
- base::string16 query(base::UTF8ToUTF16("anonymous"));
- base::string16 text(base::UTF8ToUTF16("famous"));
- EXPECT_NEAR(
- match.WeightedRatio(TokenizedString(query), TokenizedString(text),
- kPartialMatchPenaltyRate, false),
- 0.67, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("Clash.of.clan"));
- base::string16 text(base::UTF8ToUTF16("ClashOfTitan"));
- EXPECT_NEAR(
- match.WeightedRatio(TokenizedString(query), TokenizedString(text),
- kPartialMatchPenaltyRate, false),
- 0.81, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("final fantasy"));
- base::string16 text(base::UTF8ToUTF16("finalfantasy"));
- EXPECT_NEAR(
- match.WeightedRatio(TokenizedString(query), TokenizedString(text),
- kPartialMatchPenaltyRate, false),
- 0.96, 0.01);
- }
- {
- base::string16 query(base::UTF8ToUTF16("short text!!!"));
- base::string16 text(
- base::UTF8ToUTF16("this sentence is much much much much much longer "
- "than the text before"));
- EXPECT_NEAR(
- match.WeightedRatio(TokenizedString(query), TokenizedString(text),
- kPartialMatchPenaltyRate, false),
- 0.85, 0.01);
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, FirstCharacterMatchTest) {
- {
- base::string16 query(base::UTF8ToUTF16("COC"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::FirstCharacterMatch(
- TokenizedString(query), TokenizedString(text)),
- 1.0);
- }
- {
- base::string16 query(base::UTF8ToUTF16("CC"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::FirstCharacterMatch(
- TokenizedString(query), TokenizedString(text)),
- 0.8);
- }
- {
- base::string16 query(base::UTF8ToUTF16("C o C"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::FirstCharacterMatch(
- TokenizedString(query), TokenizedString(text)),
- 0.0);
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, PrefixMatchTest) {
- {
- base::string16 query(base::UTF8ToUTF16("clas"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::PrefixMatch(TokenizedString(query),
- TokenizedString(text)),
- 1.0);
- }
- {
- base::string16 query(base::UTF8ToUTF16("clash clan"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::PrefixMatch(TokenizedString(query),
- TokenizedString(text)),
- 0.9);
- }
- {
- base::string16 query(base::UTF8ToUTF16("c o c"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::PrefixMatch(TokenizedString(query),
- TokenizedString(text)),
- 1.0);
- }
- {
- base::string16 query(base::UTF8ToUTF16("clam"));
- base::string16 text(base::UTF8ToUTF16("Clash of Clan"));
- EXPECT_EQ(FuzzyTokenizedStringMatch::PrefixMatch(TokenizedString(query),
- TokenizedString(text)),
- 0.0);
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, ParamThresholdTest1) {
- FuzzyTokenizedStringMatch match;
- {
- base::string16 query(base::UTF8ToUTF16("anonymous"));
- base::string16 text(base::UTF8ToUTF16("famous"));
- EXPECT_FALSE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.4, false, true, false,
- kPartialMatchPenaltyRate));
- }
- {
- base::string16 query(base::UTF8ToUTF16("CC"));
- base::string16 text(base::UTF8ToUTF16("Clash Of Clan"));
- EXPECT_TRUE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.4, false, true, false,
- kPartialMatchPenaltyRate));
- }
- {
- base::string16 query(base::UTF8ToUTF16("Clash.of.clan"));
- base::string16 text(base::UTF8ToUTF16("ClashOfTitan"));
- EXPECT_TRUE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.4, false, true, false,
- kPartialMatchPenaltyRate));
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, ParamThresholdTest2) {
- FuzzyTokenizedStringMatch match;
- {
- base::string16 query(base::UTF8ToUTF16("anonymous"));
- base::string16 text(base::UTF8ToUTF16("famous"));
- EXPECT_FALSE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.5, false, true, false,
- kPartialMatchPenaltyRate));
- }
- {
- base::string16 query(base::UTF8ToUTF16("CC"));
- base::string16 text(base::UTF8ToUTF16("Clash Of Clan"));
- EXPECT_TRUE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.5, false, true, false,
- kPartialMatchPenaltyRate));
- }
- {
- base::string16 query(base::UTF8ToUTF16("Clash.of.clan"));
- base::string16 text(base::UTF8ToUTF16("ClashOfTitan"));
- EXPECT_FALSE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.5, false, true, false,
- kPartialMatchPenaltyRate));
- }
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, OtherParamTest) {
- FuzzyTokenizedStringMatch match;
- base::string16 query(base::UTF8ToUTF16("anonymous"));
- base::string16 text(base::UTF8ToUTF16("famous"));
- EXPECT_FALSE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.35, false, false, true,
- kPartialMatchPenaltyRate));
- EXPECT_NEAR(match.relevance(), 0.33 / 2, 0.01);
-}
-
-TEST_F(FuzzyTokenizedStringMatchTest, ExactTextMatchTest) {
- FuzzyTokenizedStringMatch match;
- base::string16 query(base::UTF8ToUTF16("yat"));
- base::string16 text(base::UTF8ToUTF16("YaT"));
- EXPECT_TRUE(match.IsRelevant(TokenizedString(query), TokenizedString(text),
- 0.35, false, false, true,
- kPartialMatchPenaltyRate));
- EXPECT_DOUBLE_EQ(match.relevance(), 1.0);
- EXPECT_EQ(match.hits().size(), 1u);
- EXPECT_EQ(match.hits()[0].start(), 0u);
- EXPECT_EQ(match.hits()[0].end(), 3u);
-}
-
-} // namespace
diff --git a/chromium/chrome/common/string_matching/sequence_matcher.cc b/chromium/chrome/common/string_matching/sequence_matcher.cc
deleted file mode 100644
index 0d42146f087..00000000000
--- a/chromium/chrome/common/string_matching/sequence_matcher.cc
+++ /dev/null
@@ -1,198 +0,0 @@
-// Copyright (c) 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.
-
-#include "chrome/common/string_matching/sequence_matcher.h"
-
-#include <algorithm>
-#include <queue>
-
-#include "base/check_op.h"
-
-namespace {
-using Match = SequenceMatcher::Match;
-using Matches = std::vector<Match>;
-
-bool CompareMatches(const Match& m1, const Match& m2) {
- return m1.pos_first_string < m2.pos_first_string;
-}
-} // namespace
-
-SequenceMatcher::Match::Match() = default;
-SequenceMatcher::Match::Match(int pos_first, int pos_second, int len)
- : pos_first_string(pos_first), pos_second_string(pos_second), length(len) {
- DCHECK_GE(pos_first_string, 0);
- DCHECK_GE(pos_second_string, 0);
- DCHECK_GE(length, 0);
-}
-
-SequenceMatcher::SequenceMatcher(const base::string16& first_string,
- const base::string16& second_string,
- bool use_edit_distance)
- : first_string_(first_string),
- second_string_(second_string),
- dp_common_string_(second_string.size() + 1, 0) {
- DCHECK(!first_string_.empty() || !second_string_.empty());
-
- for (size_t i = 0; i < second_string_.size(); i++) {
- char_to_positions_[second_string_[i]].emplace_back(i);
- }
- use_edit_distance_ = use_edit_distance;
-}
-
-Match SequenceMatcher::FindLongestMatch(int first_start,
- int first_end,
- int second_start,
- int second_end) {
- Match match(first_start, second_start, 0);
-
- // These two vectors are used to do "fast update".
- // |dp_values_to_erase| contains the values should be erased from
- // |dp_common_string_|.
- // |dp_values_to_affect| contains the values should be updated from
- // |dp_common_string_|.
- std::vector<std::pair<int, int>> dp_values_to_erase;
- std::vector<std::pair<int, int>> dp_values_to_affect;
-
- for (int i = first_start; i < first_end; i++) {
- dp_values_to_affect.clear();
- for (auto j : char_to_positions_[first_string_[i]]) {
- if (j < second_start) {
- continue;
- }
- if (j >= second_end) {
- break;
- }
- // dp_commong_string_[j + 1] is length of longest common substring
- // ends at first_string_[i] and second_string_[j + 1]
- const int length = dp_common_string_[j] + 1;
- dp_values_to_affect.emplace_back(j + 1, length);
- if (length > match.length) {
- match.pos_first_string = i - length + 1;
- match.pos_second_string = j - length + 1;
- match.length = length;
- }
- }
- // Updates dp_common_string_
- for (auto const& element : dp_values_to_erase) {
- dp_common_string_[element.first] = 0;
- }
- for (auto const& element : dp_values_to_affect) {
- dp_common_string_[element.first] = element.second;
- }
- std::swap(dp_values_to_erase, dp_values_to_affect);
- }
- // Erases all updated value for the next call.
- std::fill(dp_common_string_.begin(), dp_common_string_.end(), 0);
-
- return match;
-}
-
-Matches SequenceMatcher::GetMatchingBlocks() {
- if (!matching_blocks_.empty()) {
- return matching_blocks_;
- }
-
- // This queue contains a tuple of 4 integers that represent 2 substrings to
- // find the longest match in the following order: first_start, first_end,
- // second_start, second_end.
- std::queue<std::tuple<int, int, int, int>> queue_block;
- queue_block.emplace(0, first_string_.size(), 0, second_string_.size());
-
- // Find all matching blocks recursively.
- while (!queue_block.empty()) {
- int first_start, first_end, second_start, second_end;
- std::tie(first_start, first_end, second_start, second_end) =
- queue_block.front();
- queue_block.pop();
- const Match match =
- FindLongestMatch(first_start, first_end, second_start, second_end);
- if (match.length > 0) {
- if (first_start < match.pos_first_string &&
- second_start < match.pos_second_string) {
- queue_block.emplace(first_start, match.pos_first_string, second_start,
- match.pos_second_string);
- }
- if (match.pos_first_string + match.length < first_end &&
- match.pos_second_string + match.length < second_end) {
- queue_block.emplace(match.pos_first_string + match.length, first_end,
- match.pos_second_string + match.length, second_end);
- }
- matching_blocks_.push_back(match);
- }
- }
-
- matching_blocks_.push_back(
- Match(first_string_.size(), second_string_.size(), 0));
- sort(matching_blocks_.begin(), matching_blocks_.end(), CompareMatches);
- return matching_blocks_;
-}
-
-int SequenceMatcher::EditDistance() {
- // If edit distance is already calculated
- if (edit_distance_ >= 0) {
- return edit_distance_;
- }
-
- const int len_first = first_string_.size();
- const int len_second = second_string_.size();
- if (len_first == 0 || len_second == 0) {
- edit_distance_ = std::max(len_first, len_second);
- return edit_distance_;
- }
-
- // Memory for the dynamic programming:
- // dp[i + 1][j + 1] is the edit distane of first |i| characters of
- // |first_string_| and first |j| characters of |second_string_|
- int dp[len_first + 1][len_second + 1];
-
- // Initialize memory
- for (int i = 0; i < len_first + 1; i++) {
- dp[i][0] = i;
- }
- for (int j = 0; j < len_second + 1; j++) {
- dp[0][j] = j;
- }
-
- // Calculate the edit distance
- for (int i = 1; i < len_first + 1; i++) {
- for (int j = 1; j < len_second + 1; j++) {
- const int cost = first_string_[i - 1] == second_string_[j - 1] ? 0 : 1;
- // Insertion and deletion
- dp[i][j] = std::min(dp[i - 1][j], dp[i][j - 1]) + 1;
- // Substitution
- dp[i][j] = std::min(dp[i][j], dp[i - 1][j - 1] + cost);
- // Transposition
- if (i > 1 && j > 1 && first_string_[i - 2] == second_string_[j - 1] &&
- first_string_[i - 1] == second_string_[j - 2]) {
- dp[i][j] = std::min(dp[i][j], dp[i - 2][j - 2] + cost);
- }
- }
- }
- edit_distance_ = dp[len_first][len_second];
- return edit_distance_;
-}
-
-double SequenceMatcher::Ratio() {
- if (use_edit_distance_) {
- if (edit_distance_ratio_ < 0) {
- const int edit_distance = EditDistance();
- edit_distance_ratio_ = std::max(
- 0.0, 1.0 - static_cast<double>(edit_distance) * 2 /
- (first_string_.size() + second_string_.size()));
- }
- return edit_distance_ratio_;
- }
-
- // Uses block matching to calculate ratio.
- if (block_matching_ratio_ < 0) {
- int sum_match = 0;
- const int sum_length = first_string_.size() + second_string_.size();
- DCHECK_NE(sum_length, 0);
- for (const auto& match : GetMatchingBlocks()) {
- sum_match += match.length;
- }
- block_matching_ratio_ = 2.0 * sum_match / sum_length;
- }
- return block_matching_ratio_;
-}
diff --git a/chromium/chrome/common/string_matching/sequence_matcher.h b/chromium/chrome/common/string_matching/sequence_matcher.h
deleted file mode 100644
index 71bc10b6892..00000000000
--- a/chromium/chrome/common/string_matching/sequence_matcher.h
+++ /dev/null
@@ -1,78 +0,0 @@
-// Copyright (c) 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_SEQUENCE_MATCHER_H_
-#define CHROME_COMMON_STRING_MATCHING_SEQUENCE_MATCHER_H_
-
-#include <string>
-#include <unordered_map>
-#include <vector>
-
-#include "base/logging.h"
-#include "base/macros.h"
-#include "base/strings/string16.h"
-
-// Performs the calculation of similarity level between 2 strings. This class's
-// functionality is inspired by python's difflib.SequenceMatcher library.
-// (https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher)
-class SequenceMatcher {
- public:
- // Representing a common substring between |first_string_| and
- // |second_string_|.
- struct Match {
- Match();
- Match(int pos_first, int pos_second, int len);
- // Starting position of the common substring in |first_string_|.
- int pos_first_string;
- // Starting position of the common substring in |second_string_|.
- int pos_second_string;
- // Length of the common substring.
- int length;
- };
- SequenceMatcher(const base::string16& first_string,
- const base::string16& second_string,
- bool use_edit_distance);
-
- ~SequenceMatcher() = default;
-
- // Calculates similarity ratio of |first_string_| and |second_string_|.
- double Ratio();
- // Calculates the Damerau–Levenshtein distance between |first_string_| and
- // |second_string_|.
- // See https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance for more
- // details.
- int EditDistance();
- // Finds the longest common substring between
- // |first_string_[first_start:first_end]| and
- // |second_string_[second_start:second_end]|.
- Match FindLongestMatch(int first_start,
- int first_end,
- int second_start,
- int second_end);
- // Get all matching blocks of |first_string_| and |second_string_|.
- // All blocks will be sorted by starting position of them in the
- // |first_string_|. The last matching block will always be
- // Match(first_string_.size(), second_string_.size(), 0).
- std::vector<Match> GetMatchingBlocks();
-
- private:
- base::string16 first_string_;
- base::string16 second_string_;
- double edit_distance_ratio_ = -1.0;
- double block_matching_ratio_ = -1.0;
- std::vector<Match> matching_blocks_;
-
- // Controls whether to use edit distance to calculate ratio.
- bool use_edit_distance_;
- int edit_distance_ = -1;
- // For each character |c| in |second_string_|, this variable
- // |char_to_positions_| stores all positions where |c| occurs in
- // |second_string_|.
- std::unordered_map<char, std::vector<int>> char_to_positions_;
- // Memory for dynamic programming algorithm used in FindLongestMatch().
- std::vector<int> dp_common_string_;
- DISALLOW_COPY_AND_ASSIGN(SequenceMatcher);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_SEQUENCE_MATCHER_H_
diff --git a/chromium/chrome/common/string_matching/sequence_matcher_unittest.cc b/chromium/chrome/common/string_matching/sequence_matcher_unittest.cc
deleted file mode 100644
index c06fcfc6452..00000000000
--- a/chromium/chrome/common/string_matching/sequence_matcher_unittest.cc
+++ /dev/null
@@ -1,137 +0,0 @@
-// Copyright (c) 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.
-
-#include "chrome/common/string_matching/sequence_matcher.h"
-
-#include "base/macros.h"
-#include "base/strings/utf_string_conversions.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-constexpr bool kDefaultUseEditDistance = false;
-
-using Match = SequenceMatcher::Match;
-bool MatchEqual(const Match& match1, const Match& match2) {
- return match1.pos_first_string == match2.pos_first_string &&
- match1.pos_second_string == match2.pos_second_string &&
- match1.length == match2.length;
-}
-
-class SequenceMatcherTest : public testing::Test {};
-
-TEST_F(SequenceMatcherTest, TestEditDistance) {
- // Transposition
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("abcd"),
- base::UTF8ToUTF16("abdc"), kDefaultUseEditDistance)
- .EditDistance(),
- 1);
-
- // Deletion
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("abcde"),
- base::UTF8ToUTF16("abcd"), kDefaultUseEditDistance)
- .EditDistance(),
- 1);
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("12"), base::UTF8ToUTF16(""),
- kDefaultUseEditDistance)
- .EditDistance(),
- 2);
-
- // Insertion
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("abc"),
- base::UTF8ToUTF16("abxbc"), kDefaultUseEditDistance)
- .EditDistance(),
- 2);
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16(""), base::UTF8ToUTF16("abxbc"),
- kDefaultUseEditDistance)
- .EditDistance(),
- 5);
-
- // Substitution
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("book"),
- base::UTF8ToUTF16("back"), kDefaultUseEditDistance)
- .EditDistance(),
- 2);
-
- // Combination
- ASSERT_EQ(
- SequenceMatcher(base::UTF8ToUTF16("caclulation"),
- base::UTF8ToUTF16("calculator"), kDefaultUseEditDistance)
- .EditDistance(),
- 3);
- ASSERT_EQ(
- SequenceMatcher(base::UTF8ToUTF16("sunday"),
- base::UTF8ToUTF16("saturday"), kDefaultUseEditDistance)
- .EditDistance(),
- 3);
-}
-
-TEST_F(SequenceMatcherTest, TestFindLongestMatch) {
- SequenceMatcher sequence_match(base::UTF8ToUTF16("miscellanious"),
- base::UTF8ToUTF16("miscellaneous"),
- kDefaultUseEditDistance);
- ASSERT_TRUE(MatchEqual(sequence_match.FindLongestMatch(0, 13, 0, 13),
- Match(0, 0, 9)));
- ASSERT_TRUE(MatchEqual(sequence_match.FindLongestMatch(7, 13, 7, 13),
- Match(10, 10, 3)));
-
- ASSERT_TRUE(MatchEqual(
- SequenceMatcher(base::UTF8ToUTF16(""), base::UTF8ToUTF16("abcd"),
- kDefaultUseEditDistance)
- .FindLongestMatch(0, 0, 0, 4),
- Match(0, 0, 0)));
- ASSERT_TRUE(MatchEqual(
- SequenceMatcher(base::UTF8ToUTF16("abababbababa"),
- base::UTF8ToUTF16("ababbaba"), kDefaultUseEditDistance)
- .FindLongestMatch(0, 12, 0, 8),
- Match(2, 0, 8)));
- ASSERT_TRUE(MatchEqual(
- SequenceMatcher(base::UTF8ToUTF16("aaaaaa"), base::UTF8ToUTF16("aaaaa"),
- kDefaultUseEditDistance)
- .FindLongestMatch(0, 6, 0, 5),
- Match(0, 0, 5)));
-}
-
-TEST_F(SequenceMatcherTest, TestGetMatchingBlocks) {
- SequenceMatcher sequence_match(
- base::UTF8ToUTF16("This is a demo sentence!!!"),
- base::UTF8ToUTF16("This demo sentence is good!!!"),
- kDefaultUseEditDistance);
- const std::vector<Match> true_matches = {Match(0, 0, 4), Match(9, 4, 14),
- Match(23, 26, 3), Match(26, 29, 0)};
- const std::vector<Match> matches = sequence_match.GetMatchingBlocks();
- ASSERT_EQ(matches.size(), 4ul);
- for (int i = 0; i < 4; i++) {
- ASSERT_TRUE(MatchEqual(matches[i], true_matches[i]));
- }
-}
-
-TEST_F(SequenceMatcherTest, TestSequenceMatcherRatio) {
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("abcd"),
- base::UTF8ToUTF16("adbc"), kDefaultUseEditDistance)
- .Ratio(),
- 0.75);
- ASSERT_EQ(
- SequenceMatcher(base::UTF8ToUTF16("white cats"),
- base::UTF8ToUTF16("cats white"), kDefaultUseEditDistance)
- .Ratio(),
- 0.5);
-}
-
-TEST_F(SequenceMatcherTest, TestEditDistanceRatio) {
- ASSERT_EQ(SequenceMatcher(base::UTF8ToUTF16("abcd"),
- base::UTF8ToUTF16("adbc"), true)
- .Ratio(),
- 0.5);
- EXPECT_NEAR(SequenceMatcher(base::UTF8ToUTF16("white cats"),
- base::UTF8ToUTF16("cats white"), true)
- .Ratio(),
- 0.2, 0.01);
-
- // Totally different
- EXPECT_NEAR(SequenceMatcher(base::UTF8ToUTF16("dog"),
- base::UTF8ToUTF16("elphant"), true)
- .Ratio(),
- 0.0, 0.01);
-}
-} // namespace
diff --git a/chromium/chrome/common/string_matching/term_break_iterator.cc b/chromium/chrome/common/string_matching/term_break_iterator.cc
deleted file mode 100644
index ae2f3b834ff..00000000000
--- a/chromium/chrome/common/string_matching/term_break_iterator.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/term_break_iterator.h"
-
-#include "base/check.h"
-#include "base/i18n/char_iterator.h"
-#include "base/notreached.h"
-#include "base/strings/string_util.h"
-#include "third_party/icu/source/common/unicode/uchar.h"
-
-TermBreakIterator::TermBreakIterator(const base::string16& word)
- : word_(word),
- prev_(npos),
- pos_(0),
- iter_(new base::i18n::UTF16CharIterator(&word)),
- state_(STATE_START) {}
-
-TermBreakIterator::~TermBreakIterator() = default;
-
-bool TermBreakIterator::Advance() {
- // 2D matrix that defines term boundaries. Each row represents current state.
- // Each col represents new state from input char. Cells with true value
- // represents a term boundary.
- const bool kBoundary[][STATE_LAST] = {
- // START NUMBER UPPER LOWER CHAR
- {false, false, false, false, false}, // START
- {false, false, true, true, true}, // NUMBER
- {false, true, false, false, true}, // UPPER
- {false, true, true, false, true}, // LOWER
- {false, true, true, true, false}, // CHAR
- };
-
- while (iter_->Advance()) {
- const State new_state = GetNewState(word_[iter_->array_pos()]);
- const bool is_boundary = kBoundary[state_][new_state];
- state_ = new_state;
- if (is_boundary)
- break;
- }
-
- prev_ = pos_;
- pos_ = iter_->array_pos();
-
- return prev_ != pos_ || !iter_->end();
-}
-
-const base::string16 TermBreakIterator::GetCurrentTerm() const {
- DCHECK(prev_ != npos && pos_ != npos);
- return word_.substr(prev_, pos_ - prev_);
-}
-
-TermBreakIterator::State TermBreakIterator::GetNewState(base::char16 ch) {
- if (base::IsAsciiDigit(ch) || ch == '.' || ch == ',')
- return STATE_NUMBER;
-
- const bool is_upper = !!u_isUUppercase(ch);
- const bool is_lower = !!u_isULowercase(ch);
-
- if (is_upper && is_lower) {
- NOTREACHED() << "Invalid state for ch=" << ch;
- return STATE_CHAR;
- }
-
- if (is_upper)
- return STATE_UPPER;
- if (is_lower)
- return STATE_LOWER;
-
- return STATE_CHAR;
-}
diff --git a/chromium/chrome/common/string_matching/term_break_iterator.h b/chromium/chrome/common/string_matching/term_break_iterator.h
deleted file mode 100644
index 80d069acc3c..00000000000
--- a/chromium/chrome/common/string_matching/term_break_iterator.h
+++ /dev/null
@@ -1,68 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_TERM_BREAK_ITERATOR_H_
-#define CHROME_COMMON_STRING_MATCHING_TERM_BREAK_ITERATOR_H_
-
-#include <stddef.h>
-
-#include <memory>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-
-namespace base {
-namespace i18n {
-class UTF16CharIterator;
-}
-} // namespace base
-
-// TermBreakIterator breaks terms out of a word. Terms are broken on
-// camel case boundaries and alpha/number boundaries. Numbers are defined
-// as [0-9\.,]+.
-// e.g.
-// CamelCase -> Camel, Case
-// Python2.7 -> Python, 2.7
-class TermBreakIterator {
- public:
- // Note that |word| must out live this iterator.
- explicit TermBreakIterator(const base::string16& word);
- ~TermBreakIterator();
-
- // Advance to the next term. Returns false if at the end of the word.
- bool Advance();
-
- // Returns the current term, which is the substr of |word_| in range
- // [prev_, pos_).
- const base::string16 GetCurrentTerm() const;
-
- size_t prev() const { return prev_; }
- size_t pos() const { return pos_; }
-
- static const size_t npos = static_cast<size_t>(-1);
-
- private:
- enum State {
- STATE_START, // Initial state
- STATE_NUMBER, // Current char is a number [0-9\.,].
- STATE_UPPER, // Current char is upper case.
- STATE_LOWER, // Current char is lower case.
- STATE_CHAR, // Current char has no case, e.g. a cjk char.
- STATE_LAST,
- };
-
- // Returns new state for given |ch|.
- State GetNewState(base::char16 ch);
-
- const base::string16& word_;
- size_t prev_;
- size_t pos_;
-
- std::unique_ptr<base::i18n::UTF16CharIterator> iter_;
- State state_;
-
- DISALLOW_COPY_AND_ASSIGN(TermBreakIterator);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_TERM_BREAK_ITERATOR_H_
diff --git a/chromium/chrome/common/string_matching/term_break_iterator_unittest.cc b/chromium/chrome/common/string_matching/term_break_iterator_unittest.cc
deleted file mode 100644
index 8ff0f2f8766..00000000000
--- a/chromium/chrome/common/string_matching/term_break_iterator_unittest.cc
+++ /dev/null
@@ -1,87 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/term_break_iterator.h"
-
-#include "base/strings/utf_string_conversions.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-using base::UTF8ToUTF16;
-
-namespace {
-
-TEST(TermBreakIteratorTest, EmptyWord) {
- base::string16 empty;
- TermBreakIterator iter(empty);
- EXPECT_FALSE(iter.Advance());
-}
-
-TEST(TermBreakIteratorTest, Simple) {
- base::string16 word(UTF8ToUTF16("simple"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("simple"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-TEST(TermBreakIteratorTest, CamelCase) {
- base::string16 word(UTF8ToUTF16("CamelCase"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Camel"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Case"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-TEST(TermBreakIteratorTest, LowerToUpper) {
- base::string16 word(UTF8ToUTF16("lowerToUpper"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("lower"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("To"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Upper"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-TEST(TermBreakIteratorTest, AlphaNumber) {
- base::string16 word(UTF8ToUTF16("Chromium26.0.0.0"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Chromium"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("26.0.0.0"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-TEST(TermBreakIteratorTest, StartsWithNumber) {
- base::string16 word(UTF8ToUTF16("123startWithNumber"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("123"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("start"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("With"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Number"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-TEST(TermBreakIteratorTest, CaseAndNoCase) {
- // "English" + two Chinese chars U+4E2D U+6587 + "Word"
- base::string16 word(UTF8ToUTF16("English\xe4\xb8\xad\xe6\x96\x87Word"));
- TermBreakIterator iter(word);
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("English"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("\xe4\xb8\xad\xe6\x96\x87"), iter.GetCurrentTerm());
- EXPECT_TRUE(iter.Advance());
- EXPECT_EQ(UTF8ToUTF16("Word"), iter.GetCurrentTerm());
- EXPECT_FALSE(iter.Advance()); // Test unexpected advance after end.
-}
-
-} // namespace
diff --git a/chromium/chrome/common/string_matching/tokenized_string.cc b/chromium/chrome/common/string_matching/tokenized_string.cc
deleted file mode 100644
index 77c0703100a..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string.h"
-
-#include <stddef.h>
-
-#include "base/i18n/break_iterator.h"
-#include "base/i18n/case_conversion.h"
-#include "base/notreached.h"
-#include "chrome/common/string_matching/term_break_iterator.h"
-
-using base::i18n::BreakIterator;
-
-TokenizedString::TokenizedString(const base::string16& text) : text_(text) {
- Tokenize();
-}
-
-TokenizedString::~TokenizedString() = default;
-
-void TokenizedString::Tokenize() {
- BreakIterator break_iter(text_, BreakIterator::BREAK_WORD);
- if (!break_iter.Init()) {
- NOTREACHED() << "BreakIterator init failed"
- << ", text=\"" << text_ << "\"";
- return;
- }
-
- while (break_iter.Advance()) {
- if (!break_iter.IsWord())
- continue;
-
- const base::string16 word(break_iter.GetString());
- const size_t word_start = break_iter.prev();
- TermBreakIterator term_iter(word);
- while (term_iter.Advance()) {
- tokens_.emplace_back(base::i18n::ToLower(term_iter.GetCurrentTerm()));
- mappings_.emplace_back(word_start + term_iter.prev(),
- word_start + term_iter.pos());
- }
- }
-}
diff --git a/chromium/chrome/common/string_matching/tokenized_string.h b/chromium/chrome/common/string_matching/tokenized_string.h
deleted file mode 100644
index a564741f1da..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_H_
-#define CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_H_
-
-#include <vector>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "ui/gfx/range/range.h"
-
-// TokenizedString takes a string and breaks it down into token words. It
-// first breaks using BreakIterator to get all the words. Then it breaks
-// the words again at camel case boundaries and alpha/number boundaries.
-class TokenizedString {
- public:
- typedef std::vector<base::string16> Tokens;
- typedef std::vector<gfx::Range> Mappings;
-
- explicit TokenizedString(const base::string16& text);
- ~TokenizedString();
-
- const base::string16& text() const { return text_; }
- const Tokens& tokens() const { return tokens_; }
- const Mappings& mappings() const { return mappings_; }
-
- private:
- void Tokenize();
-
- // Input text.
- const base::string16 text_;
-
- // Broken down tokens and the index mapping of tokens in original string.
- Tokens tokens_;
- Mappings mappings_;
-
- DISALLOW_COPY_AND_ASSIGN(TokenizedString);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_H_
diff --git a/chromium/chrome/common/string_matching/tokenized_string_char_iterator.cc b/chromium/chrome/common/string_matching/tokenized_string_char_iterator.cc
deleted file mode 100644
index b558c4d3f28..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_char_iterator.cc
+++ /dev/null
@@ -1,85 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string_char_iterator.h"
-
-#include "base/check.h"
-#include "base/i18n/char_iterator.h"
-#include "third_party/icu/source/common/unicode/utf16.h"
-
-TokenizedStringCharIterator::State::State() : token_index(0u), char_index(0) {}
-
-TokenizedStringCharIterator::State::State(size_t token_index, int char_index)
- : token_index(token_index), char_index(char_index) {}
-
-TokenizedStringCharIterator::TokenizedStringCharIterator(
- const TokenizedString& tokenized)
- : tokens_(tokenized.tokens()),
- mappings_(tokenized.mappings()),
- current_token_(0) {
- CreateTokenCharIterator();
-}
-
-TokenizedStringCharIterator::~TokenizedStringCharIterator() = default;
-
-bool TokenizedStringCharIterator::NextChar() {
- if (current_token_iter_) {
- current_token_iter_->Advance();
- if (!current_token_iter_->end())
- return true;
- }
-
- return NextToken();
-}
-
-bool TokenizedStringCharIterator::NextToken() {
- if (current_token_ < tokens_.size()) {
- ++current_token_;
- CreateTokenCharIterator();
- }
-
- return !!current_token_iter_;
-}
-
-int32_t TokenizedStringCharIterator::Get() const {
- return current_token_iter_ ? current_token_iter_->get() : 0;
-}
-
-int32_t TokenizedStringCharIterator::GetArrayPos() const {
- DCHECK(current_token_iter_);
- return mappings_[current_token_].start() + current_token_iter_->array_pos();
-}
-
-size_t TokenizedStringCharIterator::GetCharSize() const {
- return current_token_iter_ ? U16_LENGTH(Get()) : 0;
-}
-
-bool TokenizedStringCharIterator::IsFirstCharOfToken() const {
- return current_token_iter_ && current_token_iter_->char_offset() == 0;
-}
-
-TokenizedStringCharIterator::State TokenizedStringCharIterator::GetState()
- const {
- return State(current_token_,
- current_token_iter_ ? current_token_iter_->char_offset() : 0);
-}
-
-void TokenizedStringCharIterator::SetState(const State& state) {
- current_token_ = state.token_index;
- CreateTokenCharIterator();
- if (current_token_iter_) {
- while (current_token_iter_->char_offset() < state.char_index)
- current_token_iter_->Advance();
- }
-}
-
-void TokenizedStringCharIterator::CreateTokenCharIterator() {
- if (current_token_ == tokens_.size()) {
- current_token_iter_.reset();
- return;
- }
-
- current_token_iter_.reset(
- new base::i18n::UTF16CharIterator(&tokens_[current_token_]));
-}
diff --git a/chromium/chrome/common/string_matching/tokenized_string_char_iterator.h b/chromium/chrome/common/string_matching/tokenized_string_char_iterator.h
deleted file mode 100644
index 76a5be6e19a..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_char_iterator.h
+++ /dev/null
@@ -1,76 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_CHAR_ITERATOR_H_
-#define CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_CHAR_ITERATOR_H_
-
-#include <stddef.h>
-#include <stdint.h>
-
-#include <memory>
-
-#include "base/macros.h"
-#include "chrome/common/string_matching/tokenized_string.h"
-
-namespace base {
-namespace i18n {
-class UTF16CharIterator;
-}
-} // namespace base
-
-// An UTF16 char iterator for a TokenizedString.
-class TokenizedStringCharIterator {
- public:
- struct State {
- State();
- State(size_t token_index, int char_index);
-
- size_t token_index;
- int32_t char_index;
- };
-
- // Requires |tokenized| out-lives this iterator.
- explicit TokenizedStringCharIterator(const TokenizedString& tokenized);
- ~TokenizedStringCharIterator();
-
- // Advances to the next char. Returns false if there is no next char.
- bool NextChar();
-
- // Advances to the first char of the next token. Returns false if there is
- // no next token.
- bool NextToken();
-
- // Returns the current char if there is one. Otherwise, returns 0.
- int32_t Get() const;
-
- // Returns the array index in original text of the tokenized string that is
- // passed in constructor.
- int32_t GetArrayPos() const;
-
- // Returns the number of UTF16 code units for the current char.
- size_t GetCharSize() const;
-
- // Returns true if the current char is the first char of the current token.
- bool IsFirstCharOfToken() const;
-
- // Helpers to get and restore the iterator's state.
- State GetState() const;
- void SetState(const State& state);
-
- // Returns true if the iterator is at the end.
- bool end() const { return !current_token_iter_; }
-
- private:
- void CreateTokenCharIterator();
-
- const TokenizedString::Tokens& tokens_;
- const TokenizedString::Mappings& mappings_;
-
- size_t current_token_;
- std::unique_ptr<base::i18n::UTF16CharIterator> current_token_iter_;
-
- DISALLOW_COPY_AND_ASSIGN(TokenizedStringCharIterator);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_CHAR_ITERATOR_H_
diff --git a/chromium/chrome/common/string_matching/tokenized_string_char_iterator_unittest.cc b/chromium/chrome/common/string_matching/tokenized_string_char_iterator_unittest.cc
deleted file mode 100644
index 61b5c4cfaef..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_char_iterator_unittest.cc
+++ /dev/null
@@ -1,145 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string_char_iterator.h"
-
-#include <string>
-#include <vector>
-
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/strings/utf_string_conversions.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-// Returns a string represents the current state of |iter|. The state string
-// has three fields. The first is the current char. The second is the offset of
-// the current char in terms of the original text of the TokenizedString. The
-// last one is optional and only shows up when IsFirstCharOfToken returns true.
-std::string GetIterateState(const TokenizedStringCharIterator& iter) {
- return base::StringPrintf(
- "%s%d%s", base::UTF16ToUTF8(base::string16(1, iter.Get())).c_str(),
- iter.GetArrayPos(), iter.IsFirstCharOfToken() ? "!" : "");
-}
-
-void TestBeyondTheEnd(TokenizedStringCharIterator* iter) {
- ASSERT_TRUE(iter->end());
- ASSERT_FALSE(iter->NextChar());
- ASSERT_FALSE(iter->NextToken());
-
- // Don't care what it returns, but this shouldn't crash.
- iter->Get();
-}
-
-void TestEveryChar(const std::string& text, const std::string& expects) {
- TokenizedString tokens(base::UTF8ToUTF16(text));
- TokenizedStringCharIterator iter(tokens);
-
- std::vector<std::string> results;
- while (!iter.end()) {
- results.push_back(GetIterateState(iter));
- iter.NextChar();
- }
-
- EXPECT_EQ(expects, base::JoinString(results, " "));
- TestBeyondTheEnd(&iter);
-}
-
-void TestNextToken(const std::string& text, const std::string& expects) {
- TokenizedString tokens(base::UTF8ToUTF16(text));
- TokenizedStringCharIterator iter(tokens);
-
- std::vector<std::string> results;
- while (!iter.end()) {
- results.push_back(GetIterateState(iter));
- iter.NextToken();
- }
-
- EXPECT_EQ(expects, base::JoinString(results, " "));
- TestBeyondTheEnd(&iter);
-}
-
-void TestFirstTwoCharInEveryToken(const std::string& text,
- const std::string& expects) {
- TokenizedString tokens(base::UTF8ToUTF16(text));
- TokenizedStringCharIterator iter(tokens);
-
- std::vector<std::string> results;
- while (!iter.end()) {
- results.push_back(GetIterateState(iter));
- if (iter.NextChar())
- results.push_back(GetIterateState(iter));
-
- iter.NextToken();
- }
-
- EXPECT_EQ(expects, base::JoinString(results, " "));
- TestBeyondTheEnd(&iter);
-}
-
-TEST(TokenizedStringCharIteratorTest, NoTerms) {
- const char* text;
-
- text = "";
- TestEveryChar(text, "");
- TestNextToken(text, "");
- TestFirstTwoCharInEveryToken(text, "");
-
- text = "!@#$%^&*()<<<**>>>";
- TestEveryChar(text, "");
- TestNextToken(text, "");
- TestFirstTwoCharInEveryToken(text, "");
-}
-
-TEST(TokenizedStringCharIteratorTest, Basic) {
- const char* text;
-
- text = "c";
- TestEveryChar(text, "c0!");
- TestNextToken(text, "c0!");
- TestFirstTwoCharInEveryToken(text, "c0!");
-
- text = "Simple";
- TestEveryChar(text, "s0! i1 m2 p3 l4 e5");
- TestNextToken(text, "s0!");
- TestFirstTwoCharInEveryToken(text, "s0! i1");
-
- text = "ScratchPad";
- TestEveryChar(text, "s0! c1 r2 a3 t4 c5 h6 p7! a8 d9");
- TestNextToken(text, "s0! p7!");
- TestFirstTwoCharInEveryToken(text, "s0! c1 p7! a8");
-
- text = "Chess2.0";
- TestEveryChar(text, "c0! h1 e2 s3 s4 25! .6 07");
- TestNextToken(text, "c0! 25!");
- TestFirstTwoCharInEveryToken(text, "c0! h1 25! .6");
-
- text = "Cut the rope";
- TestEveryChar(text, "c0! u1 t2 t4! h5 e6 r8! o9 p10 e11");
- TestNextToken(text, "c0! t4! r8!");
- TestFirstTwoCharInEveryToken(text, "c0! u1 t4! h5 r8! o9");
-
- text = "AutoCAD WS";
- TestEveryChar(text, "a0! u1 t2 o3 c4! a5 d6 w8! s9");
- TestNextToken(text, "a0! c4! w8!");
- TestFirstTwoCharInEveryToken(text, "a0! u1 c4! a5 w8! s9");
-
- text = "Great TweetDeck";
- TestEveryChar(text, "g0! r1 e2 a3 t4 t6! w7 e8 e9 t10 d11! e12 c13 k14");
- TestNextToken(text, "g0! t6! d11!");
- TestFirstTwoCharInEveryToken(text, "g0! r1 t6! w7 d11! e12");
-
- text = "Draw-It!";
- TestEveryChar(text, "d0! r1 a2 w3 i5! t6");
- TestNextToken(text, "d0! i5!");
- TestFirstTwoCharInEveryToken(text, "d0! r1 i5! t6");
-
- text = "Faxing & Signing";
- TestEveryChar(text, "f0! a1 x2 i3 n4 g5 s9! i10 g11 n12 i13 n14 g15");
- TestNextToken(text, "f0! s9!");
- TestFirstTwoCharInEveryToken(text, "f0! a1 s9! i10");
-}
-
-} // namespace
diff --git a/chromium/chrome/common/string_matching/tokenized_string_fuzzer.cc b/chromium/chrome/common/string_matching/tokenized_string_fuzzer.cc
deleted file mode 100644
index 0e40150fda0..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_fuzzer.cc
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 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.
-
-#include "base/strings/string16.h"
-#include "chrome/common/string_matching/tokenized_string.h"
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- if (size < 1 || size % 2 != 0)
- return 0;
-
- // Test for base::string16 if size is even.
- base::string16 string_input16(reinterpret_cast<const base::char16*>(data),
- size / 2);
- TokenizedString tokenized_string_from_string16(string_input16);
- return 0;
-}
diff --git a/chromium/chrome/common/string_matching/tokenized_string_match.cc b/chromium/chrome/common/string_matching/tokenized_string_match.cc
deleted file mode 100644
index 0545cb1b2af..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_match.cc
+++ /dev/null
@@ -1,248 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string_match.h"
-
-#include <stddef.h>
-
-#include <cmath>
-
-#include "base/check.h"
-#include "base/i18n/string_search.h"
-#include "base/macros.h"
-#include "base/strings/string_util.h"
-#include "chrome/common/string_matching/tokenized_string_char_iterator.h"
-
-namespace {
-
-// The factors below are applied when the current char of query matches
-// the current char of the text to be matched. Different factors are chosen
-// based on where the match happens. kIsPrefixMultiplier is used when the
-// matched portion is a prefix of both the query and the text, which implies
-// that the matched chars are at the same position in query and text. This is
-// the most preferred case thus it has the highest score. When the current char
-// of the query and the text does not match, the algorithm moves to the next
-// token in the text and try to match from there. kIsFrontOfWordMultipler will
-// be used if the first char of the token matches the current char of the query.
-// Otherwise, the match is considered as weak and kIsWeakHitMultiplier is
-// used.
-// Examples:
-// Suppose the text to be matched is 'Google Chrome'.
-// Query 'go' would yield kIsPrefixMultiplier for each char.
-// Query 'gc' would use kIsPrefixMultiplier for 'g' and
-// kIsFrontOfWordMultipler for 'c'.
-// Query 'ch' would use kIsFrontOfWordMultipler for 'c' and
-// kIsWeakHitMultiplier for 'h'.
-// Query 'oo' does not match any prefix and would use the substring match
-// fallback, thus kIsSubstringMultiplier is used for each char.
-const double kIsPrefixMultiplier = 1.0;
-const double kIsFrontOfWordMultipler = 0.8;
-const double kIsWeakHitMultiplier = 0.6;
-const double kIsSubstringMultiplier = 0.4;
-
-// A relevance score that represents no match.
-const double kNoMatchScore = 0.0;
-
-// PrefixMatcher matches the chars of a given query as prefix of tokens in
-// a given text or as prefix of the acronyms of those text tokens.
-class PrefixMatcher {
- public:
- PrefixMatcher(const TokenizedString& query, const TokenizedString& text)
- : query_iter_(query),
- text_iter_(text),
- current_match_(gfx::Range::InvalidRange()),
- current_relevance_(kNoMatchScore) {}
-
- // Invokes RunMatch to perform prefix match. Use |states_| as a stack to
- // perform DFS (depth first search) so that all possible matches are
- // attempted. Stops on the first full match and returns true. Otherwise,
- // returns false to indicate no match.
- bool Match() {
- while (!RunMatch()) {
- // No match found and no more states to try. Bail out.
- if (states_.empty()) {
- current_relevance_ = kNoMatchScore;
- current_hits_.clear();
- return false;
- }
-
- PopState();
-
- // Skip restored match to try other possibilites.
- AdvanceToNextTextToken();
- }
-
- if (current_match_.IsValid())
- current_hits_.push_back(current_match_);
-
- return true;
- }
-
- double relevance() const { return current_relevance_; }
- const TokenizedStringMatch::Hits& hits() const { return current_hits_; }
-
- private:
- // Context record of a match.
- struct State {
- State() : relevance(kNoMatchScore) {}
- State(double relevance,
- const gfx::Range& current_match,
- const TokenizedStringMatch::Hits& hits,
- const TokenizedStringCharIterator& query_iter,
- const TokenizedStringCharIterator& text_iter)
- : relevance(relevance),
- current_match(current_match),
- hits(hits.begin(), hits.end()),
- query_iter_state(query_iter.GetState()),
- text_iter_state(text_iter.GetState()) {}
-
- // The current score of the processed query chars.
- double relevance;
-
- // Current matching range.
- gfx::Range current_match;
-
- // Completed matching ranges of the processed query chars.
- TokenizedStringMatch::Hits hits;
-
- // States of the processed query and text chars.
- TokenizedStringCharIterator::State query_iter_state;
- TokenizedStringCharIterator::State text_iter_state;
- };
- typedef std::vector<State> States;
-
- // Match chars from the query and text one by one. For each matching char,
- // calculate relevance and matching ranges. And the current stats is
- // recorded so that the match could be skipped later to try other
- // possiblities. Repeat until any of the iterators run out. Return true if
- // query iterator runs out, i.e. all chars in query are matched.
- bool RunMatch() {
- while (!query_iter_.end() && !text_iter_.end()) {
- if (query_iter_.Get() == text_iter_.Get()) {
- PushState();
-
- if (query_iter_.GetArrayPos() == text_iter_.GetArrayPos())
- current_relevance_ += kIsPrefixMultiplier;
- else if (text_iter_.IsFirstCharOfToken())
- current_relevance_ += kIsFrontOfWordMultipler;
- else
- current_relevance_ += kIsWeakHitMultiplier;
-
- if (!current_match_.IsValid())
- current_match_.set_start(text_iter_.GetArrayPos());
- current_match_.set_end(text_iter_.GetArrayPos() +
- text_iter_.GetCharSize());
-
- query_iter_.NextChar();
- text_iter_.NextChar();
- } else {
- AdvanceToNextTextToken();
- }
- }
-
- return query_iter_.end();
- }
-
- // Skip to the next text token and close current match. Invoked when a
- // mismatch happens or to skip a restored match.
- void AdvanceToNextTextToken() {
- if (current_match_.IsValid()) {
- current_hits_.push_back(current_match_);
- current_match_ = gfx::Range::InvalidRange();
- }
-
- text_iter_.NextToken();
- }
-
- void PushState() {
- states_.push_back(State(current_relevance_, current_match_, current_hits_,
- query_iter_, text_iter_));
- }
-
- void PopState() {
- DCHECK(!states_.empty());
-
- State& last_match = states_.back();
- current_relevance_ = last_match.relevance;
- current_match_ = last_match.current_match;
- current_hits_.swap(last_match.hits);
- query_iter_.SetState(last_match.query_iter_state);
- text_iter_.SetState(last_match.text_iter_state);
-
- states_.pop_back();
- }
-
- TokenizedStringCharIterator query_iter_;
- TokenizedStringCharIterator text_iter_;
-
- States states_;
- gfx::Range current_match_;
-
- double current_relevance_;
- TokenizedStringMatch::Hits current_hits_;
-
- DISALLOW_COPY_AND_ASSIGN(PrefixMatcher);
-};
-
-} // namespace
-
-TokenizedStringMatch::TokenizedStringMatch() : relevance_(kNoMatchScore) {}
-
-TokenizedStringMatch::~TokenizedStringMatch() = default;
-
-bool TokenizedStringMatch::Calculate(const TokenizedString& query,
- const TokenizedString& text) {
- relevance_ = kNoMatchScore;
- hits_.clear();
-
- // If there is an exact match, relevance will be 1.0 and there is only 1 hit
- // that is the entire text/query.
- const auto& query_text = query.text();
- const auto& text_text = text.text();
- const auto query_size = query_text.size();
- const auto text_size = text_text.size();
- if (query_size > 0 && query_size == text_size &&
- base::EqualsCaseInsensitiveASCII(query_text, text_text)) {
- hits_.push_back(gfx::Range(0, query_size));
- relevance_ = 1.0;
- return true;
- }
-
- PrefixMatcher matcher(query, text);
- if (matcher.Match()) {
- relevance_ = matcher.relevance();
- hits_.assign(matcher.hits().begin(), matcher.hits().end());
- }
-
- // Substring match as a fallback.
- if (relevance_ == kNoMatchScore) {
- size_t substr_match_start = 0;
- size_t substr_match_length = 0;
- if (base::i18n::StringSearchIgnoringCaseAndAccents(
- query.text(), text.text(), &substr_match_start,
- &substr_match_length)) {
- relevance_ = kIsSubstringMultiplier * substr_match_length;
- hits_.push_back(gfx::Range(substr_match_start,
- substr_match_start + substr_match_length));
- }
- }
-
- // Temper the relevance score with an exponential curve. Each point of
- // relevance (roughly, each keystroke) is worth less than the last. This means
- // that typing a few characters of a word is enough to promote matches very
- // high, with any subsequent characters being worth comparatively less.
- // TODO(mgiuca): This doesn't really play well with Omnibox results, since as
- // you type more characters, the app/omnibox results tend to jump over each
- // other.
- relevance_ = 1.0 - std::pow(0.5, relevance_);
-
- return relevance_ > kNoMatchScore;
-}
-
-bool TokenizedStringMatch::Calculate(const base::string16& query,
- const base::string16& text) {
- const TokenizedString tokenized_query(query);
- const TokenizedString tokenized_text(text);
- return Calculate(tokenized_query, tokenized_text);
-}
diff --git a/chromium/chrome/common/string_matching/tokenized_string_match.h b/chromium/chrome/common/string_matching/tokenized_string_match.h
deleted file mode 100644
index 0112ac9ab10..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_match.h
+++ /dev/null
@@ -1,49 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_MATCH_H_
-#define CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_MATCH_H_
-
-#include <vector>
-
-#include "base/macros.h"
-#include "base/strings/string16.h"
-#include "ui/gfx/range/range.h"
-
-class TokenizedString;
-
-// TokenizedStringMatch takes two tokenized strings: one as the text and
-// the other one as the query. It matches the query against the text,
-// calculates a relevance score between [0, 1] and marks the matched portions
-// of text. A relevance of zero means the two are completely different to each
-// other. The higher the relevance score, the better the two strings are
-// matched. Matched portions of text are stored as index ranges.
-class TokenizedStringMatch {
- public:
- typedef std::vector<gfx::Range> Hits;
-
- TokenizedStringMatch();
- ~TokenizedStringMatch();
-
- // Calculates the relevance and hits. Returns true if the two strings are
- // somewhat matched, i.e. relevance score is not zero.
- bool Calculate(const TokenizedString& query, const TokenizedString& text);
-
- // Convenience wrapper to calculate match from raw string input.
- bool Calculate(const base::string16& query, const base::string16& text);
-
- double relevance() const { return relevance_; }
- const Hits& hits() const { return hits_; }
-
- private:
- // Score in range of [0,1] representing how well the query matches the text.
- double relevance_;
-
- // Char index ranges in |text| of where matches are found.
- Hits hits_;
-
- DISALLOW_COPY_AND_ASSIGN(TokenizedStringMatch);
-};
-
-#endif // CHROME_COMMON_STRING_MATCHING_TOKENIZED_STRING_MATCH_H_
diff --git a/chromium/chrome/common/string_matching/tokenized_string_match_unittest.cc b/chromium/chrome/common/string_matching/tokenized_string_match_unittest.cc
deleted file mode 100644
index 01a23d3be1d..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_match_unittest.cc
+++ /dev/null
@@ -1,149 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string_match.h"
-
-#include <stddef.h>
-
-#include <string>
-
-#include "base/stl_util.h"
-#include "base/strings/utf_string_conversions.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-// Returns a string of |text| marked the hits in |match| using block bracket.
-// e.g. text= "Text", match.hits = [{0,1}], returns "[T]ext".
-std::string MatchHit(const base::string16& text,
- const TokenizedStringMatch& match) {
- base::string16 marked = text;
-
- const TokenizedStringMatch::Hits& hits = match.hits();
- for (TokenizedStringMatch::Hits::const_reverse_iterator it = hits.rbegin();
- it != hits.rend(); ++it) {
- const gfx::Range& hit = *it;
- marked.insert(hit.end(), 1, ']');
- marked.insert(hit.start(), 1, '[');
- }
-
- return base::UTF16ToUTF8(marked);
-}
-
-TEST(TokenizedStringMatchTest, NotMatch) {
- struct {
- const char* text;
- const char* query;
- } kTestCases[] = {
- {"", ""}, {"", "query"},
- {"text", ""}, {"!", "!@#$%^&*()<<<**>>>"},
- {"abd", "abcd"}, {"cd", "abcd"},
- };
-
- TokenizedStringMatch match;
- for (size_t i = 0; i < base::size(kTestCases); ++i) {
- const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
- EXPECT_FALSE(match.Calculate(base::UTF8ToUTF16(kTestCases[i].query), text))
- << "Test case " << i << " : text=" << kTestCases[i].text
- << ", query=" << kTestCases[i].query;
- }
-}
-
-TEST(TokenizedStringMatchTest, Match) {
- struct {
- const char* text;
- const char* query;
- const char* expect;
- } kTestCases[] = {
- {"ScratchPad", "pad", "Scratch[Pad]"},
- {"ScratchPad", "sp", "[S]cratch[P]ad"},
- {"Chess2", "che", "[Che]ss2"},
- {"Chess2", "c2", "[C]hess[2]"},
- {"Cut the rope", "cut ro", "[Cut] the [ro]pe"},
- {"Cut the rope", "cr", "[C]ut the [r]ope"},
- {"John Doe", "jdoe", "[J]ohn [Doe]"},
- {"John Doe", "johnd", "[John D]oe"},
- {"Secure Shell", "she", "Secure [She]ll"},
- {"Simple Secure Shell", "sish", "[Si]mple Secure [Sh]ell"},
- {"Netflix", "flix", "Net[flix]"},
- };
-
- TokenizedStringMatch match;
- for (size_t i = 0; i < base::size(kTestCases); ++i) {
- const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
- EXPECT_TRUE(match.Calculate(base::UTF8ToUTF16(kTestCases[i].query), text));
- EXPECT_EQ(kTestCases[i].expect, MatchHit(text, match));
- }
-}
-
-TEST(TokenizedStringMatchTest, Relevance) {
- struct {
- const char* text;
- const char* query_low;
- const char* query_high;
- } kTestCases[] = {
- // More matched chars are better.
- {"Google Chrome", "g", "go"},
- {"Google Chrome", "go", "goo"},
- {"Google Chrome", "goo", "goog"},
- {"Google Chrome", "c", "ch"},
- {"Google Chrome", "ch", "chr"},
- // Acronym match is better than something in the middle.
- {"Google Chrome", "ch", "gc"},
- // Prefix match is better than middle match and acronym match.
- {"Google Chrome", "ch", "go"},
- {"Google Chrome", "gc", "go"},
- // Substring match has the lowest score.
- {"Google Chrome", "oo", "gc"},
- {"Google Chrome", "oo", "go"},
- {"Google Chrome", "oo", "ch"},
- };
-
- TokenizedStringMatch match_low;
- TokenizedStringMatch match_high;
- for (size_t i = 0; i < base::size(kTestCases); ++i) {
- const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
- EXPECT_TRUE(
- match_low.Calculate(base::UTF8ToUTF16(kTestCases[i].query_low), text));
- EXPECT_TRUE(match_high.Calculate(
- base::UTF8ToUTF16(kTestCases[i].query_high), text));
- EXPECT_LT(match_low.relevance(), match_high.relevance())
- << "Test case " << i << " : text=" << kTestCases[i].text
- << ", query_low=" << kTestCases[i].query_low
- << ", query_high=" << kTestCases[i].query_high;
- }
-}
-
-// More specialized tests of the absolute relevance scores. (These tests are
-// minimal, because they are so brittle. Changing the scoring algorithm will
-// require updating this test.)
-TEST(TokenizedStringMatchTest, AbsoluteRelevance) {
- const double kEpsilon = 0.006;
- struct {
- const char* text;
- const char* query;
- double expected_score;
- } kTestCases[] = {
- // The first few chars should increase the score extremely high. After
- // that, they should count less.
- // NOTE: 0.87 is a magic number, as it is the Omnibox score for a "pretty
- // good" match. We want a 3-letter prefix match to be slightly above 0.87.
- {"Google Chrome", "g", 0.5},
- {"Google Chrome", "go", 0.75},
- {"Google Chrome", "goo", 0.88},
- {"Google Chrome", "goog", 0.94},
- };
-
- TokenizedStringMatch match;
- for (size_t i = 0; i < base::size(kTestCases); ++i) {
- const base::string16 text(base::UTF8ToUTF16(kTestCases[i].text));
- EXPECT_TRUE(match.Calculate(base::UTF8ToUTF16(kTestCases[i].query), text));
- EXPECT_NEAR(match.relevance(), kTestCases[i].expected_score, kEpsilon)
- << "Test case " << i << " : text=" << kTestCases[i].text
- << ", query=" << kTestCases[i].query
- << ", expected_score=" << kTestCases[i].expected_score;
- }
-}
-
-} // namespace
diff --git a/chromium/chrome/common/string_matching/tokenized_string_unittest.cc b/chromium/chrome/common/string_matching/tokenized_string_unittest.cc
deleted file mode 100644
index 51c98b2f295..00000000000
--- a/chromium/chrome/common/string_matching/tokenized_string_unittest.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-// 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.
-
-#include "chrome/common/string_matching/tokenized_string.h"
-
-#include <stddef.h>
-
-#include "base/strings/utf_string_conversions.h"
-#include "testing/gtest/include/gtest/gtest.h"
-
-namespace {
-
-base::string16 GetContent(const TokenizedString& tokenized) {
- const TokenizedString::Tokens& tokens = tokenized.tokens();
- const TokenizedString::Mappings& mappings = tokenized.mappings();
-
- base::string16 str;
- for (size_t i = 0; i < tokens.size(); ++i) {
- if (i > 0)
- str += ' ';
- str += tokens[i];
- str += base::UTF8ToUTF16(mappings[i].ToString());
- }
- return str;
-}
-
-TEST(TokenizedStringTest, Empty) {
- base::string16 empty;
- TokenizedString tokens(empty);
- EXPECT_EQ(base::string16(), GetContent(tokens));
-}
-
-TEST(TokenizedStringTest, Basic) {
- {
- base::string16 text(base::UTF8ToUTF16("ScratchPad"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("scratch{0,7} pad{7,10}"), GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("Chess2.0"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("chess{0,5} 2.0{5,8}"), GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("Cut the rope"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("cut{0,3} the{4,7} rope{8,12}"),
- GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("AutoCAD WS"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("auto{0,4} cad{4,7} ws{8,10}"),
- GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("Great TweetDeck"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("great{0,5} tweet{6,11} deck{11,15}"),
- GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("Draw-It!"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("draw{0,4} it{5,7}"), GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("Faxing & Signing"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16("faxing{0,6} signing{9,16}"),
- GetContent(tokens));
- }
- {
- base::string16 text(base::UTF8ToUTF16("!@#$%^&*()<<<**>>>"));
- TokenizedString tokens(text);
- EXPECT_EQ(base::UTF8ToUTF16(""), GetContent(tokens));
- }
-}
-
-} // namespace
diff --git a/chromium/chrome/common/subresource_redirect_service.mojom b/chromium/chrome/common/subresource_redirect_service.mojom
new file mode 100644
index 00000000000..716b9afc59e
--- /dev/null
+++ b/chromium/chrome/common/subresource_redirect_service.mojom
@@ -0,0 +1,18 @@
+// Copyright 2020 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.
+
+module subresource_redirect.mojom;
+
+import "mojo/public/mojom/base/time.mojom";
+
+// This service is implemented in the browser process and is used by the
+// renderer to notify the state of https image compression. This interface is
+// associated with a frame.
+interface SubresourceRedirectService {
+ // Notifies an image fetch from the compression server had failed. When
+ // Retry-After response header is present |retry_after| indicates the time
+ // after which subsequent image fetches should be initiated, otherwise
+ // |retry_after| is zero.
+ NotifyCompressedImageFetchFailed(mojo_base.mojom.TimeDelta retry_after);
+};
diff --git a/chromium/chrome/common/themes/autogenerated_theme_util.cc b/chromium/chrome/common/themes/autogenerated_theme_util.cc
index 6a6b8d74fd7..40cb375b94e 100644
--- a/chromium/chrome/common/themes/autogenerated_theme_util.cc
+++ b/chromium/chrome/common/themes/autogenerated_theme_util.cc
@@ -132,5 +132,5 @@ AutogeneratedThemeColors GetAutogeneratedThemeColors(SkColor color) {
frame_color = DarkenColor(frame_color, kDarkenStep);
}
return {frame_color, frame_text_color, active_tab_color,
- active_tab_text_color};
+ active_tab_text_color, active_tab_color};
}
diff --git a/chromium/chrome/common/themes/autogenerated_theme_util.h b/chromium/chrome/common/themes/autogenerated_theme_util.h
index ba84c4028ca..4317c49b638 100644
--- a/chromium/chrome/common/themes/autogenerated_theme_util.h
+++ b/chromium/chrome/common/themes/autogenerated_theme_util.h
@@ -22,6 +22,7 @@ struct AutogeneratedThemeColors {
SkColor frame_text_color;
SkColor active_tab_color;
SkColor active_tab_text_color;
+ SkColor ntp_color;
};
// Generates theme colors for the given |color|.
diff --git a/chromium/chrome/common/url_constants.cc b/chromium/chrome/common/url_constants.cc
index 1376b956df3..99d38846f95 100644
--- a/chromium/chrome/common/url_constants.cc
+++ b/chromium/chrome/common/url_constants.cc
@@ -16,7 +16,7 @@ const char kAutomaticSettingsResetLearnMoreURL[] =
"https://support.google.com/chrome/?p=ui_automatic_settings_reset";
const char kAdvancedProtectionDownloadLearnMoreURL[] =
- "https://support.google.com/accounts/?p=ap_faq";
+ "https://support.google.com/accounts/accounts?p=safe-browsing";
const char kBluetoothAdapterOffHelpURL[] =
"https://support.google.com/chrome?p=bluetooth";
@@ -280,6 +280,8 @@ const char kUpgradeHelpCenterBaseURL[] =
const char kWhoIsMyAdministratorHelpURL[] =
"https://support.google.com/chrome?p=your_administrator";
+const char kChromeFlashRoadmapURL[] = "https://www.chromium.org/flash-roadmap/";
+
#if defined(OS_ANDROID)
const char kAndroidAppScheme[] = "android-app";
#endif
@@ -329,9 +331,6 @@ const char kChromeOSGestureEducationHelpURL[] =
const char kChromePaletteHelpURL[] =
"https://support.google.com/chromebook?p=stylus_help";
-const char kClassroomSigninLearnMoreURL[] =
- "https://support.google.com/chromebook/?p=familylink_accounts";
-
const char kCrosScheme[] = "cros";
const char kCupsPrintLearnMoreURL[] =
@@ -379,9 +378,6 @@ const char kLinuxAppsLearnMoreURL[] =
const char kLinuxExportImportHelpURL[] =
"https://support.google.com/chromebook?p=linux_backup_restore";
-const char kLinuxCreditsPath[] =
- "/opt/google/chrome/resources/linux_credits.html";
-
const char kNaturalScrollHelpURL[] =
"https://support.google.com/chromebook/?p=simple_scrolling";
@@ -405,6 +401,9 @@ const char kTimeZoneSettingsLearnMoreURL[] =
const char kSmbSharesLearnMoreURL[] =
"https://support.google.com/chromebook?p=network_file_shares";
+const char kSuggestedContentLearnMoreURL[] =
+ "https://support.google.com/chromebook/?p=explorecontent";
+
const char kTabletModeGesturesLearnMoreURL[] =
"https://support.google.com/chromebook?p=tablet_mode_gestures";
diff --git a/chromium/chrome/common/url_constants.h b/chromium/chrome/common/url_constants.h
index 808ac18c5e1..ce93bf7963a 100644
--- a/chromium/chrome/common/url_constants.h
+++ b/chromium/chrome/common/url_constants.h
@@ -234,6 +234,9 @@ extern const char kUpgradeHelpCenterBaseURL[];
// Help center URL for who the account administrator is.
extern const char kWhoIsMyAdministratorHelpURL[];
+// Link to the flash roadmap
+extern const char kChromeFlashRoadmapURL[];
+
#if defined(OS_ANDROID)
extern const char kAndroidAppScheme[];
#endif
@@ -282,9 +285,6 @@ extern const char kChromeOSGestureEducationHelpURL[];
// Palette help link for Chrome.
extern const char kChromePaletteHelpURL[];
-// The URL for "How do I sign in to Classroom?" page.
-extern const char kClassroomSigninLearnMoreURL[];
-
extern const char kCrosScheme[];
extern const char kCupsPrintLearnMoreURL[];
@@ -327,9 +327,6 @@ extern const char kLinuxAppsLearnMoreURL[];
// The URL for additional help that is given when Linux export/import fails.
extern const char kLinuxExportImportHelpURL[];
-// Credits for Linux for Chromebooks.
-extern const char kLinuxCreditsPath[];
-
// The URL for the "Learn more" link for natural scrolling on ChromeOS.
extern const char kNaturalScrollHelpURL[];
@@ -358,6 +355,9 @@ extern const char kTimeZoneSettingsLearnMoreURL[];
// The URL for the "Learn more" page for the network file shares settings page.
extern const char kSmbSharesLearnMoreURL[];
+// The URL for the "Learn more" page for Suggested Content in the privacy page.
+extern const char kSuggestedContentLearnMoreURL[];
+
// The URL to a support article with more information about gestures available
// in tablet mode on Chrome OS (gesture to go to home screen, overview, or to go
// back). Used as a "Learn more" link URL for the accessibility option to shelf
diff --git a/chromium/chrome/common/web_application_info.cc b/chromium/chrome/common/web_application_info.cc
index e5fa3d94085..5590bfdf304 100644
--- a/chromium/chrome/common/web_application_info.cc
+++ b/chromium/chrome/common/web_application_info.cc
@@ -4,7 +4,8 @@
#include "chrome/common/web_application_info.h"
-WebApplicationIconInfo::WebApplicationIconInfo() : square_size_px(0) {}
+// WebApplicationIconInfo
+WebApplicationIconInfo::WebApplicationIconInfo() = default;
WebApplicationIconInfo::WebApplicationIconInfo(const WebApplicationIconInfo&) =
default;
@@ -20,22 +21,47 @@ WebApplicationIconInfo& WebApplicationIconInfo::operator=(
WebApplicationIconInfo& WebApplicationIconInfo::operator=(
WebApplicationIconInfo&&) = default;
-WebApplicationShortcutInfo::WebApplicationShortcutInfo() = default;
+// WebApplicationShortcutsMenuItemInfo::Icon
+WebApplicationShortcutsMenuItemInfo::Icon::Icon() = default;
-WebApplicationShortcutInfo::WebApplicationShortcutInfo(
- const WebApplicationShortcutInfo& other) = default;
+WebApplicationShortcutsMenuItemInfo::Icon::Icon(
+ const WebApplicationShortcutsMenuItemInfo::Icon&) = default;
-WebApplicationShortcutInfo::WebApplicationShortcutInfo(
- WebApplicationShortcutInfo&&) noexcept = default;
+WebApplicationShortcutsMenuItemInfo::Icon::Icon(
+ WebApplicationShortcutsMenuItemInfo::Icon&&) = default;
-WebApplicationShortcutInfo::~WebApplicationShortcutInfo() = default;
+WebApplicationShortcutsMenuItemInfo::Icon::~Icon() = default;
-WebApplicationShortcutInfo& WebApplicationShortcutInfo::operator=(
- const WebApplicationShortcutInfo&) = default;
+WebApplicationShortcutsMenuItemInfo::Icon&
+WebApplicationShortcutsMenuItemInfo::Icon::operator=(
+ const WebApplicationShortcutsMenuItemInfo::Icon&) = default;
-WebApplicationShortcutInfo& WebApplicationShortcutInfo::operator=(
- WebApplicationShortcutInfo&&) noexcept = default;
+WebApplicationShortcutsMenuItemInfo::Icon&
+WebApplicationShortcutsMenuItemInfo::Icon::operator=(
+ WebApplicationShortcutsMenuItemInfo::Icon&&) = default;
+// WebApplicationShortcutsMenuItemInfo
+WebApplicationShortcutsMenuItemInfo::WebApplicationShortcutsMenuItemInfo() =
+ default;
+
+WebApplicationShortcutsMenuItemInfo::WebApplicationShortcutsMenuItemInfo(
+ const WebApplicationShortcutsMenuItemInfo& other) = default;
+
+WebApplicationShortcutsMenuItemInfo::WebApplicationShortcutsMenuItemInfo(
+ WebApplicationShortcutsMenuItemInfo&&) noexcept = default;
+
+WebApplicationShortcutsMenuItemInfo::~WebApplicationShortcutsMenuItemInfo() =
+ default;
+
+WebApplicationShortcutsMenuItemInfo&
+WebApplicationShortcutsMenuItemInfo::operator=(
+ const WebApplicationShortcutsMenuItemInfo&) = default;
+
+WebApplicationShortcutsMenuItemInfo&
+WebApplicationShortcutsMenuItemInfo::operator=(
+ WebApplicationShortcutsMenuItemInfo&&) noexcept = default;
+
+// WebApplicationInfo
WebApplicationInfo::WebApplicationInfo() = default;
WebApplicationInfo::WebApplicationInfo(const WebApplicationInfo& other) =
@@ -51,6 +77,24 @@ bool operator==(const WebApplicationIconInfo& icon_info1,
std::ostream& operator<<(std::ostream& out,
const WebApplicationIconInfo& icon_info) {
- return out << "url: " << icon_info.url
- << " square_size_px: " << icon_info.square_size_px;
+ out << "url: " << icon_info.url << " square_size_px: ";
+ if (icon_info.square_size_px)
+ out << *icon_info.square_size_px;
+ else
+ out << "none";
+ return out;
+}
+
+bool operator==(const WebApplicationShortcutsMenuItemInfo::Icon& icon1,
+ const WebApplicationShortcutsMenuItemInfo::Icon& icon2) {
+ return std::tie(icon1.url, icon1.square_size_px) ==
+ std::tie(icon2.url, icon2.square_size_px);
+}
+
+bool operator==(const WebApplicationShortcutsMenuItemInfo& shortcut_info1,
+ const WebApplicationShortcutsMenuItemInfo& shortcut_info2) {
+ return std::tie(shortcut_info1.name, shortcut_info1.url,
+ shortcut_info1.shortcut_icon_infos) ==
+ std::tie(shortcut_info2.name, shortcut_info2.url,
+ shortcut_info2.shortcut_icon_infos);
}
diff --git a/chromium/chrome/common/web_application_info.h b/chromium/chrome/common/web_application_info.h
index 6cfde5ae8d7..5b3843e9d33 100644
--- a/chromium/chrome/common/web_application_info.h
+++ b/chromium/chrome/common/web_application_info.h
@@ -21,7 +21,10 @@
#include "url/gurl.h"
using SquareSizePx = int;
+using ShortcutsMenuIconsBitmaps = std::vector<std::map<SquareSizePx, SkBitmap>>;
+// TODO(https://crbug.com/1091473): Rename WebApplication* occurrences in this
+// file to WebApp*.
struct WebApplicationIconInfo {
WebApplicationIconInfo();
WebApplicationIconInfo(const WebApplicationIconInfo&);
@@ -31,18 +34,34 @@ struct WebApplicationIconInfo {
WebApplicationIconInfo& operator=(WebApplicationIconInfo&&);
GURL url;
- SquareSizePx square_size_px;
+ base::Optional<SquareSizePx> square_size_px;
};
// Structure used when creating app icon shortcuts menu and for downloading
// associated shortcut icons when supported by OS platform (eg. Windows).
-struct WebApplicationShortcutInfo {
- WebApplicationShortcutInfo();
- WebApplicationShortcutInfo(const WebApplicationShortcutInfo&);
- WebApplicationShortcutInfo(WebApplicationShortcutInfo&&) noexcept;
- ~WebApplicationShortcutInfo();
- WebApplicationShortcutInfo& operator=(const WebApplicationShortcutInfo&);
- WebApplicationShortcutInfo& operator=(WebApplicationShortcutInfo&&) noexcept;
+struct WebApplicationShortcutsMenuItemInfo {
+ struct Icon {
+ Icon();
+ Icon(const Icon&);
+ Icon(Icon&&);
+ ~Icon();
+ Icon& operator=(const Icon&);
+ Icon& operator=(Icon&&);
+
+ GURL url;
+ SquareSizePx square_size_px = 0;
+ };
+
+ WebApplicationShortcutsMenuItemInfo();
+ WebApplicationShortcutsMenuItemInfo(
+ const WebApplicationShortcutsMenuItemInfo&);
+ WebApplicationShortcutsMenuItemInfo(
+ WebApplicationShortcutsMenuItemInfo&&) noexcept;
+ ~WebApplicationShortcutsMenuItemInfo();
+ WebApplicationShortcutsMenuItemInfo& operator=(
+ const WebApplicationShortcutsMenuItemInfo&);
+ WebApplicationShortcutsMenuItemInfo& operator=(
+ WebApplicationShortcutsMenuItemInfo&&) noexcept;
// Title of shortcut item in App Icon Shortcut Menu.
base::string16 name;
@@ -51,10 +70,7 @@ struct WebApplicationShortcutInfo {
GURL url;
// List of shortcut icon URLs with associated square size.
- std::vector<WebApplicationIconInfo> shortcut_icon_infos;
-
- // Shortcut icon bitmaps keyed by their square size.
- std::map<SquareSizePx, SkBitmap> shortcut_icon_bitmaps;
+ std::vector<Icon> shortcut_icon_infos;
};
// Structure used when installing a web page as an app.
@@ -120,7 +136,18 @@ struct WebApplicationInfo {
std::vector<std::string> additional_search_terms;
// Set of shortcut infos populated using shortcuts specified in the manifest.
- std::vector<WebApplicationShortcutInfo> shortcut_infos;
+ //
+ // TODO(https://crbug.com/1100751): Rename this to shortcuts_menu_item_infos.
+ std::vector<WebApplicationShortcutsMenuItemInfo> shortcut_infos;
+
+ // Vector of shortcut icon bitmaps keyed by their square size. The index of a
+ // given std::map matches that of the shortcut in shortcut_infos whose bitmaps
+ // it contains.
+ ShortcutsMenuIconsBitmaps shortcuts_menu_icons_bitmaps;
+
+ // User preference as to whether to auto run the app on OS login.
+ // Currently only supported in Windows platform.
+ bool run_on_os_login = false;
};
std::ostream& operator<<(std::ostream& out,
@@ -129,4 +156,10 @@ std::ostream& operator<<(std::ostream& out,
bool operator==(const WebApplicationIconInfo& icon_info1,
const WebApplicationIconInfo& icon_info2);
+bool operator==(const WebApplicationShortcutsMenuItemInfo::Icon& icon1,
+ const WebApplicationShortcutsMenuItemInfo::Icon& icon2);
+
+bool operator==(const WebApplicationShortcutsMenuItemInfo& shortcut_info1,
+ const WebApplicationShortcutsMenuItemInfo& shortcut_info2);
+
#endif // CHROME_COMMON_WEB_APPLICATION_INFO_H_
diff --git a/chromium/chrome/common/web_components_prefs.cc b/chromium/chrome/common/web_components_prefs.cc
deleted file mode 100644
index 41bffa77ea9..00000000000
--- a/chromium/chrome/common/web_components_prefs.cc
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.
-
-#include "chrome/common/web_components_prefs.h"
-
-#include "chrome/common/pref_names.h"
-#include "components/prefs/pref_registry_simple.h"
-
-namespace web_components_prefs {
-
-void RegisterProfilePrefs(PrefRegistrySimple* registry) {
- registry->RegisterBooleanPref(prefs::kWebComponentsV0Enabled,
- /*default_value=*/false);
-}
-
-} // namespace web_components_prefs
diff --git a/chromium/chrome/common/web_components_prefs.h b/chromium/chrome/common/web_components_prefs.h
deleted file mode 100644
index 863bca647b3..00000000000
--- a/chromium/chrome/common/web_components_prefs.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// 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.
-
-#ifndef CHROME_COMMON_WEB_COMPONENTS_PREFS_H_
-#define CHROME_COMMON_WEB_COMPONENTS_PREFS_H_
-
-class PrefRegistrySimple;
-
-namespace web_components_prefs {
-
-// Register preferences for Web Components.
-void RegisterProfilePrefs(PrefRegistrySimple* registry);
-
-} // namespace web_components_prefs
-
-#endif // CHROME_COMMON_WEB_COMPONENTS_PREFS_H_
diff --git a/chromium/chrome/common/webui_url_constants.cc b/chromium/chrome/common/webui_url_constants.cc
index 1eb51da8a9e..2ceb36f1940 100644
--- a/chromium/chrome/common/webui_url_constants.cc
+++ b/chromium/chrome/common/webui_url_constants.cc
@@ -28,7 +28,6 @@ const char kChromeUIAutofillInternalsHost[] = "autofill-internals";
const char kChromeUIBluetoothInternalsHost[] = "bluetooth-internals";
const char kChromeUIBookmarksHost[] = "bookmarks";
const char kChromeUIBookmarksURL[] = "chrome://bookmarks/";
-const char kChromeUICameraHost[] = "camera";
const char kChromeUICertificateViewerHost[] = "view-cert";
const char kChromeUICertificateViewerURL[] = "chrome://view-cert/";
const char kChromeUIChromeSigninHost[] = "chrome-signin";
@@ -62,6 +61,7 @@ const char kChromeUIDownloadInternalsHost[] = "download-internals";
const char kChromeUIDownloadsHost[] = "downloads";
const char kChromeUIDownloadsURL[] = "chrome://downloads/";
const char kChromeUIDriveInternalsHost[] = "drive-internals";
+const char kChromeUIEDUCoexistenceLoginURL[] = "chrome://chrome-signin/edu";
const char kChromeUIExtensionIconHost[] = "extension-icon";
const char kChromeUIExtensionIconURL[] = "chrome://extension-icon/";
const char kChromeUIExtensionsHost[] = "extensions";
@@ -83,14 +83,11 @@ const char kChromeUIHistoryURL[] = "chrome://history/";
const char kChromeUIIdentityInternalsHost[] = "identity-internals";
const char kChromeUIInspectHost[] = "inspect";
const char kChromeUIInspectURL[] = "chrome://inspect/";
+const char kChromeUIInternalsHost[] = "internals";
const char kChromeUIInterstitialHost[] = "interstitials";
const char kChromeUIInterstitialURL[] = "chrome://interstitials/";
const char kChromeUIInterventionsInternalsHost[] = "interventions-internals";
const char kChromeUIInvalidationsHost[] = "invalidations";
-const char kChromeUIKaleidoscopeHost[] = "kaleidoscope";
-const char kChromeUIKaleidoscopeURL[] = "chrome://kaleidoscope";
-const char kChromeUIKaleidoscopeContentHost[] = "kaleidoscope-content";
-const char kChromeUIKaleidoscopeContentURL[] = "chrome://kaleidoscope-content";
const char kChromeUIKillHost[] = "kill";
const char kChromeUILocalStateHost[] = "local-state";
const char kChromeUIManagementHost[] = "management";
@@ -139,6 +136,8 @@ const char kChromeUISigninEmailConfirmationURL[] =
"chrome://signin-email-confirmation";
const char kChromeUISigninErrorHost[] = "signin-error";
const char kChromeUISigninErrorURL[] = "chrome://signin-error/";
+const char kChromeUISigninReauthHost[] = "signin-reauth";
+const char kChromeUISigninReauthURL[] = "chrome://signin-reauth/";
const char kChromeUISiteDetailsPrefixURL[] =
"chrome://settings/content/siteDetails?site=";
const char kChromeUISiteEngagementHost[] = "site-engagement";
@@ -163,7 +162,6 @@ const char kChromeUIThumbnailHost[] = "thumb";
const char kChromeUIThumbnailListHost[] = "thumbnails";
const char kChromeUIThumbnailURL[] = "chrome://thumb/";
const char kChromeUITranslateInternalsHost[] = "translate-internals";
-const char kChromeUIUkmHost[] = "ukm";
const char kChromeUIUsbInternalsHost[] = "usb-internals";
const char kChromeUIUserActionsHost[] = "user-actions";
const char kChromeUIVersionHost[] = "version";
@@ -189,6 +187,8 @@ const char kChromeUINativeNewTabURL[] = "chrome-native://newtab/";
const char kChromeUIOfflineInternalsHost[] = "offline-internals";
const char kChromeUISnippetsInternalsHost[] = "snippets-internals";
const char kChromeUIWebApksHost[] = "webapks";
+#else
+const char kChromeUINearbyInternalsHost[] = "nearby-internals";
#endif
#if defined(OS_CHROMEOS)
@@ -326,6 +326,11 @@ const char kChromeUIHatsURL[] = "chrome://hats/";
const char kChromeUIProfilePickerHost[] = "profile-picker";
#endif
+#if !defined(OS_ANDROID)
+const char kChromeUINearbyShareHost[] = "nearby";
+const char kChromeUINearbyShareURL[] = "chrome://nearby/";
+#endif // !defined(OS_ANDROID)
+
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
const char kChromeUILinuxProxyConfigHost[] = "linux-proxy-config";
#endif
@@ -353,6 +358,11 @@ const char kChromeUITabStripHost[] = "tab-strip";
const char kChromeUITabStripURL[] = "chrome://tab-strip";
#endif
+#if !defined(OS_ANDROID)
+const char kChromeUITabSearchHost[] = "tab-search";
+const char kChromeUITabSearchURL[] = "chrome://tab-search/";
+#endif
+
const char kChromeUIWebRtcLogsHost[] = "webrtc-logs";
// Settings sub pages.
@@ -465,6 +475,7 @@ const char* const kChromeHostURLs[] = {
#if !defined(OS_ANDROID)
content::kChromeUITracingHost,
#endif
+ content::kChromeUIUkmHost,
content::kChromeUIWebRTCInternalsHost,
#if !defined(OS_ANDROID)
#if !defined(OS_CHROMEOS)
diff --git a/chromium/chrome/common/webui_url_constants.h b/chromium/chrome/common/webui_url_constants.h
index 5ff6b8ba8b4..bd3205d7c73 100644
--- a/chromium/chrome/common/webui_url_constants.h
+++ b/chromium/chrome/common/webui_url_constants.h
@@ -36,7 +36,6 @@ extern const char kChromeUIAutofillInternalsHost[];
extern const char kChromeUIBluetoothInternalsHost[];
extern const char kChromeUIBookmarksHost[];
extern const char kChromeUIBookmarksURL[];
-extern const char kChromeUICameraHost[];
extern const char kChromeUICertificateViewerHost[];
extern const char kChromeUICertificateViewerURL[];
extern const char kChromeUIChromeSigninHost[];
@@ -68,6 +67,7 @@ extern const char kChromeUIDownloadInternalsHost[];
extern const char kChromeUIDownloadsHost[];
extern const char kChromeUIDownloadsURL[];
extern const char kChromeUIDriveInternalsHost[];
+extern const char kChromeUIEDUCoexistenceLoginURL[];
extern const char kChromeUIExtensionIconHost[];
extern const char kChromeUIExtensionIconURL[];
extern const char kChromeUIExtensionsHost[];
@@ -89,19 +89,11 @@ extern const char kChromeUIHistoryURL[];
extern const char kChromeUIIdentityInternalsHost[];
extern const char kChromeUIInspectHost[];
extern const char kChromeUIInspectURL[];
+extern const char kChromeUIInternalsHost[];
extern const char kChromeUIInterstitialHost[];
extern const char kChromeUIInterstitialURL[];
extern const char kChromeUIInterventionsInternalsHost[];
extern const char kChromeUIInvalidationsHost[];
-
-// |kChromeUIKaleidoscopeHost| and |kChromeUIKaleidoscopeContentHost| are used
-// in the public repo, so are defined here. We only use the URL constants in the
-// internal repo, but they are defined here to be near the host constants.
-extern const char kChromeUIKaleidoscopeHost[];
-extern const char kChromeUIKaleidoscopeURL[];
-extern const char kChromeUIKaleidoscopeContentHost[];
-extern const char kChromeUIKaleidoscopeContentURL[];
-
extern const char kChromeUIKillHost[];
extern const char kChromeUILocalStateHost[];
extern const char kChromeUIManagementHost[];
@@ -149,6 +141,8 @@ extern const char kChromeUISigninEmailConfirmationHost[];
extern const char kChromeUISigninEmailConfirmationURL[];
extern const char kChromeUISigninErrorHost[];
extern const char kChromeUISigninErrorURL[];
+extern const char kChromeUISigninReauthHost[];
+extern const char kChromeUISigninReauthURL[];
extern const char kChromeUISiteDetailsPrefixURL[];
extern const char kChromeUISiteEngagementHost[];
extern const char kChromeUISuggestionsHost[];
@@ -171,7 +165,6 @@ extern const char kChromeUIThumbnailHost[];
extern const char kChromeUIThumbnailListHost[];
extern const char kChromeUIThumbnailURL[];
extern const char kChromeUITranslateInternalsHost[];
-extern const char kChromeUIUkmHost[];
extern const char kChromeUIUsbInternalsHost[];
extern const char kChromeUIUserActionsHost[];
extern const char kChromeUIVersionHost[];
@@ -195,6 +188,8 @@ extern const char kChromeUINativeHistoryURL[];
extern const char kChromeUINativeNewTabURL[];
extern const char kChromeUISnippetsInternalsHost[];
extern const char kChromeUIWebApksHost[];
+#else
+extern const char kChromeUINearbyInternalsHost[];
#endif // defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
@@ -288,9 +283,13 @@ extern const char kChromeUIDiscardsURL[];
extern const char kChromeUIHatsHost[];
extern const char kChromeUIHatsURL[];
extern const char kChromeUIProfilePickerHost[];
-
#endif
+#if !defined(OS_ANDROID)
+extern const char kChromeUINearbyShareHost[];
+extern const char kChromeUINearbyShareURL[];
+#endif // !defined(OS_CHROMEOS)
+
#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
extern const char kChromeUILinuxProxyConfigHost[];
#endif
@@ -318,6 +317,11 @@ extern const char kChromeUITabStripHost[];
extern const char kChromeUITabStripURL[];
#endif
+#if !defined(OS_ANDROID)
+extern const char kChromeUITabSearchHost[];
+extern const char kChromeUITabSearchURL[];
+#endif
+
extern const char kChromeUIWebRtcLogsHost[];
// Settings sub-pages.